From a4d7f672c67da0f63f398588cde2bc5f6643537d Mon Sep 17 00:00:00 2001 From: Andrey Litvitski Date: Tue, 21 Jul 2026 21:52:26 +0300 Subject: [PATCH] lil tests --- .../manifest.yaml | 534 +++--- .../sol.cpp | 18 +- .../sol.cs | 2 +- .../sol.dart | 7 +- .../sol.go | 6 +- .../sol.rb | 4 +- .../sol.rs | 10 +- .../sol.swift | 4 +- .../manifest.yaml | 251 +++ .../1125. smallest-sufficient-team/sol.cpp | 114 +- .../1125. smallest-sufficient-team/sol.cs | 130 +- .../1125. smallest-sufficient-team/sol.dart | 101 +- .../1125. smallest-sufficient-team/sol.go | 125 +- .../1125. smallest-sufficient-team/sol.java | 106 +- .../1125. smallest-sufficient-team/sol.kt | 39 +- .../1125. smallest-sufficient-team/sol.py | 2 +- .../1125. smallest-sufficient-team/sol.py2 | 65 +- .../1125. smallest-sufficient-team/sol.rb | 81 +- .../1125. smallest-sufficient-team/sol.rs | 112 +- .../1125. smallest-sufficient-team/sol.swift | 78 +- .../1125. smallest-sufficient-team/sol.ts | 91 +- .../manifest.yaml | 598 ++++--- .../sol.dart | 2 +- .../sol.py2 | 4 - .../sol.swift | 2 +- .../sol.ts | 2 +- .../manifest.yaml | 953 ++++------ .../sol.cpp | 18 +- .../sol.cs | 19 +- .../sol.dart | 17 +- .../sol.go | 29 +- .../sol.java | 67 +- .../sol.kt | 26 +- .../sol.py | 1 - .../sol.py2 | 2 +- .../sol.rb | 4 +- .../sol.rs | 31 +- .../sol.swift | 15 +- .../sol.ts | 7 +- .../manifest.yaml | 272 +++ .../sol.cpp | 26 + .../sol.cs | 23 + .../sol.dart | 22 + .../sol.go | 23 + .../sol.java | 23 + .../sol.kt | 23 + .../sol.py | 18 + .../sol.py2 | 21 + .../sol.rb | 22 + .../sol.rs | 22 + .../sol.swift | 22 + .../sol.ts | 20 + .../manifest.yaml | 335 ++++ .../sol.cpp | 21 + .../sol.cs | 22 + .../sol.dart | 21 + .../sol.go | 25 + .../sol.java | 21 + .../sol.kt | 22 + .../sol.py | 20 + .../sol.py2 | 20 + .../sol.rb | 20 + .../sol.rs | 20 + .../sol.swift | 20 + .../sol.ts | 23 + .../manifest.yaml | 200 +++ .../1137. n-th-tribonacci-number/sol.cpp | 13 + .../1137. n-th-tribonacci-number/sol.cs | 12 + .../1137. n-th-tribonacci-number/sol.dart | 12 + .../1137. n-th-tribonacci-number/sol.go | 10 + .../1137. n-th-tribonacci-number/sol.java | 12 + .../1137. n-th-tribonacci-number/sol.kt | 14 + .../1137. n-th-tribonacci-number/sol.py | 12 + .../1137. n-th-tribonacci-number/sol.py2 | 9 + .../1137. n-th-tribonacci-number/sol.rb | 12 + .../1137. n-th-tribonacci-number/sol.rs | 14 + .../1137. n-th-tribonacci-number/sol.swift | 12 + .../1137. n-th-tribonacci-number/sol.ts | 12 + .../1138. alphabet-board-path/manifest.yaml | 207 +++ .../1138. alphabet-board-path/sol.cpp | 54 + .../1138. alphabet-board-path/sol.cs | 53 + .../1138. alphabet-board-path/sol.dart | 53 + .../1138. alphabet-board-path/sol.go | 77 + .../1138. alphabet-board-path/sol.java | 53 + .../1138. alphabet-board-path/sol.kt | 51 + .../1138. alphabet-board-path/sol.py | 57 + .../1138. alphabet-board-path/sol.py2 | 46 + .../1138. alphabet-board-path/sol.rb | 54 + .../1138. alphabet-board-path/sol.rs | 51 + .../1138. alphabet-board-path/sol.swift | 50 + .../1138. alphabet-board-path/sol.ts | 56 + .../manifest.yaml | 459 +++++ .../1139. largest-1-bordered-square/sol.cpp | 29 + .../1139. largest-1-bordered-square/sol.cs | 32 + .../1139. largest-1-bordered-square/sol.dart | 37 + .../1139. largest-1-bordered-square/sol.go | 43 + .../1139. largest-1-bordered-square/sol.java | 28 + .../1139. largest-1-bordered-square/sol.kt | 29 + .../1139. largest-1-bordered-square/sol.py | 19 + .../1139. largest-1-bordered-square/sol.py2 | 23 + .../1139. largest-1-bordered-square/sol.rb | 29 + .../1139. largest-1-bordered-square/sol.rs | 29 + .../1139. largest-1-bordered-square/sol.swift | 31 + .../1139. largest-1-bordered-square/sol.ts | 27 + .../1140. stone-game-ii/manifest.yaml | 261 +++ tests/1001-1500/1140. stone-game-ii/sol.cpp | 24 + tests/1001-1500/1140. stone-game-ii/sol.cs | 27 + tests/1001-1500/1140. stone-game-ii/sol.dart | 25 + tests/1001-1500/1140. stone-game-ii/sol.go | 43 + tests/1001-1500/1140. stone-game-ii/sol.java | 30 + tests/1001-1500/1140. stone-game-ii/sol.kt | 23 + tests/1001-1500/1140. stone-game-ii/sol.py | 21 + tests/1001-1500/1140. stone-game-ii/sol.py2 | 21 + tests/1001-1500/1140. stone-game-ii/sol.rb | 24 + tests/1001-1500/1140. stone-game-ii/sol.rs | 29 + tests/1001-1500/1140. stone-game-ii/sol.swift | 23 + tests/1001-1500/1140. stone-game-ii/sol.ts | 23 + .../manifest.yaml | 288 +++ .../1143. longest-common-subsequence/sol.cpp | 22 + .../1143. longest-common-subsequence/sol.cs | 25 + .../1143. longest-common-subsequence/sol.dart | 23 + .../1143. longest-common-subsequence/sol.go | 34 + .../1143. longest-common-subsequence/sol.java | 26 + .../1143. longest-common-subsequence/sol.kt | 21 + .../1143. longest-common-subsequence/sol.py | 25 + .../1143. longest-common-subsequence/sol.py2 | 22 + .../1143. longest-common-subsequence/sol.rb | 21 + .../1143. longest-common-subsequence/sol.rs | 26 + .../sol.swift | 23 + .../1143. longest-common-subsequence/sol.ts | 19 + .../manifest.yaml | 250 +++ .../sol.cpp | 23 + .../sol.cs | 22 + .../sol.dart | 22 + .../sol.go | 33 + .../sol.java | 22 + .../sol.kt | 22 + .../sol.py | 16 + .../sol.py2 | 20 + .../sol.rb | 22 + .../sol.rs | 22 + .../sol.swift | 22 + .../sol.ts | 20 + .../manifest.yaml | 966 ++++++++++ .../1145. binary-tree-coloring-game/sol.cpp | 44 + .../1145. binary-tree-coloring-game/sol.cs | 44 + .../1145. binary-tree-coloring-game/sol.dart | 43 + .../1145. binary-tree-coloring-game/sol.go | 48 + .../1145. binary-tree-coloring-game/sol.java | 46 + .../1145. binary-tree-coloring-game/sol.kt | 41 + .../1145. binary-tree-coloring-game/sol.py | 43 + .../1145. binary-tree-coloring-game/sol.py2 | 44 + .../1145. binary-tree-coloring-game/sol.rb | 45 + .../1145. binary-tree-coloring-game/sol.rs | 66 + .../1145. binary-tree-coloring-game/sol.swift | 49 + .../1145. binary-tree-coloring-game/sol.ts | 46 + .../manifest.yaml | 223 +++ .../sol.cpp | 20 + .../sol.cs | 19 + .../sol.dart | 19 + .../sol.go | 20 + .../sol.java | 19 + .../sol.kt | 22 + .../sol.py | 19 + .../sol.py2 | 18 + .../sol.rb | 19 + .../sol.rs | 23 + .../sol.swift | 20 + .../sol.ts | 20 + .../1154. day-of-the-year/manifest.yaml | 207 +++ tests/1001-1500/1154. day-of-the-year/sol.cpp | 19 + tests/1001-1500/1154. day-of-the-year/sol.cs | 18 + .../1001-1500/1154. day-of-the-year/sol.dart | 18 + tests/1001-1500/1154. day-of-the-year/sol.go | 16 + .../1001-1500/1154. day-of-the-year/sol.java | 15 + tests/1001-1500/1154. day-of-the-year/sol.kt | 18 + tests/1001-1500/1154. day-of-the-year/sol.py | 27 + tests/1001-1500/1154. day-of-the-year/sol.py2 | 15 + tests/1001-1500/1154. day-of-the-year/sol.rb | 13 + tests/1001-1500/1154. day-of-the-year/sol.rs | 19 + .../1001-1500/1154. day-of-the-year/sol.swift | 18 + tests/1001-1500/1154. day-of-the-year/sol.ts | 26 + .../manifest.yaml | 331 ++++ .../sol.cpp | 28 + .../sol.cs | 27 + .../sol.dart | 27 + .../sol.go | 25 + .../sol.java | 27 + .../sol.kt | 27 + .../sol.py | 28 + .../sol.py2 | 28 + .../sol.rb | 29 + .../sol.rs | 30 + .../sol.swift | 27 + .../sol.ts | 25 + .../manifest.yaml | 221 +++ .../sol.cpp | 33 + .../sol.cs | 38 + .../sol.dart | 35 + .../sol.go | 36 + .../sol.java | 34 + .../sol.kt | 34 + .../sol.py | 25 + .../sol.py2 | 27 + .../sol.rb | 30 + .../sol.rs | 35 + .../sol.swift | 33 + .../sol.ts | 30 + .../manifest.yaml | 320 ++++ .../sol.cpp | 26 + .../sol.cs | 29 + .../sol.dart | 25 + .../sol.go | 31 + .../sol.java | 25 + .../sol.kt | 25 + .../sol.py | 21 + .../sol.py2 | 22 + .../sol.rb | 26 + .../sol.rs | 33 + .../sol.swift | 25 + .../sol.ts | 23 + .../manifest.yaml | 322 ++++ .../sol.cpp | 38 + .../sol.cs | 38 + .../sol.dart | 33 + .../sol.go | 35 + .../sol.java | 40 + .../sol.kt | 35 + .../sol.py | 30 + .../sol.py2 | 30 + .../sol.rb | 33 + .../sol.rs | 48 + .../sol.swift | 39 + .../sol.ts | 36 + .../manifest.yaml | 505 ++++++ .../sol.cpp | 48 + .../1162. as-far-from-land-as-possible/sol.cs | 46 + .../sol.dart | 48 + .../1162. as-far-from-land-as-possible/sol.go | 44 + .../sol.java | 47 + .../1162. as-far-from-land-as-possible/sol.kt | 46 + .../1162. as-far-from-land-as-possible/sol.py | 39 + .../sol.py2 | 38 + .../1162. as-far-from-land-as-possible/sol.rb | 39 + .../1162. as-far-from-land-as-possible/sol.rs | 52 + .../sol.swift | 47 + .../1162. as-far-from-land-as-possible/sol.ts | 49 + .../manifest.yaml | 232 +++ .../sol.cpp | 20 + .../sol.cs | 19 + .../sol.dart | 19 + .../sol.go | 17 + .../sol.java | 19 + .../sol.kt | 25 + .../sol.py | 15 + .../sol.py2 | 18 + .../sol.rb | 18 + .../sol.rs | 20 + .../sol.swift | 20 + .../sol.ts | 19 + .../1169. invalid-transactions/manifest.yaml | 185 ++ .../1169. invalid-transactions/sol.cpp | 61 + .../1169. invalid-transactions/sol.cs | 51 + .../1169. invalid-transactions/sol.dart | 45 + .../1169. invalid-transactions/sol.go | 53 + .../1169. invalid-transactions/sol.java | 47 + .../1169. invalid-transactions/sol.kt | 46 + .../1169. invalid-transactions/sol.py | 39 + .../1169. invalid-transactions/sol.py2 | 42 + .../1169. invalid-transactions/sol.rb | 48 + .../1169. invalid-transactions/sol.rs | 56 + .../1169. invalid-transactions/sol.swift | 44 + .../1169. invalid-transactions/sol.ts | 45 + .../manifest.yaml | 409 +++++ .../sol.cpp | 32 + .../sol.cs | 31 + .../sol.dart | 27 + .../sol.go | 29 + .../sol.java | 30 + .../sol.kt | 26 + .../sol.py | 32 + .../sol.py2 | 26 + .../sol.rb | 29 + .../sol.rs | 27 + .../sol.swift | 27 + .../sol.ts | 25 + .../manifest.yaml | 260 +++ .../sol.cpp | 36 + .../sol.cs | 36 + .../sol.dart | 33 + .../sol.go | 29 + .../sol.java | 35 + .../sol.kt | 34 + .../sol.py | 30 + .../sol.py2 | 30 + .../sol.rb | 33 + .../sol.rs | 34 + .../sol.swift | 35 + .../sol.ts | 35 + .../1175. prime-arrangements/manifest.yaml | 224 +++ .../1175. prime-arrangements/sol.cpp | 47 + .../1001-1500/1175. prime-arrangements/sol.cs | 41 + .../1175. prime-arrangements/sol.dart | 43 + .../1001-1500/1175. prime-arrangements/sol.go | 39 + .../1175. prime-arrangements/sol.java | 37 + .../1001-1500/1175. prime-arrangements/sol.kt | 38 + .../1001-1500/1175. prime-arrangements/sol.py | 32 + .../1175. prime-arrangements/sol.py2 | 24 + .../1001-1500/1175. prime-arrangements/sol.rb | 45 + .../1001-1500/1175. prime-arrangements/sol.rs | 42 + .../1175. prime-arrangements/sol.swift | 52 + .../1001-1500/1175. prime-arrangements/sol.ts | 32 + .../manifest.yaml | 504 ++++++ .../sol.cpp | 31 + .../sol.cs | 34 + .../sol.dart | 30 + .../sol.go | 32 + .../sol.java | 30 + .../sol.kt | 26 + .../sol.py | 21 + .../sol.py2 | 26 + .../sol.rb | 27 + .../sol.rs | 31 + .../sol.swift | 31 + .../sol.ts | 24 + .../manifest.yaml | 330 ++++ .../sol.cpp | 35 + .../sol.cs | 38 + .../sol.dart | 34 + .../sol.go | 34 + .../sol.java | 34 + .../sol.kt | 34 + .../sol.py | 41 + .../sol.py2 | 27 + .../sol.rb | 33 + .../sol.rs | 36 + .../sol.swift | 34 + .../sol.ts | 32 + .../manifest.yaml | 355 ++++ .../1184. distance-between-bus-stops/sol.cpp | 17 + .../1184. distance-between-bus-stops/sol.cs | 18 + .../1184. distance-between-bus-stops/sol.dart | 21 + .../1184. distance-between-bus-stops/sol.go | 17 + .../1184. distance-between-bus-stops/sol.java | 18 + .../1184. distance-between-bus-stops/sol.kt | 12 + .../1184. distance-between-bus-stops/sol.py | 10 + .../1184. distance-between-bus-stops/sol.py2 | 12 + .../1184. distance-between-bus-stops/sol.rb | 11 + .../1184. distance-between-bus-stops/sol.rs | 11 + .../sol.swift | 12 + .../1184. distance-between-bus-stops/sol.ts | 15 + .../1185. day-of-the-week/manifest.yaml | 307 ++++ tests/1001-1500/1185. day-of-the-week/sol.cpp | 29 + tests/1001-1500/1185. day-of-the-week/sol.cs | 40 + .../1001-1500/1185. day-of-the-week/sol.dart | 28 + tests/1001-1500/1185. day-of-the-week/sol.go | 33 + .../1001-1500/1185. day-of-the-week/sol.java | 40 + tests/1001-1500/1185. day-of-the-week/sol.kt | 31 + tests/1001-1500/1185. day-of-the-week/sol.py | 39 + tests/1001-1500/1185. day-of-the-week/sol.py2 | 44 + tests/1001-1500/1185. day-of-the-week/sol.rb | 39 + tests/1001-1500/1185. day-of-the-week/sol.rs | 30 + .../1001-1500/1185. day-of-the-week/sol.swift | 28 + tests/1001-1500/1185. day-of-the-week/sol.ts | 48 + .../manifest.yaml | 271 +++ .../sol.cpp | 22 + .../sol.cs | 21 + .../sol.dart | 22 + .../sol.go | 26 + .../sol.java | 21 + .../sol.kt | 21 + .../sol.py | 27 + .../sol.py2 | 21 + .../sol.rb | 19 + .../sol.rs | 21 + .../sol.swift | 21 + .../sol.ts | 19 + .../manifest.yaml | 311 ++++ .../sol.cpp | 30 + .../sol.cs | 42 + .../sol.dart | 42 + .../sol.go | 47 + .../sol.java | 43 + .../sol.kt | 43 + .../sol.py | 23 + .../sol.py2 | 32 + .../sol.rb | 32 + .../sol.rs | 56 + .../sol.swift | 42 + .../sol.ts | 41 + .../manifest.yaml | 216 +++ .../1189. maximum-number-of-balloons/sol.cpp | 10 + .../1189. maximum-number-of-balloons/sol.cs | 11 + .../1189. maximum-number-of-balloons/sol.dart | 9 + .../1189. maximum-number-of-balloons/sol.go | 7 + .../1189. maximum-number-of-balloons/sol.java | 9 + .../1189. maximum-number-of-balloons/sol.kt | 9 + .../1189. maximum-number-of-balloons/sol.py | 4 + .../1189. maximum-number-of-balloons/sol.py2 | 10 + .../1189. maximum-number-of-balloons/sol.rb | 7 + .../1189. maximum-number-of-balloons/sol.rs | 10 + .../sol.swift | 9 + .../1189. maximum-number-of-balloons/sol.ts | 13 + .../manifest.yaml | 206 +++ .../sol.cpp | 28 + .../sol.cs | 27 + .../sol.dart | 25 + .../sol.go | 29 + .../sol.java | 25 + .../sol.kt | 29 + .../sol.py | 28 + .../sol.py2 | 31 + .../sol.rb | 23 + .../sol.rs | 24 + .../sol.swift | 25 + .../sol.ts | 22 + .../manifest.yaml | 317 ++++ .../1191. k-concatenation-maximum-sum/sol.cpp | 37 + .../1191. k-concatenation-maximum-sum/sol.cs | 35 + .../sol.dart | 33 + .../1191. k-concatenation-maximum-sum/sol.go | 47 + .../sol.java | 35 + .../1191. k-concatenation-maximum-sum/sol.kt | 28 + .../1191. k-concatenation-maximum-sum/sol.py | 22 + .../1191. k-concatenation-maximum-sum/sol.py2 | 23 + .../1191. k-concatenation-maximum-sum/sol.rb | 23 + .../1191. k-concatenation-maximum-sum/sol.rs | 34 + .../sol.swift | 31 + .../1191. k-concatenation-maximum-sum/sol.ts | 29 + .../manifest.yaml | 552 ++++++ .../sol.cpp | 52 + .../sol.cs | 56 + .../sol.dart | 58 + .../sol.go | 69 + .../sol.java | 64 + .../sol.kt | 59 + .../sol.py | 72 + .../sol.py2 | 49 + .../sol.rb | 52 + .../sol.rs | 63 + .../sol.swift | 58 + .../sol.ts | 54 + .../manifest.yaml | 324 ++++ .../1200. minimum-absolute-difference/sol.cpp | 17 + .../1200. minimum-absolute-difference/sol.cs | 16 + .../sol.dart | 19 + .../1200. minimum-absolute-difference/sol.go | 17 + .../sol.java | 16 + .../1200. minimum-absolute-difference/sol.kt | 16 + .../1200. minimum-absolute-difference/sol.py | 8 + .../1200. minimum-absolute-difference/sol.py2 | 9 + .../1200. minimum-absolute-difference/sol.rb | 11 + .../1200. minimum-absolute-difference/sol.rs | 11 + .../sol.swift | 16 + .../1200. minimum-absolute-difference/sol.ts | 14 + .../1201. ugly-number-iii/manifest.yaml | 397 ++++ tests/1001-1500/1201. ugly-number-iii/sol.cpp | 39 + tests/1001-1500/1201. ugly-number-iii/sol.cs | 38 + .../1001-1500/1201. ugly-number-iii/sol.dart | 38 + tests/1001-1500/1201. ugly-number-iii/sol.go | 38 + .../1001-1500/1201. ugly-number-iii/sol.java | 38 + tests/1001-1500/1201. ugly-number-iii/sol.kt | 44 + tests/1001-1500/1201. ugly-number-iii/sol.py | 28 + tests/1001-1500/1201. ugly-number-iii/sol.py2 | 44 + tests/1001-1500/1201. ugly-number-iii/sol.rb | 40 + tests/1001-1500/1201. ugly-number-iii/sol.rs | 42 + .../1001-1500/1201. ugly-number-iii/sol.swift | 42 + tests/1001-1500/1201. ugly-number-iii/sol.ts | 41 + .../manifest.yaml | 457 +++++ .../1202. smallest-string-with-swaps/sol.cpp | 42 + .../1202. smallest-string-with-swaps/sol.cs | 47 + .../1202. smallest-string-with-swaps/sol.dart | 43 + .../1202. smallest-string-with-swaps/sol.go | 47 + .../1202. smallest-string-with-swaps/sol.java | 50 + .../1202. smallest-string-with-swaps/sol.kt | 43 + .../1202. smallest-string-with-swaps/sol.py | 41 + .../1202. smallest-string-with-swaps/sol.py2 | 39 + .../1202. smallest-string-with-swaps/sol.rb | 37 + .../1202. smallest-string-with-swaps/sol.rs | 46 + .../sol.swift | 43 + .../1202. smallest-string-with-swaps/sol.ts | 44 + .../manifest.yaml | 428 +++++ .../sol.cpp | 59 + .../sol.cs | 62 + .../sol.dart | 55 + .../sol.go | 76 + .../sol.java | 33 + .../sol.kt | 52 + .../sol.py | 55 + .../sol.py2 | 47 + .../sol.rb | 55 + .../sol.rs | 75 + .../sol.swift | 59 + .../sol.ts | 72 + .../manifest.yaml | 281 +++ .../sol.cpp | 22 + .../1207. unique-number-of-occurrences/sol.cs | 20 + .../sol.dart | 20 + .../1207. unique-number-of-occurrences/sol.go | 18 + .../sol.java | 20 + .../1207. unique-number-of-occurrences/sol.kt | 20 + .../1207. unique-number-of-occurrences/sol.py | 15 + .../sol.py2 | 18 + .../1207. unique-number-of-occurrences/sol.rb | 20 + .../1207. unique-number-of-occurrences/sol.rs | 16 + .../sol.swift | 20 + .../1207. unique-number-of-occurrences/sol.ts | 18 + .../manifest.yaml | 327 ++++ .../sol.cpp | 18 + .../sol.cs | 17 + .../sol.dart | 17 + .../sol.go | 22 + .../sol.java | 17 + .../sol.kt | 19 + .../sol.py | 16 + .../sol.py2 | 18 + .../sol.rb | 17 + .../sol.rs | 22 + .../sol.swift | 20 + .../sol.ts | 17 + .../manifest.yaml | 283 +++ .../sol.cpp | 21 + .../sol.cs | 20 + .../sol.dart | 23 + .../sol.go | 25 + .../sol.java | 22 + .../sol.kt | 20 + .../sol.py | 14 + .../sol.py2 | 16 + .../sol.rb | 17 + .../sol.rs | 26 + .../sol.swift | 20 + .../sol.ts | 18 + .../manifest.yaml | 587 ++++++ .../sol.cpp | 62 + .../sol.cs | 60 + .../sol.dart | 77 + .../sol.go | 87 + .../sol.java | 63 + .../sol.kt | 61 + .../sol.py | 61 + .../sol.py2 | 48 + .../sol.rb | 62 + .../sol.rs | 57 + .../sol.swift | 64 + .../sol.ts | 63 + .../manifest.yaml | 234 +++ .../sol.cpp | 14 + .../sol.cs | 13 + .../sol.dart | 13 + .../sol.go | 14 + .../sol.java | 13 + .../sol.kt | 14 + .../sol.py | 10 + .../sol.py2 | 14 + .../sol.rb | 14 + .../sol.rs | 14 + .../sol.swift | 13 + .../sol.ts | 12 + .../manifest.yaml | 297 +++ .../sol.cpp | 18 + .../sol.cs | 17 + .../sol.dart | 17 + .../sol.go | 15 + .../sol.java | 19 + .../sol.kt | 13 + .../sol.py | 14 + .../sol.py2 | 14 + .../sol.rb | 14 + .../sol.rs | 16 + .../sol.swift | 17 + .../sol.ts | 17 + .../manifest.yaml | 501 ++++++ .../1219. path-with-maximum-gold/sol.cpp | 43 + .../1219. path-with-maximum-gold/sol.cs | 44 + .../1219. path-with-maximum-gold/sol.dart | 40 + .../1219. path-with-maximum-gold/sol.go | 46 + .../1219. path-with-maximum-gold/sol.java | 41 + .../1219. path-with-maximum-gold/sol.kt | 42 + .../1219. path-with-maximum-gold/sol.py | 33 + .../1219. path-with-maximum-gold/sol.py2 | 46 + .../1219. path-with-maximum-gold/sol.rb | 39 + .../1219. path-with-maximum-gold/sol.rs | 41 + .../1219. path-with-maximum-gold/sol.swift | 39 + .../1219. path-with-maximum-gold/sol.ts | 44 + .../manifest.yaml | 220 +++ .../1220. count-vowels-permutation/sol.cpp | 20 + .../1220. count-vowels-permutation/sol.cs | 19 + .../1220. count-vowels-permutation/sol.dart | 19 + .../1220. count-vowels-permutation/sol.go | 13 + .../1220. count-vowels-permutation/sol.java | 19 + .../1220. count-vowels-permutation/sol.kt | 23 + .../1220. count-vowels-permutation/sol.py | 11 + .../1220. count-vowels-permutation/sol.py2 | 16 + .../1220. count-vowels-permutation/sol.rb | 15 + .../1220. count-vowels-permutation/sol.rs | 23 + .../1220. count-vowels-permutation/sol.swift | 19 + .../1220. count-vowels-permutation/sol.ts | 21 + .../manifest.yaml | 205 +++ .../sol.cpp | 18 + .../sol.cs | 17 + .../sol.dart | 18 + .../sol.go | 15 + .../sol.java | 18 + .../sol.kt | 17 + .../sol.py | 12 + .../sol.py2 | 16 + .../sol.rb | 17 + .../sol.rs | 17 + .../sol.swift | 17 + .../sol.ts | 16 + .../manifest.yaml | 744 ++++++++ .../sol.cpp | 29 + .../sol.cs | 28 + .../sol.dart | 28 + .../sol.go | 31 + .../sol.java | 28 + .../sol.kt | 29 + .../sol.py | 30 + .../sol.py2 | 29 + .../sol.rb | 30 + .../sol.rs | 31 + .../sol.swift | 28 + .../sol.ts | 35 + .../1223. dice-roll-simulation/manifest.yaml | 299 ++++ .../1223. dice-roll-simulation/sol.cpp | 38 + .../1223. dice-roll-simulation/sol.cs | 37 + .../1223. dice-roll-simulation/sol.dart | 37 + .../1223. dice-roll-simulation/sol.go | 38 + .../1223. dice-roll-simulation/sol.java | 37 + .../1223. dice-roll-simulation/sol.kt | 36 + .../1223. dice-roll-simulation/sol.py | 37 + .../1223. dice-roll-simulation/sol.py2 | 32 + .../1223. dice-roll-simulation/sol.rb | 31 + .../1223. dice-roll-simulation/sol.rs | 38 + .../1223. dice-roll-simulation/sol.swift | 37 + .../1223. dice-roll-simulation/sol.ts | 35 + .../manifest.yaml | 276 +++ .../1224. maximum-equal-frequency/sol.cpp | 43 + .../1224. maximum-equal-frequency/sol.cs | 40 + .../1224. maximum-equal-frequency/sol.dart | 40 + .../1224. maximum-equal-frequency/sol.go | 42 + .../1224. maximum-equal-frequency/sol.java | 41 + .../1224. maximum-equal-frequency/sol.kt | 40 + .../1224. maximum-equal-frequency/sol.py | 31 + .../1224. maximum-equal-frequency/sol.py2 | 34 + .../1224. maximum-equal-frequency/sol.rb | 35 + .../1224. maximum-equal-frequency/sol.rs | 43 + .../1224. maximum-equal-frequency/sol.swift | 37 + .../1224. maximum-equal-frequency/sol.ts | 41 + .../manifest.yaml | 221 +++ .../sol.cpp | 6 + .../sol.cs | 5 + .../sol.dart | 5 + .../sol.go | 6 + .../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 | 414 +++++ .../sol.cpp | 37 + .../sol.cs | 36 + .../sol.dart | 36 + .../sol.go | 30 + .../sol.java | 36 + .../sol.kt | 36 + .../sol.py | 29 + .../sol.py2 | 28 + .../sol.rb | 28 + .../sol.rs | 36 + .../sol.swift | 36 + .../sol.ts | 34 + .../manifest.yaml | 346 ++++ .../sol.cpp | 20 + .../sol.cs | 19 + .../sol.dart | 19 + .../sol.go | 17 + .../sol.java | 19 + .../sol.kt | 19 + .../sol.py | 14 + .../sol.py2 | 18 + .../sol.rb | 19 + .../sol.rs | 20 + .../sol.swift | 21 + .../sol.ts | 21 + .../manifest.yaml | 220 +++ .../sol.cpp | 45 + .../sol.cs | 44 + .../sol.dart | 47 + .../sol.go | 52 + .../sol.java | 52 + .../sol.kt | 38 + .../sol.py | 27 + .../sol.py2 | 31 + .../sol.rb | 30 + .../sol.rs | 41 + .../sol.swift | 45 + .../sol.ts | 39 + .../manifest.yaml | 335 ++++ .../sol.cpp | 28 + .../sol.cs | 26 + .../sol.dart | 31 + .../sol.go | 31 + .../sol.java | 29 + .../sol.kt | 19 + .../sol.py | 48 + .../sol.py2 | 22 + .../sol.rb | 22 + .../sol.rs | 21 + .../sol.swift | 34 + .../sol.ts | 37 + .../manifest.yaml | 228 +++ .../sol.cpp | 10 + .../sol.cs | 9 + .../sol.dart | 6 + .../sol.go | 8 + .../sol.java | 9 + .../sol.kt | 5 + .../sol.py | 8 + .../sol.py2 | 8 + .../sol.rb | 6 + .../sol.rs | 5 + .../sol.swift | 9 + .../sol.ts | 7 + .../manifest.yaml | 344 ++++ .../sol.cpp | 28 + .../sol.cs | 26 + .../sol.dart | 34 + .../sol.go | 43 + .../sol.java | 35 + .../sol.kt | 18 + .../sol.py | 15 + .../sol.py2 | 18 + .../sol.rb | 18 + .../sol.rs | 36 + .../sol.swift | 26 + .../sol.ts | 28 + .../manifest.yaml | 290 +++ .../sol.cpp | 39 + .../sol.cs | 37 + .../sol.dart | 39 + .../sol.go | 45 + .../sol.java | 37 + .../sol.kt | 37 + .../sol.py | 34 + .../sol.py2 | 28 + .../sol.rb | 39 + .../sol.rs | 39 + .../sol.swift | 37 + .../sol.ts | 35 + .../manifest.yaml | 276 +++ .../sol.cpp | 21 + .../sol.cs | 20 + .../sol.dart | 20 + .../sol.go | 25 + .../sol.java | 24 + .../sol.kt | 16 + .../sol.py | 18 + .../sol.py2 | 23 + .../sol.rb | 21 + .../sol.rs | 30 + .../sol.swift | 22 + .../sol.ts | 18 + .../manifest.yaml | 316 ++++ .../sol.cpp | 15 + .../sol.cs | 19 + .../sol.dart | 13 + .../sol.go | 11 + .../sol.java | 14 + .../sol.kt | 13 + .../sol.py | 10 + .../sol.py2 | 15 + .../sol.rb | 14 + .../sol.rs | 15 + .../sol.swift | 13 + .../sol.ts | 12 + .../manifest.yaml | 212 +++ .../sol.cpp | 30 + .../sol.cs | 29 + .../sol.dart | 29 + .../sol.go | 36 + .../sol.java | 29 + .../sol.kt | 29 + .../sol.py | 22 + .../sol.py2 | 29 + .../sol.rb | 27 + .../sol.rs | 35 + .../sol.swift | 33 + .../sol.ts | 26 + .../manifest.yaml | 256 +++ .../1250. check-if-it-is-a-good-array/sol.cpp | 10 + .../1250. check-if-it-is-a-good-array/sol.cs | 18 + .../sol.dart | 18 + .../1250. check-if-it-is-a-good-array/sol.go | 14 + .../sol.java | 18 + .../1250. check-if-it-is-a-good-array/sol.kt | 20 + .../1250. check-if-it-is-a-good-array/sol.py | 7 + .../1250. check-if-it-is-a-good-array/sol.py2 | 14 + .../1250. check-if-it-is-a-good-array/sol.rb | 9 + .../1250. check-if-it-is-a-good-array/sol.rs | 18 + .../sol.swift | 20 + .../1250. check-if-it-is-a-good-array/sol.ts | 13 + .../manifest.yaml | 1020 +++++++++++ .../sol.cpp | 23 + .../sol.cs | 25 + .../sol.dart | 22 + .../sol.go | 23 + .../sol.java | 27 + .../sol.kt | 22 + .../sol.py | 19 + .../sol.py2 | 25 + .../sol.rb | 31 + .../sol.rs | 24 + .../sol.swift | 22 + .../sol.ts | 20 + .../manifest.yaml | 887 +++++++++ .../sol.cpp | 31 + .../sol.cs | 33 + .../sol.dart | 29 + .../sol.go | 35 + .../sol.java | 40 + .../sol.kt | 32 + .../sol.py | 24 + .../sol.py2 | 28 + .../sol.rb | 29 + .../sol.rs | 37 + .../sol.swift | 31 + .../sol.ts | 31 + .../manifest.yaml | 421 +++++ .../1254. number-of-closed-islands/sol.cpp | 31 + .../1254. number-of-closed-islands/sol.cs | 30 + .../1254. number-of-closed-islands/sol.dart | 32 + .../1254. number-of-closed-islands/sol.go | 34 + .../1254. number-of-closed-islands/sol.java | 31 + .../1254. number-of-closed-islands/sol.kt | 31 + .../1254. number-of-closed-islands/sol.py | 23 + .../1254. number-of-closed-islands/sol.py2 | 27 + .../1254. number-of-closed-islands/sol.rb | 29 + .../1254. number-of-closed-islands/sol.rs | 40 + .../1254. number-of-closed-islands/sol.swift | 31 + .../1254. number-of-closed-islands/sol.ts | 35 + .../manifest.yaml | 1589 +++++++++++++++++ .../sol.cpp | 44 + .../sol.cs | 44 + .../sol.dart | 42 + .../sol.go | 45 + .../sol.java | 43 + .../sol.kt | 24 + .../sol.py | 38 + .../sol.py2 | 41 + .../sol.rb | 45 + .../sol.rs | 43 + .../sol.swift | 43 + .../sol.ts | 45 + .../1260. shift-2d-grid/manifest.yaml | 1025 +++++++++++ tests/1001-1500/1260. shift-2d-grid/sol.cpp | 59 + tests/1001-1500/1260. shift-2d-grid/sol.cs | 66 + tests/1001-1500/1260. shift-2d-grid/sol.dart | 58 + tests/1001-1500/1260. shift-2d-grid/sol.go | 56 + tests/1001-1500/1260. shift-2d-grid/sol.java | 70 + tests/1001-1500/1260. shift-2d-grid/sol.kt | 57 + tests/1001-1500/1260. shift-2d-grid/sol.py | 61 + tests/1001-1500/1260. shift-2d-grid/sol.py2 | 53 + tests/1001-1500/1260. shift-2d-grid/sol.rb | 57 + tests/1001-1500/1260. shift-2d-grid/sol.rs | 59 + tests/1001-1500/1260. shift-2d-grid/sol.swift | 59 + tests/1001-1500/1260. shift-2d-grid/sol.ts | 56 + .../manifest.yaml | 269 +++ .../sol.cpp | 19 + .../sol.cs | 18 + .../sol.dart | 19 + .../sol.go | 23 + .../sol.java | 18 + .../sol.kt | 18 + .../sol.py | 12 + .../sol.py2 | 16 + .../sol.rb | 17 + .../sol.rs | 17 + .../sol.swift | 18 + .../sol.ts | 19 + .../manifest.yaml | 508 ++++++ .../sol.cpp | 58 + .../sol.cs | 59 + .../sol.dart | 56 + .../sol.go | 64 + .../sol.java | 56 + .../sol.kt | 60 + .../sol.py | 53 + .../sol.py2 | 49 + .../sol.rb | 59 + .../sol.rs | 71 + .../sol.swift | 53 + .../sol.ts | 75 + .../manifest.yaml | 480 +++++ .../sol.cpp | 13 + .../sol.cs | 12 + .../sol.dart | 11 + .../sol.go | 19 + .../sol.java | 12 + .../sol.kt | 12 + .../sol.py | 9 + .../sol.py2 | 13 + .../sol.rb | 12 + .../sol.rs | 11 + .../sol.swift | 11 + .../sol.ts | 10 + .../manifest.yaml | 401 +++++ .../sol.cpp | 26 + .../sol.cs | 25 + .../sol.dart | 25 + .../sol.go | 23 + .../sol.java | 25 + .../sol.kt | 25 + .../sol.py | 13 + .../sol.py2 | 15 + .../sol.rb | 11 + .../sol.rs | 25 + .../sol.swift | 25 + .../sol.ts | 23 + .../manifest.yaml | 525 ++++++ .../1268. search-suggestions-system/sol.cpp | 40 + .../1268. search-suggestions-system/sol.cs | 19 + .../1268. search-suggestions-system/sol.dart | 40 + .../1268. search-suggestions-system/sol.go | 41 + .../1268. search-suggestions-system/sol.java | 19 + .../1268. search-suggestions-system/sol.kt | 12 + .../1268. search-suggestions-system/sol.py | 33 + .../1268. search-suggestions-system/sol.py2 | 32 + .../1268. search-suggestions-system/sol.rb | 36 + .../1268. search-suggestions-system/sol.rs | 12 + .../1268. search-suggestions-system/sol.swift | 12 + .../1268. search-suggestions-system/sol.ts | 35 + .../manifest.yaml | 286 +++ .../sol.cpp | 20 + .../sol.cs | 19 + .../sol.dart | 19 + .../sol.go | 26 + .../sol.java | 19 + .../sol.kt | 19 + .../sol.py | 21 + .../sol.py2 | 23 + .../sol.rb | 20 + .../sol.rs | 25 + .../sol.swift | 19 + .../sol.ts | 17 + .../manifest.yaml | 473 +++++ .../sol.cpp | 27 + .../sol.cs | 32 + .../sol.dart | 26 + .../sol.go | 47 + .../sol.java | 31 + .../sol.kt | 27 + .../sol.py | 25 + .../sol.py2 | 22 + .../sol.rb | 25 + .../sol.rs | 27 + .../sol.swift | 26 + .../sol.ts | 35 + .../manifest.yaml | 279 +++ .../sol.cpp | 17 + .../sol.cs | 16 + .../sol.dart | 16 + .../sol.go | 14 + .../sol.java | 19 + .../sol.kt | 16 + .../sol.py | 17 + .../sol.py2 | 17 + .../sol.rb | 17 + .../sol.rs | 16 + .../sol.swift | 16 + .../sol.ts | 14 + .../manifest.yaml | 399 +++++ .../sol.cpp | 26 + .../sol.cs | 25 + .../sol.dart | 26 + .../sol.go | 22 + .../sol.java | 25 + .../sol.kt | 26 + .../sol.py | 18 + .../sol.py2 | 23 + .../sol.rb | 23 + .../sol.rs | 26 + .../sol.swift | 27 + .../sol.ts | 22 + .../manifest.yaml | 282 +++ .../1278. palindrome-partitioning-iii/sol.cpp | 28 + .../1278. palindrome-partitioning-iii/sol.cs | 32 + .../sol.dart | 27 + .../1278. palindrome-partitioning-iii/sol.go | 45 + .../sol.java | 32 + .../1278. palindrome-partitioning-iii/sol.kt | 27 + .../1278. palindrome-partitioning-iii/sol.py | 19 + .../1278. palindrome-partitioning-iii/sol.py2 | 24 + .../1278. palindrome-partitioning-iii/sol.rb | 28 + .../1278. palindrome-partitioning-iii/sol.rs | 29 + .../sol.swift | 32 + .../1278. palindrome-partitioning-iii/sol.ts | 27 + .../manifest.yaml | 228 +++ .../sol.cpp | 16 + .../sol.cs | 15 + .../sol.dart | 15 + .../sol.go | 13 + .../sol.java | 15 + .../sol.kt | 16 + .../sol.py | 12 + .../sol.py2 | 16 + .../sol.rb | 15 + .../sol.rs | 16 + .../sol.swift | 16 + .../sol.ts | 13 + .../manifest.yaml | 333 ++++ .../sol.cpp | 16 + .../sol.cs | 16 + .../sol.dart | 16 + .../sol.go | 12 + .../sol.java | 15 + .../sol.kt | 16 + .../sol.py | 11 + .../sol.py2 | 16 + .../sol.rb | 16 + .../sol.rs | 16 + .../sol.swift | 14 + .../sol.ts | 15 + .../manifest.yaml | 296 +++ .../sol.cpp | 26 + .../sol.cs | 25 + .../sol.dart | 25 + .../sol.go | 28 + .../sol.java | 28 + .../sol.kt | 25 + .../sol.py | 20 + .../sol.py2 | 25 + .../sol.rb | 26 + .../sol.rs | 25 + .../sol.swift | 25 + .../sol.ts | 23 + .../manifest.yaml | 393 ++++ .../sol.cpp | 65 + .../sol.cs | 72 + .../sol.dart | 59 + .../sol.go | 54 + .../sol.java | 60 + .../sol.kt | 64 + .../sol.py | 67 + .../sol.py2 | 41 + .../sol.rb | 48 + .../sol.rs | 54 + .../sol.swift | 56 + .../sol.ts | 57 + .../manifest.yaml | 628 +++++++ .../sol.cpp | 15 + .../sol.cs | 18 + .../sol.dart | 14 + .../sol.go | 12 + .../sol.java | 14 + .../sol.kt | 14 + .../sol.py | 10 + .../sol.py2 | 14 + .../sol.rb | 14 + .../sol.rs | 15 + .../sol.swift | 14 + .../sol.ts | 12 + .../manifest.yaml | 440 +++++ .../1288. remove-covered-intervals/sol.cpp | 16 + .../1288. remove-covered-intervals/sol.cs | 13 + .../1288. remove-covered-intervals/sol.dart | 13 + .../1288. remove-covered-intervals/sol.go | 18 + .../1288. remove-covered-intervals/sol.java | 13 + .../1288. remove-covered-intervals/sol.kt | 12 + .../1288. remove-covered-intervals/sol.py | 10 + .../1288. remove-covered-intervals/sol.py2 | 12 + .../1288. remove-covered-intervals/sol.rb | 14 + .../1288. remove-covered-intervals/sol.rs | 15 + .../1288. remove-covered-intervals/sol.swift | 15 + .../1288. remove-covered-intervals/sol.ts | 12 + .../manifest.yaml | 514 ++++++ .../1289. minimum-falling-path-sum-ii/sol.cpp | 27 + .../1289. minimum-falling-path-sum-ii/sol.cs | 26 + .../sol.dart | 25 + .../1289. minimum-falling-path-sum-ii/sol.go | 35 + .../sol.java | 30 + .../1289. minimum-falling-path-sum-ii/sol.kt | 25 + .../1289. minimum-falling-path-sum-ii/sol.py | 21 + .../1289. minimum-falling-path-sum-ii/sol.py2 | 20 + .../1289. minimum-falling-path-sum-ii/sol.rb | 23 + .../1289. minimum-falling-path-sum-ii/sol.rs | 32 + .../sol.swift | 24 + .../1289. minimum-falling-path-sum-ii/sol.ts | 23 + .../manifest.yaml | 427 +++++ .../sol.cpp | 21 + .../sol.cs | 21 + .../sol.dart | 18 + .../sol.go | 15 + .../sol.java | 20 + .../sol.kt | 20 + .../sol.py | 7 + .../sol.py2 | 16 + .../sol.rb | 18 + .../sol.rs | 27 + .../sol.swift | 21 + .../sol.ts | 20 + .../1291. sequential-digits/manifest.yaml | 343 ++++ .../1001-1500/1291. sequential-digits/sol.cpp | 23 + .../1001-1500/1291. sequential-digits/sol.cs | 22 + .../1291. sequential-digits/sol.dart | 16 + .../1001-1500/1291. sequential-digits/sol.go | 20 + .../1291. sequential-digits/sol.java | 24 + .../1001-1500/1291. sequential-digits/sol.kt | 18 + .../1001-1500/1291. sequential-digits/sol.py | 10 + .../1001-1500/1291. sequential-digits/sol.py2 | 13 + .../1001-1500/1291. sequential-digits/sol.rb | 13 + .../1001-1500/1291. sequential-digits/sol.rs | 15 + .../1291. sequential-digits/sol.swift | 18 + .../1001-1500/1291. sequential-digits/sol.ts | 14 + .../manifest.yaml | 651 +++++++ .../sol.cpp | 44 + .../sol.cs | 47 + .../sol.dart | 43 + .../sol.go | 53 + .../sol.java | 51 + .../sol.kt | 44 + .../sol.py | 51 + .../sol.py2 | 44 + .../sol.rb | 47 + .../sol.rs | 52 + .../sol.swift | 43 + .../sol.ts | 42 + .../manifest.yaml | 1104 ++++++++++++ .../sol.cpp | 27 + .../sol.cs | 27 + .../sol.dart | 34 + .../sol.go | 29 + .../sol.java | 27 + .../sol.kt | 29 + .../sol.py | 43 + .../sol.py2 | 25 + .../sol.rb | 25 + .../sol.rs | 33 + .../sol.swift | 29 + .../sol.ts | 30 + .../manifest.yaml | 282 +++ .../sol.cpp | 17 + .../sol.cs | 11 + .../sol.dart | 11 + .../sol.go | 17 + .../sol.java | 16 + .../sol.kt | 16 + .../sol.py | 11 + .../sol.py2 | 11 + .../sol.rb | 16 + .../sol.rs | 16 + .../sol.swift | 16 + .../sol.ts | 14 + .../manifest.yaml | 312 ++++ .../sol.cpp | 20 + .../sol.cs | 20 + .../sol.dart | 19 + .../sol.go | 23 + .../sol.java | 19 + .../sol.kt | 19 + .../sol.py | 18 + .../sol.py2 | 20 + .../sol.rb | 17 + .../sol.rs | 26 + .../sol.swift | 19 + .../sol.ts | 17 + .../manifest.yaml | 355 ++++ .../sol.cpp | 27 + .../sol.cs | 30 + .../sol.dart | 28 + .../sol.go | 26 + .../sol.java | 29 + .../sol.kt | 29 + .../sol.py | 22 + .../sol.py2 | 28 + .../sol.rb | 27 + .../sol.rs | 34 + .../sol.swift | 29 + .../sol.ts | 32 + .../manifest.yaml | 1013 +++++++++++ .../sol.cpp | 26 + .../sol.cs | 25 + .../sol.dart | 22 + .../sol.go | 27 + .../sol.java | 26 + .../sol.kt | 23 + .../sol.py | 18 + .../sol.py2 | 26 + .../sol.rb | 24 + .../sol.rs | 27 + .../sol.swift | 25 + .../sol.ts | 29 + .../manifest.yaml | 247 +++ .../sol.cpp | 12 + .../sol.cs | 11 + .../sol.dart | 13 + .../sol.go | 11 + .../sol.java | 11 + .../sol.kt | 11 + .../sol.py | 6 + .../sol.py2 | 10 + .../sol.rb | 9 + .../sol.rs | 12 + .../sol.swift | 12 + .../sol.ts | 9 + .../manifest.yaml | 333 ++++ .../sol.cpp | 36 + .../sol.cs | 35 + .../sol.dart | 35 + .../sol.go | 45 + .../sol.java | 34 + .../sol.kt | 27 + .../sol.py | 30 + .../sol.py2 | 29 + .../sol.rb | 32 + .../sol.rs | 31 + .../sol.swift | 31 + .../sol.ts | 29 + .../manifest.yaml | 486 +++++ .../sol.cpp | 62 + .../sol.cs | 67 + .../sol.dart | 64 + .../sol.go | 74 + .../sol.java | 67 + .../sol.kt | 61 + .../sol.py | 50 + .../sol.py2 | 57 + .../sol.rb | 48 + .../sol.rs | 63 + .../sol.swift | 63 + .../sol.ts | 59 + .../1302. deepest-leaves-sum/manifest.yaml | 335 ++++ .../1302. deepest-leaves-sum/sol.cpp | 33 + .../1001-1500/1302. deepest-leaves-sum/sol.cs | 37 + .../1302. deepest-leaves-sum/sol.dart | 28 + .../1001-1500/1302. deepest-leaves-sum/sol.go | 34 + .../1302. deepest-leaves-sum/sol.java | 32 + .../1001-1500/1302. deepest-leaves-sum/sol.kt | 28 + .../1001-1500/1302. deepest-leaves-sum/sol.py | 31 + .../1302. deepest-leaves-sum/sol.py2 | 26 + .../1001-1500/1302. deepest-leaves-sum/sol.rb | 27 + .../1001-1500/1302. deepest-leaves-sum/sol.rs | 39 + .../1302. deepest-leaves-sum/sol.swift | 33 + .../1001-1500/1302. deepest-leaves-sum/sol.ts | 35 + .../manifest.yaml | 181 ++ .../sol.cpp | 10 + .../sol.cs | 9 + .../sol.dart | 5 + .../sol.go | 7 + .../sol.java | 9 + .../sol.kt | 5 + .../sol.py | 3 + .../sol.py2 | 7 + .../sol.rb | 5 + .../sol.rs | 5 + .../sol.swift | 5 + .../sol.ts | 3 + .../manifest.yaml | 416 +++++ .../sol.cpp | 55 + .../sol.cs | 53 + .../sol.dart | 49 + .../sol.go | 50 + .../sol.java | 55 + .../sol.kt | 52 + .../sol.py | 45 + .../sol.py2 | 42 + .../sol.rb | 48 + .../sol.rs | 60 + .../sol.swift | 57 + .../sol.ts | 60 + .../1306. jump-game-iii/manifest.yaml | 316 ++++ tests/1001-1500/1306. jump-game-iii/sol.cpp | 22 + tests/1001-1500/1306. jump-game-iii/sol.cs | 20 + tests/1001-1500/1306. jump-game-iii/sol.dart | 21 + tests/1001-1500/1306. jump-game-iii/sol.go | 19 + tests/1001-1500/1306. jump-game-iii/sol.java | 20 + tests/1001-1500/1306. jump-game-iii/sol.kt | 20 + tests/1001-1500/1306. jump-game-iii/sol.py | 16 + tests/1001-1500/1306. jump-game-iii/sol.py2 | 21 + tests/1001-1500/1306. jump-game-iii/sol.rb | 22 + tests/1001-1500/1306. jump-game-iii/sol.rs | 25 + tests/1001-1500/1306. jump-game-iii/sol.swift | 21 + tests/1001-1500/1306. jump-game-iii/sol.ts | 19 + .../manifest.yaml | 295 +++ .../1307. verbal-arithmetic-puzzle/sol.cpp | 76 + .../1307. verbal-arithmetic-puzzle/sol.cs | 70 + .../1307. verbal-arithmetic-puzzle/sol.dart | 65 + .../1307. verbal-arithmetic-puzzle/sol.go | 90 + .../1307. verbal-arithmetic-puzzle/sol.java | 81 + .../1307. verbal-arithmetic-puzzle/sol.kt | 65 + .../1307. verbal-arithmetic-puzzle/sol.py | 52 + .../1307. verbal-arithmetic-puzzle/sol.py2 | 57 + .../1307. verbal-arithmetic-puzzle/sol.rb | 68 + .../1307. verbal-arithmetic-puzzle/sol.rs | 92 + .../1307. verbal-arithmetic-puzzle/sol.swift | 67 + .../1307. verbal-arithmetic-puzzle/sol.ts | 65 + .../manifest.yaml | 202 +++ .../sol.cpp | 19 + .../sol.cs | 18 + .../sol.dart | 18 + .../sol.go | 16 + .../sol.java | 18 + .../sol.kt | 18 + .../sol.py | 12 + .../sol.py2 | 12 + .../sol.rb | 16 + .../sol.rs | 19 + .../sol.swift | 20 + .../sol.ts | 16 + .../manifest.yaml | 487 +++++ .../1310. xor-queries-of-a-subarray/sol.cpp | 17 + .../1310. xor-queries-of-a-subarray/sol.cs | 15 + .../1310. xor-queries-of-a-subarray/sol.dart | 10 + .../1310. xor-queries-of-a-subarray/sol.go | 13 + .../1310. xor-queries-of-a-subarray/sol.java | 16 + .../1310. xor-queries-of-a-subarray/sol.kt | 10 + .../1310. xor-queries-of-a-subarray/sol.py | 7 + .../1310. xor-queries-of-a-subarray/sol.py2 | 11 + .../1310. xor-queries-of-a-subarray/sol.rb | 10 + .../1310. xor-queries-of-a-subarray/sol.rs | 17 + .../1310. xor-queries-of-a-subarray/sol.swift | 10 + .../1310. xor-queries-of-a-subarray/sol.ts | 8 + .../manifest.yaml | 983 ++++++++++ .../sol.cpp | 50 + .../sol.cs | 47 + .../sol.dart | 45 + .../sol.go | 47 + .../sol.java | 45 + .../sol.kt | 36 + .../sol.py | 38 + .../sol.py2 | 36 + .../sol.rb | 38 + .../sol.rs | 47 + .../sol.swift | 41 + .../sol.ts | 43 + .../manifest.yaml | 228 +++ .../sol.cpp | 19 + .../sol.cs | 19 + .../sol.dart | 17 + .../sol.go | 26 + .../sol.java | 17 + .../sol.kt | 17 + .../sol.py | 19 + .../sol.py2 | 16 + .../sol.rb | 17 + .../sol.rs | 19 + .../sol.swift | 19 + .../sol.ts | 17 + .../manifest.yaml | 1101 ++++++++++++ .../sol.cpp | 12 + .../sol.cs | 18 + .../sol.dart | 11 + .../sol.go | 11 + .../sol.java | 18 + .../sol.kt | 18 + .../sol.py | 7 + .../sol.py2 | 7 + .../sol.rb | 9 + .../sol.rs | 13 + .../sol.swift | 13 + .../sol.ts | 9 + .../1314. matrix-block-sum/manifest.yaml | 534 ++++++ .../1001-1500/1314. matrix-block-sum/sol.cpp | 33 + tests/1001-1500/1314. matrix-block-sum/sol.cs | 36 + .../1001-1500/1314. matrix-block-sum/sol.dart | 32 + tests/1001-1500/1314. matrix-block-sum/sol.go | 46 + .../1001-1500/1314. matrix-block-sum/sol.java | 32 + tests/1001-1500/1314. matrix-block-sum/sol.kt | 33 + tests/1001-1500/1314. matrix-block-sum/sol.py | 31 + .../1001-1500/1314. matrix-block-sum/sol.py2 | 36 + tests/1001-1500/1314. matrix-block-sum/sol.rb | 33 + tests/1001-1500/1314. matrix-block-sum/sol.rs | 34 + .../1314. matrix-block-sum/sol.swift | 32 + tests/1001-1500/1314. matrix-block-sum/sol.ts | 31 + .../manifest.yaml | 421 +++++ .../sol.cpp | 34 + .../sol.cs | 34 + .../sol.dart | 33 + .../sol.go | 34 + .../sol.java | 39 + .../sol.kt | 31 + .../sol.py | 24 + .../sol.py2 | 25 + .../sol.rb | 23 + .../sol.rs | 40 + .../sol.swift | 35 + .../sol.ts | 32 + .../manifest.yaml | 280 +++ .../1316. distinct-echo-substrings/sol.cpp | 36 + .../1316. distinct-echo-substrings/sol.cs | 38 + .../1316. distinct-echo-substrings/sol.dart | 40 + .../1316. distinct-echo-substrings/sol.go | 45 + .../1316. distinct-echo-substrings/sol.java | 42 + .../1316. distinct-echo-substrings/sol.kt | 36 + .../1316. distinct-echo-substrings/sol.py | 24 + .../1316. distinct-echo-substrings/sol.py2 | 28 + .../1316. distinct-echo-substrings/sol.rb | 33 + .../1316. distinct-echo-substrings/sol.rs | 38 + .../1316. distinct-echo-substrings/sol.swift | 42 + .../1316. distinct-echo-substrings/sol.ts | 13 + .../manifest.yaml | 183 ++ .../sol.cpp | 12 + .../sol.cs | 10 + .../sol.dart | 10 + .../sol.go | 18 + .../sol.java | 10 + .../sol.kt | 10 + .../sol.py | 7 + .../sol.py2 | 9 + .../sol.rb | 9 + .../sol.rs | 10 + .../sol.swift | 10 + .../sol.ts | 8 + .../manifest.yaml | 292 +++ .../sol.cpp | 23 + .../sol.cs | 22 + .../sol.dart | 21 + .../sol.go | 26 + .../sol.java | 22 + .../sol.kt | 25 + .../sol.py | 22 + .../sol.py2 | 28 + .../sol.rb | 24 + .../sol.rs | 25 + .../sol.swift | 25 + .../sol.ts | 20 + .../manifest.yaml | 849 +++++++++ .../sol.cpp | 54 + .../sol.cs | 54 + .../sol.dart | 50 + .../sol.go | 57 + .../sol.java | 54 + .../sol.kt | 40 + .../sol.py | 43 + .../sol.py2 | 39 + .../sol.rb | 41 + .../sol.rs | 52 + .../sol.swift | 50 + .../sol.ts | 46 + .../manifest.yaml | 192 ++ .../sol.cpp | 30 + .../sol.cs | 32 + .../sol.dart | 30 + .../sol.go | 39 + .../sol.java | 32 + .../sol.kt | 30 + .../sol.py | 22 + .../sol.py2 | 22 + .../sol.rb | 22 + .../sol.rs | 29 + .../sol.swift | 29 + .../sol.ts | 29 + .../1323. maximum-69-number/manifest.yaml | 199 +++ .../1001-1500/1323. maximum-69-number/sol.cpp | 11 + .../1001-1500/1323. maximum-69-number/sol.cs | 12 + .../1323. maximum-69-number/sol.dart | 7 + .../1001-1500/1323. maximum-69-number/sol.go | 6 + .../1323. maximum-69-number/sol.java | 7 + .../1001-1500/1323. maximum-69-number/sol.kt | 5 + .../1001-1500/1323. maximum-69-number/sol.py | 4 + .../1001-1500/1323. maximum-69-number/sol.py2 | 7 + .../1001-1500/1323. maximum-69-number/sol.rb | 5 + .../1001-1500/1323. maximum-69-number/sol.rs | 5 + .../1323. maximum-69-number/sol.swift | 9 + .../1001-1500/1323. maximum-69-number/sol.ts | 3 + .../manifest.yaml | 206 +++ .../1324. print-words-vertically/sol.cpp | 33 + .../1324. print-words-vertically/sol.cs | 24 + .../1324. print-words-vertically/sol.dart | 26 + .../1324. print-words-vertically/sol.go | 24 + .../1324. print-words-vertically/sol.java | 28 + .../1324. print-words-vertically/sol.kt | 19 + .../1324. print-words-vertically/sol.py | 22 + .../1324. print-words-vertically/sol.py2 | 18 + .../1324. print-words-vertically/sol.rb | 19 + .../1324. print-words-vertically/sol.rs | 20 + .../1324. print-words-vertically/sol.swift | 23 + .../1324. print-words-vertically/sol.ts | 22 + .../manifest.yaml | 347 ++++ .../sol.cpp | 38 + .../sol.cs | 39 + .../sol.dart | 35 + .../sol.go | 33 + .../sol.java | 41 + .../sol.kt | 36 + .../sol.py | 29 + .../sol.py2 | 32 + .../sol.rb | 28 + .../sol.rs | 57 + .../sol.swift | 41 + .../sol.ts | 41 + .../manifest.yaml | 316 ++++ .../sol.cpp | 31 + .../sol.cs | 30 + .../sol.dart | 30 + .../sol.go | 28 + .../sol.java | 30 + .../sol.kt | 32 + .../sol.py | 24 + .../sol.py2 | 29 + .../sol.rb | 31 + .../sol.rs | 33 + .../sol.swift | 30 + .../sol.ts | 30 + .../1328. break-a-palindrome/manifest.yaml | 207 +++ .../1328. break-a-palindrome/sol.cpp | 14 + .../1001-1500/1328. break-a-palindrome/sol.cs | 14 + .../1328. break-a-palindrome/sol.dart | 14 + .../1001-1500/1328. break-a-palindrome/sol.go | 14 + .../1328. break-a-palindrome/sol.java | 14 + .../1001-1500/1328. break-a-palindrome/sol.kt | 14 + .../1001-1500/1328. break-a-palindrome/sol.py | 12 + .../1328. break-a-palindrome/sol.py2 | 11 + .../1001-1500/1328. break-a-palindrome/sol.rb | 11 + .../1001-1500/1328. break-a-palindrome/sol.rs | 17 + .../1328. break-a-palindrome/sol.swift | 14 + .../1001-1500/1328. break-a-palindrome/sol.ts | 12 + .../manifest.yaml | 505 ++++++ .../1329. sort-the-matrix-diagonally/sol.cpp | 27 + .../1329. sort-the-matrix-diagonally/sol.cs | 32 + .../1329. sort-the-matrix-diagonally/sol.dart | 26 + .../1329. sort-the-matrix-diagonally/sol.go | 28 + .../1329. sort-the-matrix-diagonally/sol.java | 31 + .../1329. sort-the-matrix-diagonally/sol.kt | 27 + .../1329. sort-the-matrix-diagonally/sol.py | 28 + .../1329. sort-the-matrix-diagonally/sol.py2 | 24 + .../1329. sort-the-matrix-diagonally/sol.rb | 22 + .../1329. sort-the-matrix-diagonally/sol.rs | 30 + .../sol.swift | 26 + .../1329. sort-the-matrix-diagonally/sol.ts | 28 + .../manifest.yaml | 209 +++ .../sol.cpp | 23 + .../sol.cs | 22 + .../sol.dart | 25 + .../sol.go | 29 + .../sol.java | 22 + .../sol.kt | 22 + .../sol.py | 22 + .../sol.py2 | 20 + .../sol.rb | 22 + .../sol.rs | 26 + .../sol.swift | 24 + .../sol.ts | 24 + .../manifest.yaml | 246 +++ .../1331. rank-transform-of-an-array/sol.cpp | 31 + .../1331. rank-transform-of-an-array/sol.cs | 29 + .../1331. rank-transform-of-an-array/sol.dart | 28 + .../1331. rank-transform-of-an-array/sol.go | 28 + .../1331. rank-transform-of-an-array/sol.java | 30 + .../1331. rank-transform-of-an-array/sol.kt | 29 + .../1331. rank-transform-of-an-array/sol.py | 16 + .../1331. rank-transform-of-an-array/sol.py2 | 24 + .../1331. rank-transform-of-an-array/sol.rb | 29 + .../1331. rank-transform-of-an-array/sol.rs | 27 + .../sol.swift | 29 + .../1331. rank-transform-of-an-array/sol.ts | 27 + .../manifest.yaml | 198 ++ .../sol.cpp | 8 + .../sol.cs | 7 + .../sol.dart | 5 + .../sol.go | 8 + .../sol.java | 6 + .../sol.kt | 5 + .../sol.py | 3 + .../sol.py2 | 3 + .../sol.rb | 5 + .../sol.rs | 6 + .../sol.swift | 5 + .../sol.ts | 3 + .../manifest.yaml | 431 +++++ .../sol.cpp | 37 + .../sol.cs | 36 + .../sol.dart | 36 + .../sol.go | 34 + .../sol.java | 36 + .../sol.kt | 31 + .../sol.py | 32 + .../sol.py2 | 32 + .../sol.rb | 35 + .../sol.rs | 33 + .../sol.swift | 36 + .../sol.ts | 39 + .../manifest.yaml | 583 ++++++ .../sol.cpp | 44 + .../sol.cs | 47 + .../sol.dart | 44 + .../sol.go | 45 + .../sol.java | 46 + .../sol.kt | 46 + .../sol.py | 32 + .../sol.py2 | 33 + .../sol.rb | 37 + .../sol.rs | 42 + .../sol.swift | 44 + .../sol.ts | 47 + .../manifest.yaml | 297 +++ .../sol.cpp | 39 + .../sol.cs | 44 + .../sol.dart | 40 + .../sol.go | 48 + .../sol.java | 43 + .../sol.kt | 38 + .../sol.py | 36 + .../sol.py2 | 36 + .../sol.rb | 37 + .../sol.rs | 42 + .../sol.swift | 40 + .../sol.ts | 41 + .../manifest.yaml | 1559 ++++++++++++++++ .../sol.cpp | 20 + .../sol.cs | 14 + .../sol.dart | 12 + .../sol.go | 26 + .../sol.java | 20 + .../sol.kt | 12 + .../sol.py | 10 + .../sol.py2 | 7 + .../sol.rb | 10 + .../sol.rs | 11 + .../sol.swift | 12 + .../sol.ts | 10 + .../manifest.yaml | 299 ++++ .../sol.cpp | 26 + .../sol.cs | 26 + .../sol.dart | 22 + .../sol.go | 25 + .../sol.java | 22 + .../sol.kt | 21 + .../sol.py | 18 + .../sol.py2 | 20 + .../sol.rb | 17 + .../sol.rs | 23 + .../sol.swift | 21 + .../sol.ts | 19 + .../manifest.yaml | 547 ++++++ .../sol.cpp | 46 + .../sol.cs | 46 + .../sol.dart | 37 + .../sol.go | 45 + .../sol.java | 48 + .../sol.kt | 26 + .../sol.py | 24 + .../sol.py2 | 33 + .../sol.rb | 38 + .../sol.rs | 50 + .../sol.swift | 43 + .../sol.ts | 43 + .../1001-1500/1340. jump-game-v/manifest.yaml | 304 ++++ tests/1001-1500/1340. jump-game-v/sol.cpp | 34 + tests/1001-1500/1340. jump-game-v/sol.cs | 34 + tests/1001-1500/1340. jump-game-v/sol.dart | 36 + tests/1001-1500/1340. jump-game-v/sol.go | 58 + tests/1001-1500/1340. jump-game-v/sol.java | 37 + tests/1001-1500/1340. jump-game-v/sol.kt | 29 + tests/1001-1500/1340. jump-game-v/sol.py | 29 + tests/1001-1500/1340. jump-game-v/sol.py2 | 32 + tests/1001-1500/1340. jump-game-v/sol.rb | 30 + tests/1001-1500/1340. jump-game-v/sol.rs | 20 + tests/1001-1500/1340. jump-game-v/sol.swift | 43 + tests/1001-1500/1340. jump-game-v/sol.ts | 31 + .../manifest.yaml | 186 ++ .../sol.cpp | 7 + .../sol.cs | 14 + .../sol.dart | 14 + .../sol.go | 14 + .../sol.java | 6 + .../sol.kt | 6 + .../sol.py | 5 + .../sol.py2 | 13 + .../sol.rb | 6 + .../sol.rs | 8 + .../sol.swift | 6 + .../sol.ts | 6 + .../manifest.yaml | 299 ++++ .../sol.cpp | 19 + .../sol.cs | 18 + .../sol.dart | 18 + .../sol.go | 16 + .../sol.java | 18 + .../sol.kt | 18 + .../sol.py | 16 + .../sol.py2 | 19 + .../sol.rb | 18 + .../sol.rs | 19 + .../sol.swift | 18 + .../sol.ts | 16 + .../manifest.yaml | 245 +++ .../sol.cpp | 6 + .../sol.cs | 5 + .../sol.dart | 5 + .../sol.go | 3 + .../sol.java | 5 + .../sol.kt | 5 + .../sol.py | 6 + .../sol.py2 | 8 + .../sol.rb | 6 + .../sol.rs | 5 + .../sol.swift | 5 + .../sol.ts | 6 + .../1345. jump-game-iv/manifest.yaml | 252 +++ tests/1001-1500/1345. jump-game-iv/sol.cpp | 40 + tests/1001-1500/1345. jump-game-iv/sol.cs | 44 + tests/1001-1500/1345. jump-game-iv/sol.dart | 40 + tests/1001-1500/1345. jump-game-iv/sol.go | 41 + tests/1001-1500/1345. jump-game-iv/sol.java | 42 + tests/1001-1500/1345. jump-game-iv/sol.kt | 39 + tests/1001-1500/1345. jump-game-iv/sol.py | 40 + tests/1001-1500/1345. jump-game-iv/sol.py2 | 35 + tests/1001-1500/1345. jump-game-iv/sol.rb | 39 + tests/1001-1500/1345. jump-game-iv/sol.rs | 45 + tests/1001-1500/1345. jump-game-iv/sol.swift | 40 + tests/1001-1500/1345. jump-game-iv/sol.ts | 38 + .../manifest.yaml | 198 ++ .../sol.cpp | 19 + .../sol.cs | 18 + .../sol.dart | 12 + .../sol.go | 22 + .../sol.java | 18 + .../sol.kt | 12 + .../sol.py | 10 + .../sol.py2 | 10 + .../sol.rb | 13 + .../sol.rs | 14 + .../sol.swift | 14 + .../sol.ts | 10 + .../manifest.yaml | 269 +++ .../sol.cpp | 19 + .../sol.cs | 19 + .../sol.dart | 14 + .../sol.go | 16 + .../sol.java | 18 + .../sol.kt | 14 + .../sol.py | 12 + .../sol.py2 | 14 + .../sol.rb | 9 + .../sol.rs | 17 + .../sol.swift | 14 + .../sol.ts | 12 + .../manifest.yaml | 386 ++++ .../sol.cpp | 44 + .../1349. maximum-students-taking-exam/sol.cs | 54 + .../sol.dart | 44 + .../1349. maximum-students-taking-exam/sol.go | 58 + .../sol.java | 46 + .../1349. maximum-students-taking-exam/sol.kt | 33 + .../1349. maximum-students-taking-exam/sol.py | 29 + .../sol.py2 | 30 + .../1349. maximum-students-taking-exam/sol.rb | 33 + .../1349. maximum-students-taking-exam/sol.rs | 45 + .../sol.swift | 39 + .../1349. maximum-students-taking-exam/sol.ts | 38 + .../manifest.yaml | 540 ++++++ .../sol.cpp | 12 + .../sol.cs | 11 + .../sol.dart | 11 + .../sol.go | 11 + .../sol.java | 11 + .../sol.kt | 11 + .../sol.py | 9 + .../sol.py2 | 7 + .../sol.rb | 11 + .../sol.rs | 13 + .../sol.swift | 13 + .../sol.ts | 9 + .../manifest.yaml | 633 +++++++ .../sol.cpp | 25 + .../sol.cs | 17 + .../sol.dart | 26 + .../sol.go | 41 + .../sol.java | 24 + .../sol.kt | 27 + .../sol.py | 29 + .../sol.py2 | 26 + .../sol.rb | 28 + .../sol.rs | 35 + .../sol.swift | 28 + .../sol.ts | 16 + .../manifest.yaml | 262 +++ .../sol.cpp | 31 + .../sol.cs | 17 + .../sol.dart | 28 + .../sol.go | 39 + .../sol.java | 28 + .../sol.kt | 28 + .../sol.py | 23 + .../sol.py2 | 22 + .../sol.rb | 24 + .../sol.rs | 28 + .../sol.swift | 25 + .../sol.ts | 15 + .../manifest.yaml | 252 +++ .../sol.cpp | 12 + .../sol.cs | 16 + .../sol.dart | 11 + .../sol.go | 11 + .../sol.java | 12 + .../sol.kt | 5 + .../sol.py | 3 + .../sol.py2 | 7 + .../sol.rb | 5 + .../sol.rs | 15 + .../sol.swift | 10 + .../sol.ts | 8 + .../manifest.yaml | 205 +++ .../sol.cpp | 12 + .../sol.cs | 11 + .../sol.dart | 14 + .../sol.go | 12 + .../sol.java | 11 + .../sol.kt | 11 + .../sol.py | 9 + .../sol.py2 | 12 + .../sol.rb | 11 + .../sol.rs | 11 + .../sol.swift | 11 + .../sol.ts | 9 + .../manifest.yaml | 221 +++ .../sol.cpp | 11 + .../sol.cs | 10 + .../sol.dart | 10 + .../sol.go | 8 + .../sol.java | 10 + .../sol.kt | 10 + .../sol.py | 9 + .../sol.py2 | 11 + .../sol.rb | 10 + .../sol.rs | 10 + .../sol.swift | 12 + .../sol.ts | 8 + .../manifest.yaml | 205 +++ .../sol.cpp | 18 + .../sol.cs | 17 + .../sol.dart | 17 + .../sol.go | 25 + .../sol.java | 21 + .../sol.kt | 17 + .../sol.py | 8 + .../sol.py2 | 11 + .../sol.rb | 9 + .../sol.rs | 21 + .../sol.swift | 19 + .../sol.ts | 22 + .../manifest.yaml | 562 ++++++ .../1361. validate-binary-tree-nodes/sol.cpp | 43 + .../1361. validate-binary-tree-nodes/sol.cs | 41 + .../1361. validate-binary-tree-nodes/sol.dart | 40 + .../1361. validate-binary-tree-nodes/sol.go | 51 + .../1361. validate-binary-tree-nodes/sol.java | 43 + .../1361. validate-binary-tree-nodes/sol.kt | 41 + .../1361. validate-binary-tree-nodes/sol.py | 40 + .../1361. validate-binary-tree-nodes/sol.py2 | 40 + .../1361. validate-binary-tree-nodes/sol.rb | 39 + .../1361. validate-binary-tree-nodes/sol.rs | 56 + .../sol.swift | 40 + .../1361. validate-binary-tree-nodes/sol.ts | 42 + .../1362. closest-divisors/manifest.yaml | 192 ++ .../1001-1500/1362. closest-divisors/sol.cpp | 15 + tests/1001-1500/1362. closest-divisors/sol.cs | 14 + .../1001-1500/1362. closest-divisors/sol.dart | 16 + tests/1001-1500/1362. closest-divisors/sol.go | 12 + .../1001-1500/1362. closest-divisors/sol.java | 14 + tests/1001-1500/1362. closest-divisors/sol.kt | 14 + tests/1001-1500/1362. closest-divisors/sol.py | 22 + .../1001-1500/1362. closest-divisors/sol.py2 | 14 + tests/1001-1500/1362. closest-divisors/sol.rb | 14 + tests/1001-1500/1362. closest-divisors/sol.rs | 14 + .../1362. closest-divisors/sol.swift | 14 + tests/1001-1500/1362. closest-divisors/sol.ts | 12 + .../manifest.yaml | 239 +++ .../1363. largest-multiple-of-three/sol.cpp | 41 + .../1363. largest-multiple-of-three/sol.cs | 41 + .../1363. largest-multiple-of-three/sol.dart | 44 + .../1363. largest-multiple-of-three/sol.go | 44 + .../1363. largest-multiple-of-three/sol.java | 43 + .../1363. largest-multiple-of-three/sol.kt | 44 + .../1363. largest-multiple-of-three/sol.py | 24 + .../1363. largest-multiple-of-three/sol.py2 | 28 + .../1363. largest-multiple-of-three/sol.rb | 31 + .../1363. largest-multiple-of-three/sol.rs | 44 + .../1363. largest-multiple-of-three/sol.swift | 41 + .../1363. largest-multiple-of-three/sol.ts | 39 + .../manifest.yaml | 247 +++ .../sol.cpp | 25 + .../sol.cs | 24 + .../sol.dart | 24 + .../sol.go | 21 + .../sol.java | 24 + .../sol.kt | 24 + .../sol.py | 32 + .../sol.py2 | 22 + .../sol.rb | 23 + .../sol.rs | 23 + .../sol.swift | 23 + .../sol.ts | 22 + .../1366. rank-teams-by-votes/manifest.yaml | 234 +++ .../1366. rank-teams-by-votes/sol.cpp | 27 + .../1366. rank-teams-by-votes/sol.cs | 27 + .../1366. rank-teams-by-votes/sol.dart | 28 + .../1366. rank-teams-by-votes/sol.go | 27 + .../1366. rank-teams-by-votes/sol.java | 35 + .../1366. rank-teams-by-votes/sol.kt | 27 + .../1366. rank-teams-by-votes/sol.py | 15 + .../1366. rank-teams-by-votes/sol.py2 | 12 + .../1366. rank-teams-by-votes/sol.rb | 13 + .../1366. rank-teams-by-votes/sol.rs | 28 + .../1366. rank-teams-by-votes/sol.swift | 26 + .../1366. rank-teams-by-votes/sol.ts | 25 + .../manifest.yaml | 670 +++++++ .../1367. linked-list-in-binary-tree/sol.cpp | 35 + .../1367. linked-list-in-binary-tree/sol.cs | 36 + .../1367. linked-list-in-binary-tree/sol.dart | 29 + .../1367. linked-list-in-binary-tree/sol.go | 32 + .../1367. linked-list-in-binary-tree/sol.java | 37 + .../1367. linked-list-in-binary-tree/sol.kt | 31 + .../1367. linked-list-in-binary-tree/sol.py | 27 + .../1367. linked-list-in-binary-tree/sol.py2 | 28 + .../1367. linked-list-in-binary-tree/sol.rb | 30 + .../1367. linked-list-in-binary-tree/sol.rs | 63 + .../sol.swift | 37 + .../1367. linked-list-in-binary-tree/sol.ts | 45 + .../manifest.yaml | 769 ++++++++ .../sol.cpp | 37 + .../sol.cs | 45 + .../sol.dart | 42 + .../sol.go | 44 + .../sol.java | 42 + .../sol.kt | 40 + .../sol.py | 43 + .../sol.py2 | 38 + .../sol.rb | 39 + .../sol.rs | 39 + .../sol.swift | 34 + .../sol.ts | 45 + .../manifest.yaml | 241 +++ .../sol.cpp | 30 + .../1370. increasing-decreasing-string/sol.cs | 29 + .../sol.dart | 29 + .../1370. increasing-decreasing-string/sol.go | 31 + .../sol.java | 29 + .../1370. increasing-decreasing-string/sol.kt | 29 + .../1370. increasing-decreasing-string/sol.py | 21 + .../sol.py2 | 22 + .../1370. increasing-decreasing-string/sol.rb | 24 + .../1370. increasing-decreasing-string/sol.rs | 33 + .../sol.swift | 29 + .../1370. increasing-decreasing-string/sol.ts | 27 + .../manifest.yaml | 203 +++ .../sol.cpp | 26 + .../sol.cs | 25 + .../sol.dart | 27 + .../sol.go | 36 + .../sol.java | 25 + .../sol.kt | 26 + .../sol.py | 27 + .../sol.py2 | 31 + .../sol.rb | 33 + .../sol.rs | 32 + .../sol.swift | 37 + .../sol.ts | 25 + .../manifest.yaml | 298 ++++ .../sol.cpp | 32 + .../sol.cs | 32 + .../sol.dart | 31 + .../sol.go | 37 + .../sol.java | 37 + .../sol.kt | 25 + .../sol.py | 26 + .../sol.py2 | 24 + .../sol.rb | 27 + .../sol.rs | 38 + .../sol.swift | 33 + .../sol.ts | 30 + .../manifest.yaml | 324 ++++ .../sol.cpp | 39 + .../sol.cs | 41 + .../sol.dart | 40 + .../sol.go | 42 + .../sol.java | 46 + .../sol.kt | 47 + .../sol.py | 29 + .../sol.py2 | 30 + .../sol.rb | 32 + .../sol.rs | 46 + .../sol.swift | 43 + .../sol.ts | 39 + .../manifest.yaml | 223 +++ .../sol.cpp | 10 + .../sol.cs | 9 + .../sol.dart | 9 + .../sol.go | 7 + .../sol.java | 9 + .../sol.kt | 9 + .../sol.py | 6 + .../sol.py2 | 10 + .../sol.rb | 9 + .../sol.rs | 10 + .../sol.swift | 9 + .../sol.ts | 7 + .../manifest.yaml | 496 +++++ .../sol.cpp | 16 + .../sol.cs | 15 + .../sol.dart | 17 + .../sol.go | 15 + .../sol.java | 15 + .../sol.kt | 15 + .../sol.py | 18 + .../sol.py2 | 15 + .../sol.rb | 13 + .../sol.rs | 15 + .../sol.swift | 15 + .../sol.ts | 13 + .../manifest.yaml | 392 ++++ .../sol.cpp | 24 + .../sol.cs | 25 + .../sol.dart | 26 + .../sol.go | 25 + .../sol.java | 27 + .../sol.kt | 22 + .../sol.py | 19 + .../sol.py2 | 21 + .../sol.rb | 21 + .../sol.rs | 21 + .../sol.swift | 20 + .../sol.ts | 24 + .../manifest.yaml | 773 ++++++++ .../sol.cpp | 44 + .../sol.cs | 39 + .../sol.dart | 39 + .../sol.go | 42 + .../sol.java | 35 + .../sol.kt | 34 + .../sol.py | 29 + .../sol.py2 | 34 + .../sol.rb | 36 + .../sol.rs | 59 + .../sol.swift | 38 + .../sol.ts | 43 + .../manifest.yaml | 435 +++++ .../1380. lucky-numbers-in-a-matrix/sol.cpp | 24 + .../1380. lucky-numbers-in-a-matrix/sol.cs | 23 + .../1380. lucky-numbers-in-a-matrix/sol.dart | 23 + .../1380. lucky-numbers-in-a-matrix/sol.go | 25 + .../1380. lucky-numbers-in-a-matrix/sol.java | 23 + .../1380. lucky-numbers-in-a-matrix/sol.kt | 23 + .../1380. lucky-numbers-in-a-matrix/sol.py | 11 + .../1380. lucky-numbers-in-a-matrix/sol.py2 | 15 + .../1380. lucky-numbers-in-a-matrix/sol.rb | 17 + .../1380. lucky-numbers-in-a-matrix/sol.rs | 27 + .../1380. lucky-numbers-in-a-matrix/sol.swift | 27 + .../1380. lucky-numbers-in-a-matrix/sol.ts | 21 + .../manifest.yaml | 544 ++++++ .../sol.cpp | 36 + .../1382. balance-a-binary-search-tree/sol.cs | 36 + .../sol.dart | 32 + .../1382. balance-a-binary-search-tree/sol.go | 33 + .../sol.java | 38 + .../1382. balance-a-binary-search-tree/sol.kt | 33 + .../1382. balance-a-binary-search-tree/sol.py | 21 + .../sol.py2 | 31 + .../1382. balance-a-binary-search-tree/sol.rb | 32 + .../1382. balance-a-binary-search-tree/sol.rs | 44 + .../sol.swift | 38 + .../1382. balance-a-binary-search-tree/sol.ts | 42 + .../manifest.yaml | 438 +++++ .../sol.cpp | 29 + .../sol.cs | 34 + .../sol.dart | 72 + .../sol.go | 50 + .../sol.java | 26 + .../sol.kt | 22 + .../sol.py | 20 + .../sol.py2 | 22 + .../sol.rb | 46 + .../sol.rs | 24 + .../sol.swift | 71 + .../sol.ts | 82 + .../manifest.yaml | 354 ++++ .../sol.cpp | 15 + .../sol.cs | 40 + .../sol.dart | 40 + .../sol.go | 12 + .../sol.java | 40 + .../sol.kt | 42 + .../sol.py | 17 + .../sol.py2 | 17 + .../sol.rb | 14 + .../sol.rs | 15 + .../sol.swift | 40 + .../sol.ts | 44 + .../manifest.yaml | 436 +++++ .../1386. cinema-seat-allocation/sol.cpp | 53 + .../1386. cinema-seat-allocation/sol.cs | 36 + .../1386. cinema-seat-allocation/sol.dart | 33 + .../1386. cinema-seat-allocation/sol.go | 58 + .../1386. cinema-seat-allocation/sol.java | 35 + .../1386. cinema-seat-allocation/sol.kt | 31 + .../1386. cinema-seat-allocation/sol.py | 31 + .../1386. cinema-seat-allocation/sol.py2 | 30 + .../1386. cinema-seat-allocation/sol.rb | 32 + .../1386. cinema-seat-allocation/sol.rs | 35 + .../1386. cinema-seat-allocation/sol.swift | 33 + .../1386. cinema-seat-allocation/sol.ts | 32 + .../manifest.yaml | 303 ++++ .../sol.cpp | 24 + .../sol.cs | 23 + .../sol.dart | 23 + .../sol.go | 26 + .../sol.java | 27 + .../sol.kt | 20 + .../sol.py | 22 + .../sol.py2 | 21 + .../sol.rb | 22 + .../sol.rs | 20 + .../sol.swift | 25 + .../sol.ts | 21 + .../1388. pizza-with-3n-slices/manifest.yaml | 408 +++++ .../1388. pizza-with-3n-slices/sol.cpp | 20 + .../1388. pizza-with-3n-slices/sol.cs | 18 + .../1388. pizza-with-3n-slices/sol.dart | 22 + .../1388. pizza-with-3n-slices/sol.go | 36 + .../1388. pizza-with-3n-slices/sol.java | 18 + .../1388. pizza-with-3n-slices/sol.kt | 24 + .../1388. pizza-with-3n-slices/sol.py | 26 + .../1388. pizza-with-3n-slices/sol.py2 | 19 + .../1388. pizza-with-3n-slices/sol.rb | 20 + .../1388. pizza-with-3n-slices/sol.rs | 25 + .../1388. pizza-with-3n-slices/sol.swift | 19 + .../1388. pizza-with-3n-slices/sol.ts | 22 + .../manifest.yaml | 471 +++++ .../sol.cpp | 10 + .../sol.cs | 9 + .../sol.dart | 9 + .../sol.go | 9 + .../sol.java | 13 + .../sol.kt | 9 + .../sol.py | 9 + .../sol.py2 | 11 + .../sol.rb | 10 + .../sol.rs | 9 + .../sol.swift | 9 + .../sol.ts | 7 + .../1390. four-divisors/manifest.yaml | 266 +++ tests/1001-1500/1390. four-divisors/sol.cpp | 42 + tests/1001-1500/1390. four-divisors/sol.cs | 41 + tests/1001-1500/1390. four-divisors/sol.dart | 43 + tests/1001-1500/1390. four-divisors/sol.go | 49 + tests/1001-1500/1390. four-divisors/sol.java | 41 + tests/1001-1500/1390. four-divisors/sol.kt | 47 + tests/1001-1500/1390. four-divisors/sol.py | 51 + tests/1001-1500/1390. four-divisors/sol.py2 | 42 + tests/1001-1500/1390. four-divisors/sol.rb | 47 + tests/1001-1500/1390. four-divisors/sol.rs | 56 + tests/1001-1500/1390. four-divisors/sol.swift | 47 + tests/1001-1500/1390. four-divisors/sol.ts | 39 + .../manifest.yaml | 422 +++++ .../sol.cpp | 47 + .../sol.cs | 50 + .../sol.dart | 47 + .../sol.go | 47 + .../sol.java | 46 + .../sol.kt | 48 + .../sol.py | 35 + .../sol.py2 | 41 + .../sol.rb | 41 + .../sol.rs | 57 + .../sol.swift | 45 + .../sol.ts | 63 + .../1392. longest-happy-prefix/manifest.yaml | 221 +++ .../1392. longest-happy-prefix/sol.cpp | 18 + .../1392. longest-happy-prefix/sol.cs | 17 + .../1392. longest-happy-prefix/sol.dart | 17 + .../1392. longest-happy-prefix/sol.go | 15 + .../1392. longest-happy-prefix/sol.java | 17 + .../1392. longest-happy-prefix/sol.kt | 17 + .../1392. longest-happy-prefix/sol.py | 11 + .../1392. longest-happy-prefix/sol.py2 | 16 + .../1392. longest-happy-prefix/sol.rb | 17 + .../1392. longest-happy-prefix/sol.rs | 18 + .../1392. longest-happy-prefix/sol.swift | 18 + .../1392. longest-happy-prefix/sol.ts | 15 + .../manifest.yaml | 245 +++ .../sol.cpp | 18 + .../sol.cs | 23 + .../sol.dart | 19 + .../sol.go | 17 + .../sol.java | 19 + .../sol.kt | 17 + .../sol.py | 12 + .../sol.py2 | 16 + .../sol.rb | 15 + .../sol.rs | 19 + .../sol.swift | 17 + .../sol.ts | 15 + .../1395. count-number-of-teams/manifest.yaml | 260 +++ .../1395. count-number-of-teams/sol.cpp | 31 + .../1395. count-number-of-teams/sol.cs | 30 + .../1395. count-number-of-teams/sol.dart | 30 + .../1395. count-number-of-teams/sol.go | 28 + .../1395. count-number-of-teams/sol.java | 30 + .../1395. count-number-of-teams/sol.kt | 30 + .../1395. count-number-of-teams/sol.py | 108 ++ .../1395. count-number-of-teams/sol.py2 | 15 + .../1395. count-number-of-teams/sol.rb | 30 + .../1395. count-number-of-teams/sol.rs | 30 + .../1395. count-number-of-teams/sol.swift | 30 + .../1395. count-number-of-teams/sol.ts | 28 + .../1397. find-all-good-strings/manifest.yaml | 352 ++++ .../1397. find-all-good-strings/sol.cpp | 62 + .../1397. find-all-good-strings/sol.cs | 73 + .../1397. find-all-good-strings/sol.dart | 67 + .../1397. find-all-good-strings/sol.go | 82 + .../1397. find-all-good-strings/sol.java | 63 + .../1397. find-all-good-strings/sol.kt | 42 + .../1397. find-all-good-strings/sol.py | 55 + .../1397. find-all-good-strings/sol.py2 | 34 + .../1397. find-all-good-strings/sol.rb | 65 + .../1397. find-all-good-strings/sol.rs | 93 + .../1397. find-all-good-strings/sol.swift | 63 + .../1397. find-all-good-strings/sol.ts | 73 + .../1399. count-largest-group/manifest.yaml | 179 ++ .../1399. count-largest-group/sol.cpp | 30 + .../1399. count-largest-group/sol.cs | 32 + .../1399. count-largest-group/sol.dart | 31 + .../1399. count-largest-group/sol.go | 29 + .../1399. count-largest-group/sol.java | 28 + .../1399. count-largest-group/sol.kt | 30 + .../1399. count-largest-group/sol.py | 21 + .../1399. count-largest-group/sol.py2 | 21 + .../1399. count-largest-group/sol.rb | 27 + .../1399. count-largest-group/sol.rs | 31 + .../1399. count-largest-group/sol.swift | 30 + .../1399. count-largest-group/sol.ts | 27 + .../manifest.yaml | 244 +++ .../sol.cpp | 22 + .../sol.cs | 21 + .../sol.dart | 21 + .../sol.go | 19 + .../sol.java | 21 + .../sol.kt | 15 + .../sol.py | 11 + .../sol.py2 | 16 + .../sol.rb | 12 + .../sol.rs | 15 + .../sol.swift | 15 + .../sol.ts | 13 + .../manifest.yaml | 419 +++++ .../sol.cpp | 9 + .../sol.cs | 8 + .../sol.dart | 8 + .../sol.go | 6 + .../sol.java | 8 + .../sol.kt | 8 + .../sol.py | 16 + .../sol.py2 | 16 + .../sol.rb | 14 + .../sol.rs | 8 + .../sol.swift | 8 + .../sol.ts | 14 + .../1402. reducing-dishes/manifest.yaml | 236 +++ tests/1001-1500/1402. reducing-dishes/sol.cpp | 13 + tests/1001-1500/1402. reducing-dishes/sol.cs | 12 + .../1001-1500/1402. reducing-dishes/sol.dart | 12 + tests/1001-1500/1402. reducing-dishes/sol.go | 12 + .../1001-1500/1402. reducing-dishes/sol.java | 12 + tests/1001-1500/1402. reducing-dishes/sol.kt | 13 + tests/1001-1500/1402. reducing-dishes/sol.py | 14 + tests/1001-1500/1402. reducing-dishes/sol.py2 | 14 + tests/1001-1500/1402. reducing-dishes/sol.rb | 13 + tests/1001-1500/1402. reducing-dishes/sol.rs | 15 + .../1001-1500/1402. reducing-dishes/sol.swift | 12 + tests/1001-1500/1402. reducing-dishes/sol.ts | 11 + .../manifest.yaml | 261 +++ .../sol.cpp | 16 + .../sol.cs | 15 + .../sol.dart | 15 + .../sol.go | 16 + .../sol.java | 16 + .../sol.kt | 16 + .../sol.py | 10 + .../sol.py2 | 10 + .../sol.rb | 12 + .../sol.rs | 17 + .../sol.swift | 15 + .../sol.ts | 14 + .../manifest.yaml | 153 ++ .../sol.cpp | 20 + .../sol.cs | 19 + .../sol.dart | 19 + .../sol.go | 17 + .../sol.java | 19 + .../sol.kt | 19 + .../sol.py | 15 + .../sol.py2 | 19 + .../sol.rb | 19 + .../sol.rs | 20 + .../sol.swift | 20 + .../sol.ts | 17 + .../1405. longest-happy-string/manifest.yaml | 279 +++ .../1405. longest-happy-string/sol.cpp | 39 + .../1405. longest-happy-string/sol.cs | 19 + .../1405. longest-happy-string/sol.dart | 19 + .../1405. longest-happy-string/sol.go | 64 + .../1405. longest-happy-string/sol.java | 42 + .../1405. longest-happy-string/sol.kt | 37 + .../1405. longest-happy-string/sol.py | 29 + .../1405. longest-happy-string/sol.py2 | 33 + .../1405. longest-happy-string/sol.rb | 36 + .../1405. longest-happy-string/sol.rs | 19 + .../1405. longest-happy-string/sol.swift | 37 + .../1405. longest-happy-string/sol.ts | 22 + .../1406. stone-game-iii/manifest.yaml | 276 +++ tests/1001-1500/1406. stone-game-iii/sol.cpp | 32 + tests/1001-1500/1406. stone-game-iii/sol.cs | 31 + tests/1001-1500/1406. stone-game-iii/sol.dart | 31 + tests/1001-1500/1406. stone-game-iii/sol.go | 29 + tests/1001-1500/1406. stone-game-iii/sol.java | 31 + tests/1001-1500/1406. stone-game-iii/sol.kt | 29 + tests/1001-1500/1406. stone-game-iii/sol.py | 30 + tests/1001-1500/1406. stone-game-iii/sol.py2 | 29 + tests/1001-1500/1406. stone-game-iii/sol.rb | 31 + tests/1001-1500/1406. stone-game-iii/sol.rs | 31 + .../1001-1500/1406. stone-game-iii/sol.swift | 31 + tests/1001-1500/1406. stone-game-iii/sol.ts | 30 + .../manifest.yaml | 459 +++++ .../1408. string-matching-in-an-array/sol.cpp | 16 + .../1408. string-matching-in-an-array/sol.cs | 15 + .../sol.dart | 15 + .../1408. string-matching-in-an-array/sol.go | 13 + .../sol.java | 15 + .../1408. string-matching-in-an-array/sol.kt | 15 + .../1408. string-matching-in-an-array/sol.py | 12 + .../1408. string-matching-in-an-array/sol.py2 | 14 + .../1408. string-matching-in-an-array/sol.rb | 15 + .../1408. string-matching-in-an-array/sol.rs | 15 + .../sol.swift | 15 + .../1408. string-matching-in-an-array/sol.ts | 13 + .../manifest.yaml | 263 +++ .../sol.cpp | 23 + .../sol.cs | 17 + .../sol.dart | 13 + .../sol.go | 20 + .../sol.java | 17 + .../sol.kt | 17 + .../sol.py | 14 + .../sol.py2 | 16 + .../sol.rb | 13 + .../sol.rs | 13 + .../sol.swift | 13 + .../sol.ts | 14 + .../1410. html-entity-parser/manifest.yaml | 201 +++ .../1410. html-entity-parser/sol.cpp | 42 + .../1001-1500/1410. html-entity-parser/sol.cs | 20 + .../1410. html-entity-parser/sol.dart | 20 + .../1001-1500/1410. html-entity-parser/sol.go | 20 + .../1410. html-entity-parser/sol.java | 25 + .../1001-1500/1410. html-entity-parser/sol.kt | 20 + .../1001-1500/1410. html-entity-parser/sol.py | 21 + .../1410. html-entity-parser/sol.py2 | 23 + .../1001-1500/1410. html-entity-parser/sol.rb | 17 + .../1001-1500/1410. html-entity-parser/sol.rs | 62 + .../1410. html-entity-parser/sol.swift | 20 + .../1001-1500/1410. html-entity-parser/sol.ts | 17 + .../manifest.yaml | 182 ++ .../sol.cpp | 16 + .../sol.cs | 15 + .../sol.dart | 15 + .../sol.go | 12 + .../sol.java | 15 + .../sol.kt | 16 + .../sol.py | 11 + .../sol.py2 | 15 + .../sol.rb | 14 + .../sol.rs | 16 + .../sol.swift | 18 + .../sol.ts | 14 + .../manifest.yaml | 220 +++ .../sol.cpp | 13 + .../sol.cs | 12 + .../sol.dart | 12 + .../sol.go | 13 + .../sol.java | 12 + .../sol.kt | 13 + .../sol.py | 8 + .../sol.py2 | 8 + .../sol.rb | 12 + .../sol.rs | 13 + .../sol.swift | 13 + .../sol.ts | 11 + .../manifest.yaml | 189 ++ .../sol.cpp | 22 + .../sol.cs | 21 + .../sol.dart | 21 + .../sol.go | 19 + .../sol.java | 23 + .../sol.kt | 22 + .../sol.py | 20 + .../sol.py2 | 20 + .../sol.rb | 21 + .../sol.rs | 27 + .../sol.swift | 22 + .../sol.ts | 19 + .../manifest.yaml | 232 +++ .../sol.cpp | 31 + .../sol.cs | 30 + .../sol.dart | 30 + .../sol.go | 28 + .../sol.java | 31 + .../sol.kt | 30 + .../sol.py | 22 + .../sol.py2 | 26 + .../sol.rb | 24 + .../sol.rs | 32 + .../sol.swift | 30 + .../sol.ts | 28 + .../1416. restore-the-array/manifest.yaml | 230 +++ .../1001-1500/1416. restore-the-array/sol.cpp | 20 + .../1001-1500/1416. restore-the-array/sol.cs | 19 + .../1416. restore-the-array/sol.dart | 19 + .../1001-1500/1416. restore-the-array/sol.go | 21 + .../1416. restore-the-array/sol.java | 19 + .../1001-1500/1416. restore-the-array/sol.kt | 19 + .../1001-1500/1416. restore-the-array/sol.py | 16 + .../1001-1500/1416. restore-the-array/sol.py2 | 22 + .../1001-1500/1416. restore-the-array/sol.rb | 20 + .../1001-1500/1416. restore-the-array/sol.rs | 25 + .../1416. restore-the-array/sol.swift | 20 + .../1001-1500/1416. restore-the-array/sol.ts | 17 + .../1417. reformat-the-string/manifest.yaml | 175 ++ .../1417. reformat-the-string/sol.cpp | 36 + .../1417. reformat-the-string/sol.cs | 35 + .../1417. reformat-the-string/sol.dart | 27 + .../1417. reformat-the-string/sol.go | 41 + .../1417. reformat-the-string/sol.java | 35 + .../1417. reformat-the-string/sol.kt | 27 + .../1417. reformat-the-string/sol.py | 16 + .../1417. reformat-the-string/sol.py2 | 18 + .../1417. reformat-the-string/sol.rb | 16 + .../1417. reformat-the-string/sol.rs | 20 + .../1417. reformat-the-string/sol.swift | 35 + .../1417. reformat-the-string/sol.ts | 25 + .../manifest.yaml | 597 +++++++ .../sol.cpp | 31 + .../sol.cs | 36 + .../sol.dart | 31 + .../sol.go | 41 + .../sol.java | 46 + .../sol.kt | 35 + .../sol.py | 27 + .../sol.py2 | 25 + .../sol.rb | 25 + .../sol.rs | 35 + .../sol.swift | 31 + .../sol.ts | 31 + .../manifest.yaml | 223 +++ .../sol.cpp | 32 + .../sol.cs | 31 + .../sol.dart | 31 + .../sol.go | 31 + .../sol.java | 31 + .../sol.kt | 35 + .../sol.py | 25 + .../sol.py2 | 29 + .../sol.rb | 31 + .../sol.rs | 35 + .../sol.swift | 31 + .../sol.ts | 33 + .../manifest.yaml | 293 +++ .../sol.cpp | 39 + .../sol.cs | 41 + .../sol.dart | 31 + .../sol.go | 44 + .../sol.java | 37 + .../sol.kt | 33 + .../sol.py | 33 + .../sol.py2 | 30 + .../sol.rb | 34 + .../sol.rs | 35 + .../sol.swift | 39 + .../sol.ts | 27 + .../manifest.yaml | 181 ++ .../sol.cpp | 26 + .../sol.cs | 25 + .../sol.dart | 23 + .../sol.go | 27 + .../sol.java | 25 + .../sol.kt | 21 + .../sol.py | 19 + .../sol.py2 | 19 + .../sol.rb | 21 + .../sol.rs | 22 + .../sol.swift | 22 + .../sol.ts | 23 + .../manifest.yaml | 250 +++ .../sol.cpp | 18 + .../sol.cs | 14 + .../sol.dart | 14 + .../sol.go | 17 + .../sol.java | 17 + .../sol.kt | 14 + .../sol.py | 10 + .../sol.py2 | 10 + .../sol.rb | 14 + .../sol.rs | 15 + .../sol.swift | 14 + .../sol.ts | 12 + .../1424. diagonal-traverse-ii/manifest.yaml | 340 ++++ .../1424. diagonal-traverse-ii/sol.cpp | 25 + .../1424. diagonal-traverse-ii/sol.cs | 26 + .../1424. diagonal-traverse-ii/sol.dart | 24 + .../1424. diagonal-traverse-ii/sol.go | 29 + .../1424. diagonal-traverse-ii/sol.java | 47 + .../1424. diagonal-traverse-ii/sol.kt | 26 + .../1424. diagonal-traverse-ii/sol.py | 17 + .../1424. diagonal-traverse-ii/sol.py2 | 17 + .../1424. diagonal-traverse-ii/sol.rb | 22 + .../1424. diagonal-traverse-ii/sol.rs | 25 + .../1424. diagonal-traverse-ii/sol.swift | 21 + .../1424. diagonal-traverse-ii/sol.ts | 23 + .../manifest.yaml | 280 +++ .../1425. constrained-subsequence-sum/sol.cpp | 22 + .../1425. constrained-subsequence-sum/sol.cs | 21 + .../sol.dart | 21 + .../1425. constrained-subsequence-sum/sol.go | 27 + .../sol.java | 21 + .../1425. constrained-subsequence-sum/sol.kt | 21 + .../1425. constrained-subsequence-sum/sol.py | 24 + .../1425. constrained-subsequence-sum/sol.py2 | 20 + .../1425. constrained-subsequence-sum/sol.rb | 21 + .../1425. constrained-subsequence-sum/sol.rs | 28 + .../sol.swift | 20 + .../1425. constrained-subsequence-sum/sol.ts | 19 + .../manifest.yaml | 383 ++++ .../sol.cpp | 15 + .../sol.cs | 14 + .../sol.dart | 14 + .../sol.go | 17 + .../sol.java | 19 + .../sol.kt | 14 + .../sol.py | 12 + .../sol.py2 | 15 + .../sol.rb | 15 + .../sol.rs | 14 + .../sol.swift | 14 + .../sol.ts | 12 + .../manifest.yaml | 202 +++ .../sol.cpp | 24 + .../sol.cs | 22 + .../sol.dart | 23 + .../sol.go | 27 + .../sol.java | 31 + .../sol.kt | 22 + .../sol.py | 17 + .../sol.py2 | 21 + .../sol.rb | 20 + .../sol.rs | 29 + .../sol.swift | 23 + .../sol.ts | 21 + .../manifest.yaml | 260 +++ .../sol.cpp | 49 + .../sol.cs | 51 + .../sol.dart | 51 + .../sol.go | 49 + .../sol.java | 51 + .../sol.kt | 51 + .../sol.py | 38 + .../sol.py2 | 42 + .../sol.rb | 43 + .../sol.rs | 51 + .../sol.swift | 51 + .../sol.ts | 49 + .../manifest.yaml | 1061 +++++++++++ .../sol.cpp | 31 + .../sol.cs | 33 + .../sol.dart | 31 + .../sol.go | 34 + .../sol.java | 49 + .../sol.kt | 35 + .../sol.py | 26 + .../sol.py2 | 27 + .../sol.rb | 30 + .../sol.rs | 33 + .../sol.swift | 31 + .../sol.ts | 29 + .../1436. destination-city/manifest.yaml | 527 ++++++ .../1001-1500/1436. destination-city/sol.cpp | 18 + tests/1001-1500/1436. destination-city/sol.cs | 17 + .../1001-1500/1436. destination-city/sol.dart | 17 + tests/1001-1500/1436. destination-city/sol.go | 15 + .../1001-1500/1436. destination-city/sol.java | 34 + tests/1001-1500/1436. destination-city/sol.kt | 34 + tests/1001-1500/1436. destination-city/sol.py | 12 + .../1001-1500/1436. destination-city/sol.py2 | 12 + tests/1001-1500/1436. destination-city/sol.rb | 15 + tests/1001-1500/1436. destination-city/sol.rs | 19 + .../1436. destination-city/sol.swift | 17 + tests/1001-1500/1436. destination-city/sol.ts | 15 + .../manifest.yaml | 271 +++ .../sol.cpp | 18 + .../sol.cs | 17 + .../sol.dart | 17 + .../sol.go | 15 + .../sol.java | 17 + .../sol.kt | 17 + .../sol.py | 14 + .../sol.py2 | 16 + .../sol.rb | 16 + .../sol.rs | 19 + .../sol.swift | 17 + .../sol.ts | 15 + .../manifest.yaml | 287 +++ .../sol.cpp | 28 + .../sol.cs | 28 + .../sol.dart | 29 + .../sol.go | 29 + .../sol.java | 29 + .../sol.kt | 29 + .../sol.py | 54 + .../sol.py2 | 27 + .../sol.rb | 26 + .../sol.rs | 37 + .../sol.swift | 29 + .../sol.ts | 27 + .../manifest.yaml | 592 ++++++ .../sol.cpp | 21 + .../sol.cs | 18 + .../sol.dart | 17 + .../sol.go | 21 + .../sol.java | 19 + .../sol.kt | 17 + .../sol.py | 9 + .../sol.py2 | 11 + .../sol.rb | 11 + .../sol.rs | 19 + .../sol.swift | 17 + .../sol.ts | 15 + .../manifest.yaml | 374 ++++ .../sol.cpp | 20 + .../sol.cs | 19 + .../sol.dart | 28 + .../sol.go | 28 + .../sol.java | 19 + .../sol.kt | 19 + .../sol.py | 16 + .../sol.py2 | 16 + .../sol.rb | 20 + .../sol.rs | 21 + .../sol.swift | 21 + .../sol.ts | 19 + .../manifest.yaml | 207 +++ .../sol.cpp | 23 + .../sol.cs | 22 + .../sol.dart | 20 + .../sol.go | 18 + .../sol.java | 22 + .../sol.kt | 20 + .../sol.py | 20 + .../sol.py2 | 16 + .../sol.rb | 21 + .../sol.rs | 23 + .../sol.swift | 20 + .../sol.ts | 19 + .../manifest.yaml | 556 ++++++ .../sol.cpp | 44 + .../sol.cs | 46 + .../sol.dart | 38 + .../sol.go | 53 + .../sol.java | 55 + .../sol.kt | 42 + .../sol.py | 33 + .../sol.py2 | 35 + .../sol.rb | 39 + .../sol.rs | 39 + .../sol.swift | 38 + .../sol.ts | 35 + .../manifest.yaml | 358 ++++ .../sol.cpp | 43 + .../sol.cs | 42 + .../sol.dart | 43 + .../sol.go | 58 + .../sol.java | 42 + .../sol.kt | 44 + .../sol.py | 32 + .../sol.py2 | 35 + .../sol.rb | 44 + .../sol.rs | 48 + .../sol.swift | 43 + .../sol.ts | 50 + .../manifest.yaml | 172 ++ .../1446. consecutive-characters/sol.cpp | 16 + .../1446. consecutive-characters/sol.cs | 15 + .../1446. consecutive-characters/sol.dart | 17 + .../1446. consecutive-characters/sol.go | 15 + .../1446. consecutive-characters/sol.java | 15 + .../1446. consecutive-characters/sol.kt | 15 + .../1446. consecutive-characters/sol.py | 13 + .../1446. consecutive-characters/sol.py2 | 14 + .../1446. consecutive-characters/sol.rb | 15 + .../1446. consecutive-characters/sol.rs | 16 + .../1446. consecutive-characters/sol.swift | 16 + .../1446. consecutive-characters/sol.ts | 13 + .../1447. simplified-fractions/manifest.yaml | 204 +++ .../1447. simplified-fractions/sol.cpp | 14 + .../1447. simplified-fractions/sol.cs | 22 + .../1447. simplified-fractions/sol.dart | 22 + .../1447. simplified-fractions/sol.go | 18 + .../1447. simplified-fractions/sol.java | 22 + .../1447. simplified-fractions/sol.kt | 24 + .../1447. simplified-fractions/sol.py | 11 + .../1447. simplified-fractions/sol.py2 | 18 + .../1447. simplified-fractions/sol.rb | 13 + .../1447. simplified-fractions/sol.rs | 22 + .../1447. simplified-fractions/sol.swift | 24 + .../1447. simplified-fractions/sol.ts | 18 + .../manifest.yaml | 236 +++ .../sol.cpp | 25 + .../sol.cs | 26 + .../sol.dart | 13 + .../sol.go | 28 + .../sol.java | 29 + .../sol.kt | 23 + .../sol.py | 28 + .../sol.py2 | 22 + .../sol.rb | 22 + .../sol.rs | 39 + .../sol.swift | 28 + .../sol.ts | 25 + .../manifest.yaml | 278 +++ .../sol.cpp | 34 + .../sol.cs | 40 + .../sol.dart | 33 + .../sol.go | 52 + .../sol.java | 35 + .../sol.kt | 33 + .../sol.py | 29 + .../sol.py2 | 31 + .../sol.rb | 31 + .../sol.rs | 48 + .../sol.swift | 33 + .../sol.ts | 33 + .../manifest.yaml | 576 ++++++ .../sol.cpp | 12 + .../sol.cs | 11 + .../sol.dart | 11 + .../sol.go | 9 + .../sol.java | 11 + .../sol.kt | 5 + .../sol.py | 13 + .../sol.py2 | 9 + .../sol.rb | 7 + .../sol.rs | 7 + .../sol.swift | 5 + .../sol.ts | 9 + .../manifest.yaml | 197 ++ .../sol.cpp | 26 + .../sol.cs | 13 + .../sol.dart | 9 + .../sol.go | 13 + .../sol.java | 11 + .../sol.kt | 11 + .../sol.py | 7 + .../sol.py2 | 11 + .../sol.rb | 9 + .../sol.rs | 11 + .../sol.swift | 11 + .../sol.ts | 7 + .../manifest.yaml | 501 ++++++ .../sol.cpp | 36 + .../sol.cs | 26 + .../sol.dart | 21 + .../sol.go | 35 + .../sol.java | 28 + .../sol.kt | 21 + .../sol.py | 22 + .../sol.py2 | 19 + .../sol.rb | 19 + .../sol.rs | 27 + .../sol.swift | 21 + .../sol.ts | 30 + .../manifest.yaml | 643 +++++++ .../sol.cpp | 35 + .../sol.cs | 34 + .../sol.dart | 36 + .../sol.go | 36 + .../sol.java | 34 + .../sol.kt | 37 + .../sol.py | 31 + .../sol.py2 | 36 + .../sol.rb | 34 + .../sol.rs | 37 + .../sol.swift | 37 + .../sol.ts | 33 + .../manifest.yaml | 283 +++ .../sol.cpp | 15 + .../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 | 264 +++ .../sol.cpp | 29 + .../sol.cs | 27 + .../sol.dart | 29 + .../sol.go | 27 + .../sol.java | 27 + .../sol.kt | 27 + .../sol.py | 20 + .../sol.py2 | 25 + .../sol.rb | 28 + .../sol.rs | 29 + .../sol.swift | 28 + .../sol.ts | 25 + .../manifest.yaml | 266 +++ .../sol.cpp | 47 + .../sol.cs | 48 + .../sol.dart | 44 + .../sol.go | 49 + .../sol.java | 50 + .../sol.kt | 45 + .../sol.py | 39 + .../sol.py2 | 40 + .../sol.rb | 43 + .../sol.rs | 58 + .../sol.swift | 54 + .../sol.ts | 47 + .../manifest.yaml | 367 ++++ .../sol.cpp | 30 + .../sol.cs | 34 + .../sol.dart | 33 + .../sol.go | 40 + .../sol.java | 39 + .../sol.kt | 33 + .../sol.py | 33 + .../sol.py2 | 26 + .../sol.rb | 24 + .../sol.rs | 35 + .../sol.swift | 28 + .../sol.ts | 28 + .../manifest.yaml | 295 +++ .../sol.cpp | 16 + .../sol.cs | 15 + .../sol.dart | 12 + .../sol.go | 15 + .../sol.java | 15 + .../sol.kt | 12 + .../sol.py | 9 + .../sol.py2 | 14 + .../sol.rb | 13 + .../sol.rs | 12 + .../sol.swift | 12 + .../sol.ts | 10 + .../manifest.yaml | 255 +++ .../sol.cpp | 21 + .../sol.cs | 20 + .../sol.dart | 20 + .../sol.go | 20 + .../sol.java | 20 + .../sol.kt | 20 + .../sol.py | 17 + .../sol.py2 | 22 + .../sol.rb | 21 + .../sol.rs | 24 + .../sol.swift | 22 + .../sol.ts | 18 + .../1462. course-schedule-iv/manifest.yaml | 844 +++++++++ .../1462. course-schedule-iv/sol.cpp | 14 + .../1001-1500/1462. course-schedule-iv/sol.cs | 13 + .../1462. course-schedule-iv/sol.dart | 13 + .../1001-1500/1462. course-schedule-iv/sol.go | 14 + .../1462. course-schedule-iv/sol.java | 13 + .../1001-1500/1462. course-schedule-iv/sol.kt | 11 + .../1001-1500/1462. course-schedule-iv/sol.py | 34 + .../1462. course-schedule-iv/sol.py2 | 29 + .../1001-1500/1462. course-schedule-iv/sol.rb | 33 + .../1001-1500/1462. course-schedule-iv/sol.rs | 14 + .../1462. course-schedule-iv/sol.swift | 12 + .../1001-1500/1462. course-schedule-iv/sol.ts | 12 + .../1463. cherry-pickup-ii/manifest.yaml | 535 ++++++ .../1001-1500/1463. cherry-pickup-ii/sol.cpp | 36 + tests/1001-1500/1463. cherry-pickup-ii/sol.cs | 46 + .../1001-1500/1463. cherry-pickup-ii/sol.dart | 39 + tests/1001-1500/1463. cherry-pickup-ii/sol.go | 52 + .../1001-1500/1463. cherry-pickup-ii/sol.java | 39 + tests/1001-1500/1463. cherry-pickup-ii/sol.kt | 35 + tests/1001-1500/1463. cherry-pickup-ii/sol.py | 23 + .../1001-1500/1463. cherry-pickup-ii/sol.py2 | 22 + tests/1001-1500/1463. cherry-pickup-ii/sol.rb | 30 + tests/1001-1500/1463. cherry-pickup-ii/sol.rs | 39 + .../1463. cherry-pickup-ii/sol.swift | 37 + tests/1001-1500/1463. cherry-pickup-ii/sol.ts | 37 + .../manifest.yaml | 1248 +++++++++++++ .../sol.cpp | 15 + .../sol.cs | 14 + .../sol.dart | 14 + .../sol.go | 12 + .../sol.java | 14 + .../sol.kt | 15 + .../sol.py | 12 + .../sol.py2 | 14 + .../sol.rb | 14 + .../sol.rs | 15 + .../sol.swift | 15 + .../sol.ts | 13 + .../manifest.yaml | 332 ++++ .../sol.cpp | 21 + .../sol.cs | 20 + .../sol.dart | 20 + .../sol.go | 18 + .../sol.java | 20 + .../sol.kt | 20 + .../sol.py | 24 + .../sol.py2 | 23 + .../sol.rb | 23 + .../sol.rs | 20 + .../sol.swift | 20 + .../sol.ts | 29 + .../manifest.yaml | 726 ++++++++ .../sol.cpp | 32 + .../sol.cs | 34 + .../sol.dart | 31 + .../sol.go | 34 + .../sol.java | 38 + .../sol.kt | 29 + .../sol.py | 25 + .../sol.py2 | 28 + .../sol.rb | 27 + .../sol.rs | 34 + .../sol.swift | 31 + .../sol.ts | 28 + .../manifest.yaml | 172 ++ .../sol.cpp | 41 + .../sol.cs | 41 + .../sol.dart | 59 + .../sol.go | 67 + .../sol.java | 45 + .../sol.kt | 43 + .../sol.py | 31 + .../sol.py2 | 38 + .../sol.rb | 37 + .../sol.rs | 51 + .../sol.swift | 47 + .../sol.ts | 55 + .../1470. shuffle-the-array/manifest.yaml | 1235 +++++++++++++ .../1001-1500/1470. shuffle-the-array/sol.cpp | 14 + .../1001-1500/1470. shuffle-the-array/sol.cs | 13 + .../1470. shuffle-the-array/sol.dart | 10 + .../1001-1500/1470. shuffle-the-array/sol.go | 11 + .../1470. shuffle-the-array/sol.java | 13 + .../1001-1500/1470. shuffle-the-array/sol.kt | 13 + .../1001-1500/1470. shuffle-the-array/sol.py | 9 + .../1001-1500/1470. shuffle-the-array/sol.py2 | 14 + .../1001-1500/1470. shuffle-the-array/sol.rb | 14 + .../1001-1500/1470. shuffle-the-array/sol.rs | 14 + .../1470. shuffle-the-array/sol.swift | 13 + .../1001-1500/1470. shuffle-the-array/sol.ts | 11 + .../manifest.yaml | 220 +++ .../sol.cpp | 20 + .../sol.cs | 19 + .../sol.dart | 19 + .../sol.go | 24 + .../sol.java | 19 + .../sol.kt | 20 + .../sol.py | 20 + .../sol.py2 | 20 + .../sol.rb | 21 + .../sol.rs | 21 + .../sol.swift | 20 + .../sol.ts | 18 + .../1473. paint-house-iii/manifest.yaml | 779 ++++++++ tests/1001-1500/1473. paint-house-iii/sol.cpp | 70 + tests/1001-1500/1473. paint-house-iii/sol.cs | 81 + .../1001-1500/1473. paint-house-iii/sol.dart | 69 + tests/1001-1500/1473. paint-house-iii/sol.go | 82 + .../1001-1500/1473. paint-house-iii/sol.java | 79 + tests/1001-1500/1473. paint-house-iii/sol.kt | 69 + tests/1001-1500/1473. paint-house-iii/sol.py | 44 + tests/1001-1500/1473. paint-house-iii/sol.py2 | 50 + tests/1001-1500/1473. paint-house-iii/sol.rb | 68 + tests/1001-1500/1473. paint-house-iii/sol.rs | 76 + .../1001-1500/1473. paint-house-iii/sol.swift | 69 + tests/1001-1500/1473. paint-house-iii/sol.ts | 77 + .../manifest.yaml | 217 +++ .../sol.cpp | 15 + .../sol.cs | 13 + .../sol.dart | 13 + .../sol.go | 12 + .../sol.java | 14 + .../sol.kt | 13 + .../sol.py | 12 + .../sol.py2 | 13 + .../sol.rb | 13 + .../sol.rs | 18 + .../sol.swift | 14 + .../sol.ts | 11 + .../manifest.yaml | 262 +++ .../sol.cpp | 33 + .../sol.cs | 35 + .../sol.dart | 32 + .../sol.go | 42 + .../sol.java | 35 + .../sol.kt | 32 + .../sol.py | 21 + .../sol.py2 | 29 + .../sol.rb | 33 + .../sol.rs | 30 + .../sol.swift | 32 + .../sol.ts | 30 + .../1478. allocate-mailboxes/manifest.yaml | 248 +++ .../1478. allocate-mailboxes/sol.cpp | 38 + .../1001-1500/1478. allocate-mailboxes/sol.cs | 42 + .../1478. allocate-mailboxes/sol.dart | 38 + .../1001-1500/1478. allocate-mailboxes/sol.go | 46 + .../1478. allocate-mailboxes/sol.java | 40 + .../1001-1500/1478. allocate-mailboxes/sol.kt | 37 + .../1001-1500/1478. allocate-mailboxes/sol.py | 66 + .../1478. allocate-mailboxes/sol.py2 | 31 + .../1001-1500/1478. allocate-mailboxes/sol.rb | 37 + .../1001-1500/1478. allocate-mailboxes/sol.rs | 40 + .../1478. allocate-mailboxes/sol.swift | 37 + .../1001-1500/1478. allocate-mailboxes/sol.ts | 40 + .../manifest.yaml | 304 ++++ .../1480. running-sum-of-1d-array/sol.cpp | 9 + .../1480. running-sum-of-1d-array/sol.cs | 8 + .../1480. running-sum-of-1d-array/sol.dart | 8 + .../1480. running-sum-of-1d-array/sol.go | 6 + .../1480. running-sum-of-1d-array/sol.java | 8 + .../1480. running-sum-of-1d-array/sol.kt | 8 + .../1480. running-sum-of-1d-array/sol.py | 7 + .../1480. running-sum-of-1d-array/sol.py2 | 9 + .../1480. running-sum-of-1d-array/sol.rb | 8 + .../1480. running-sum-of-1d-array/sol.rs | 9 + .../1480. running-sum-of-1d-array/sol.swift | 9 + .../1480. running-sum-of-1d-array/sol.ts | 6 + .../manifest.yaml | 227 +++ .../sol.cpp | 23 + .../sol.cs | 23 + .../sol.dart | 19 + .../sol.go | 20 + .../sol.java | 19 + .../sol.kt | 14 + .../sol.py | 12 + .../sol.py2 | 22 + .../sol.rb | 13 + .../sol.rs | 21 + .../sol.swift | 19 + .../sol.ts | 16 + .../manifest.yaml | 282 +++ .../sol.cpp | 39 + .../sol.cs | 38 + .../sol.dart | 38 + .../sol.go | 46 + .../sol.java | 41 + .../sol.kt | 38 + .../sol.py | 34 + .../sol.py2 | 37 + .../sol.rb | 40 + .../sol.rs | 42 + .../sol.swift | 38 + .../sol.ts | 36 + .../manifest.yaml | 231 +++ .../1486. xor-operation-in-an-array/sol.cpp | 12 + .../1486. xor-operation-in-an-array/sol.cs | 11 + .../1486. xor-operation-in-an-array/sol.dart | 11 + .../1486. xor-operation-in-an-array/sol.go | 9 + .../1486. xor-operation-in-an-array/sol.java | 11 + .../1486. xor-operation-in-an-array/sol.kt | 13 + .../1486. xor-operation-in-an-array/sol.py | 10 + .../1486. xor-operation-in-an-array/sol.py2 | 13 + .../1486. xor-operation-in-an-array/sol.rb | 12 + .../1486. xor-operation-in-an-array/sol.rs | 13 + .../1486. xor-operation-in-an-array/sol.swift | 13 + .../1486. xor-operation-in-an-array/sol.ts | 9 + .../manifest.yaml | 258 +++ .../1487. making-file-names-unique/sol.cpp | 25 + .../1487. making-file-names-unique/sol.cs | 25 + .../1487. making-file-names-unique/sol.dart | 24 + .../1487. making-file-names-unique/sol.go | 26 + .../1487. making-file-names-unique/sol.java | 25 + .../1487. making-file-names-unique/sol.kt | 24 + .../1487. making-file-names-unique/sol.py | 23 + .../1487. making-file-names-unique/sol.py2 | 23 + .../1487. making-file-names-unique/sol.rb | 24 + .../1487. making-file-names-unique/sol.rs | 26 + .../1487. making-file-names-unique/sol.swift | 24 + .../1487. making-file-names-unique/sol.ts | 22 + .../manifest.yaml | 247 +++ .../1488. avoid-flood-in-the-city/sol.cpp | 26 + .../1488. avoid-flood-in-the-city/sol.cs | 26 + .../1488. avoid-flood-in-the-city/sol.dart | 37 + .../1488. avoid-flood-in-the-city/sol.go | 36 + .../1488. avoid-flood-in-the-city/sol.java | 29 + .../1488. avoid-flood-in-the-city/sol.kt | 25 + .../1488. avoid-flood-in-the-city/sol.py | 21 + .../1488. avoid-flood-in-the-city/sol.py2 | 24 + .../1488. avoid-flood-in-the-city/sol.rb | 60 + .../1488. avoid-flood-in-the-city/sol.rs | 30 + .../1488. avoid-flood-in-the-city/sol.swift | 36 + .../1488. avoid-flood-in-the-city/sol.ts | 36 + .../manifest.yaml | 863 +++++++++ .../sol.cpp | 67 + .../sol.cs | 60 + .../sol.dart | 46 + .../sol.go | 67 + .../sol.java | 66 + .../sol.kt | 57 + .../sol.py | 88 + .../sol.py2 | 49 + .../sol.rb | 43 + .../sol.rs | 67 + .../sol.swift | 57 + .../sol.ts | 56 + .../manifest.yaml | 227 +++ .../sol.cpp | 16 + .../sol.cs | 19 + .../sol.dart | 19 + .../sol.go | 21 + .../sol.java | 19 + .../sol.kt | 15 + .../sol.py | 12 + .../sol.py2 | 16 + .../sol.rb | 14 + .../sol.rs | 15 + .../sol.swift | 15 + .../sol.ts | 13 + .../1492. the-kth-factor-of-n/manifest.yaml | 266 +++ .../1492. the-kth-factor-of-n/sol.cpp | 16 + .../1492. the-kth-factor-of-n/sol.cs | 15 + .../1492. the-kth-factor-of-n/sol.dart | 15 + .../1492. the-kth-factor-of-n/sol.go | 12 + .../1492. the-kth-factor-of-n/sol.java | 15 + .../1492. the-kth-factor-of-n/sol.kt | 11 + .../1492. the-kth-factor-of-n/sol.py | 12 + .../1492. the-kth-factor-of-n/sol.py2 | 15 + .../1492. the-kth-factor-of-n/sol.rb | 11 + .../1492. the-kth-factor-of-n/sol.rs | 15 + .../1492. the-kth-factor-of-n/sol.swift | 15 + .../1492. the-kth-factor-of-n/sol.ts | 13 + .../manifest.yaml | 269 +++ .../sol.cpp | 15 + .../sol.cs | 14 + .../sol.dart | 14 + .../sol.go | 18 + .../sol.java | 18 + .../sol.kt | 16 + .../sol.py | 19 + .../sol.py2 | 16 + .../sol.rb | 16 + .../sol.rs | 20 + .../sol.swift | 18 + .../sol.ts | 14 + .../1494. parallel-courses-ii/manifest.yaml | 702 ++++++++ .../1494. parallel-courses-ii/sol.cpp | 66 + .../1494. parallel-courses-ii/sol.cs | 71 + .../1494. parallel-courses-ii/sol.dart | 67 + .../1494. parallel-courses-ii/sol.go | 81 + .../1494. parallel-courses-ii/sol.java | 71 + .../1494. parallel-courses-ii/sol.kt | 68 + .../1494. parallel-courses-ii/sol.py | 51 + .../1494. parallel-courses-ii/sol.py2 | 41 + .../1494. parallel-courses-ii/sol.rb | 42 + .../1494. parallel-courses-ii/sol.rs | 78 + .../1494. parallel-courses-ii/sol.swift | 69 + .../1494. parallel-courses-ii/sol.ts | 62 + .../1496. path-crossing/manifest.yaml | 210 +++ tests/1001-1500/1496. path-crossing/sol.cpp | 17 + tests/1001-1500/1496. path-crossing/sol.cs | 17 + tests/1001-1500/1496. path-crossing/sol.dart | 17 + tests/1001-1500/1496. path-crossing/sol.go | 19 + tests/1001-1500/1496. path-crossing/sol.java | 17 + tests/1001-1500/1496. path-crossing/sol.kt | 20 + tests/1001-1500/1496. path-crossing/sol.py | 16 + tests/1001-1500/1496. path-crossing/sol.py2 | 20 + tests/1001-1500/1496. path-crossing/sol.rb | 21 + tests/1001-1500/1496. path-crossing/sol.rs | 21 + tests/1001-1500/1496. path-crossing/sol.swift | 20 + tests/1001-1500/1496. path-crossing/sol.ts | 16 + .../manifest.yaml | 209 +++ .../sol.cpp | 17 + .../sol.cs | 17 + .../sol.dart | 12 + .../sol.go | 21 + .../sol.java | 17 + .../sol.kt | 9 + .../sol.py | 10 + .../sol.py2 | 10 + .../sol.rb | 10 + .../sol.rs | 17 + .../sol.swift | 14 + .../sol.ts | 11 + .../manifest.yaml | 367 ++++ .../sol.cpp | 27 + .../sol.cs | 27 + .../sol.dart | 26 + .../sol.go | 25 + .../sol.java | 27 + .../sol.kt | 28 + .../sol.py | 21 + .../sol.py2 | 26 + .../sol.rb | 25 + .../sol.rs | 28 + .../sol.swift | 26 + .../sol.ts | 26 + .../1499. max-value-of-equation/manifest.yaml | 549 ++++++ .../1499. max-value-of-equation/sol.cpp | 23 + .../1499. max-value-of-equation/sol.cs | 22 + .../1499. max-value-of-equation/sol.dart | 25 + .../1499. max-value-of-equation/sol.go | 25 + .../1499. max-value-of-equation/sol.java | 22 + .../1499. max-value-of-equation/sol.kt | 22 + .../1499. max-value-of-equation/sol.py | 19 + .../1499. max-value-of-equation/sol.py2 | 20 + .../1499. max-value-of-equation/sol.rb | 21 + .../1499. max-value-of-equation/sol.rs | 29 + .../1499. max-value-of-equation/sol.swift | 22 + .../1499. max-value-of-equation/sol.ts | 18 + .../manifest.yaml | 210 +++ .../sol.cpp | 13 + .../sol.cs | 12 + .../sol.dart | 12 + .../sol.go | 10 + .../sol.java | 12 + .../sol.kt | 12 + .../sol.py | 13 + .../sol.py2 | 13 + .../sol.rb | 10 + .../sol.rs | 13 + .../sol.swift | 12 + .../sol.ts | 10 + .../manifest.yaml | 395 ++++ .../sol.cpp | 13 + .../sol.cs | 12 + .../sol.dart | 16 + .../sol.go | 14 + .../sol.java | 12 + .../sol.kt | 12 + .../sol.py | 11 + .../sol.py2 | 14 + .../sol.rb | 14 + .../sol.rs | 12 + .../sol.swift | 12 + .../sol.ts | 10 + .../manifest.yaml | 423 +++++ .../sol.cpp | 36 + .../sol.cs | 35 + .../sol.dart | 35 + .../sol.go | 37 + .../sol.java | 36 + .../sol.kt | 35 + .../sol.py | 20 + .../sol.py2 | 25 + .../sol.rb | 35 + .../sol.rs | 34 + .../sol.swift | 34 + .../sol.ts | 33 + .../manifest.yaml | 299 ++++ .../sol.cpp | 46 + .../sol.cs | 48 + .../sol.dart | 50 + .../sol.go | 46 + .../sol.java | 50 + .../sol.kt | 49 + .../sol.py | 47 + .../sol.py2 | 44 + .../sol.rb | 46 + .../sol.rs | 49 + .../sol.swift | 50 + .../sol.ts | 49 + .../1507. reformat-date/manifest.yaml | 230 +++ tests/1501-2000/1507. reformat-date/sol.cpp | 16 + tests/1501-2000/1507. reformat-date/sol.cs | 15 + tests/1501-2000/1507. reformat-date/sol.dart | 15 + tests/1501-2000/1507. reformat-date/sol.go | 15 + tests/1501-2000/1507. reformat-date/sol.java | 20 + tests/1501-2000/1507. reformat-date/sol.kt | 15 + tests/1501-2000/1507. reformat-date/sol.py | 20 + tests/1501-2000/1507. reformat-date/sol.py2 | 11 + tests/1501-2000/1507. reformat-date/sol.rb | 13 + tests/1501-2000/1507. reformat-date/sol.rs | 16 + tests/1501-2000/1507. reformat-date/sol.swift | 15 + tests/1501-2000/1507. reformat-date/sol.ts | 22 + .../manifest.yaml | 482 +++++ .../sol.cpp | 21 + .../sol.cs | 19 + .../sol.dart | 19 + .../sol.go | 17 + .../sol.java | 21 + .../sol.kt | 19 + .../sol.py | 10 + .../sol.py2 | 17 + .../sol.rb | 17 + .../sol.rs | 20 + .../sol.swift | 19 + .../sol.ts | 22 + .../manifest.yaml | 218 +++ .../sol.cpp | 16 + .../sol.cs | 15 + .../sol.dart | 15 + .../sol.go | 27 + .../sol.java | 13 + .../sol.kt | 15 + .../sol.py | 45 + .../sol.py2 | 16 + .../sol.rb | 13 + .../sol.rs | 16 + .../sol.swift | 15 + .../sol.ts | 13 + .../1510. stone-game-iv/manifest.yaml | 186 ++ tests/1501-2000/1510. stone-game-iv/sol.cpp | 21 + tests/1501-2000/1510. stone-game-iv/sol.cs | 25 + tests/1501-2000/1510. stone-game-iv/sol.dart | 22 + tests/1501-2000/1510. stone-game-iv/sol.go | 29 + tests/1501-2000/1510. stone-game-iv/sol.java | 24 + tests/1501-2000/1510. stone-game-iv/sol.kt | 20 + tests/1501-2000/1510. stone-game-iv/sol.py | 11 + tests/1501-2000/1510. stone-game-iv/sol.py2 | 21 + tests/1501-2000/1510. stone-game-iv/sol.rb | 21 + tests/1501-2000/1510. stone-game-iv/sol.rs | 25 + tests/1501-2000/1510. stone-game-iv/sol.swift | 20 + tests/1501-2000/1510. stone-game-iv/sol.ts | 20 + .../1512. number-of-good-pairs/manifest.yaml | 779 ++++++++ .../1512. number-of-good-pairs/sol.cpp | 14 + .../1512. number-of-good-pairs/sol.cs | 13 + .../1512. number-of-good-pairs/sol.dart | 13 + .../1512. number-of-good-pairs/sol.go | 11 + .../1512. number-of-good-pairs/sol.java | 13 + .../1512. number-of-good-pairs/sol.kt | 13 + .../1512. number-of-good-pairs/sol.py | 12 + .../1512. number-of-good-pairs/sol.py2 | 13 + .../1512. number-of-good-pairs/sol.rb | 13 + .../1512. number-of-good-pairs/sol.rs | 13 + .../1512. number-of-good-pairs/sol.swift | 13 + .../1512. number-of-good-pairs/sol.ts | 11 + .../manifest.yaml | 203 +++ .../sol.cpp | 17 + .../sol.cs | 16 + .../sol.dart | 16 + .../sol.go | 14 + .../sol.java | 16 + .../sol.kt | 16 + .../sol.py | 12 + .../sol.py2 | 12 + .../sol.rb | 16 + .../sol.rs | 16 + .../sol.swift | 16 + .../sol.ts | 14 + .../manifest.yaml | 600 +++++++ .../sol.cpp | 26 + .../sol.cs | 25 + .../sol.dart | 25 + .../sol.go | 24 + .../sol.java | 25 + .../sol.kt | 25 + .../sol.py | 25 + .../sol.py2 | 26 + .../sol.rb | 27 + .../sol.rs | 28 + .../sol.swift | 25 + .../sol.ts | 29 + .../manifest.yaml | 652 +++++++ .../sol.cpp | 44 + .../sol.cs | 45 + .../sol.dart | 41 + .../sol.go | 42 + .../sol.java | 41 + .../sol.kt | 36 + .../sol.py | 30 + .../sol.py2 | 30 + .../sol.rb | 29 + .../sol.rs | 39 + .../sol.swift | 43 + .../sol.ts | 45 + .../1518. water-bottles/manifest.yaml | 209 +++ tests/1501-2000/1518. water-bottles/sol.cpp | 6 + tests/1501-2000/1518. water-bottles/sol.cs | 5 + tests/1501-2000/1518. water-bottles/sol.dart | 5 + tests/1501-2000/1518. water-bottles/sol.go | 3 + tests/1501-2000/1518. water-bottles/sol.java | 5 + tests/1501-2000/1518. water-bottles/sol.kt | 5 + tests/1501-2000/1518. water-bottles/sol.py | 3 + tests/1501-2000/1518. water-bottles/sol.py2 | 8 + tests/1501-2000/1518. water-bottles/sol.rb | 6 + tests/1501-2000/1518. water-bottles/sol.rs | 5 + tests/1501-2000/1518. water-bottles/sol.swift | 5 + tests/1501-2000/1518. water-bottles/sol.ts | 3 + .../manifest.yaml | 728 ++++++++ .../sol.cpp | 38 + .../sol.cs | 44 + .../sol.dart | 37 + .../sol.go | 41 + .../sol.java | 42 + .../sol.kt | 38 + .../sol.py | 29 + .../sol.py2 | 31 + .../sol.rb | 36 + .../sol.rs | 43 + .../sol.swift | 39 + .../sol.ts | 36 + 3406 files changed, 183743 insertions(+), 1790 deletions(-) create mode 100644 tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/manifest.yaml create mode 100644 tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.cpp create mode 100644 tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.cs create mode 100644 tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.dart create mode 100644 tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.go create mode 100644 tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.java create mode 100644 tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.kt create mode 100644 tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.py create mode 100644 tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.py2 create mode 100644 tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.rb create mode 100644 tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.rs create mode 100644 tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.swift create mode 100644 tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.ts create mode 100644 tests/1001-1500/1131. maximum-of-absolute-value-expression/manifest.yaml create mode 100644 tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.cpp create mode 100644 tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.cs create mode 100644 tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.dart create mode 100644 tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.go create mode 100644 tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.java create mode 100644 tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.kt create mode 100644 tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.py create mode 100644 tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.py2 create mode 100644 tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.rb create mode 100644 tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.rs create mode 100644 tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.swift create mode 100644 tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.ts create mode 100644 tests/1001-1500/1137. n-th-tribonacci-number/manifest.yaml create mode 100644 tests/1001-1500/1137. n-th-tribonacci-number/sol.cpp create mode 100644 tests/1001-1500/1137. n-th-tribonacci-number/sol.cs create mode 100644 tests/1001-1500/1137. n-th-tribonacci-number/sol.dart create mode 100644 tests/1001-1500/1137. n-th-tribonacci-number/sol.go create mode 100644 tests/1001-1500/1137. n-th-tribonacci-number/sol.java create mode 100644 tests/1001-1500/1137. n-th-tribonacci-number/sol.kt create mode 100644 tests/1001-1500/1137. n-th-tribonacci-number/sol.py create mode 100644 tests/1001-1500/1137. n-th-tribonacci-number/sol.py2 create mode 100644 tests/1001-1500/1137. n-th-tribonacci-number/sol.rb create mode 100644 tests/1001-1500/1137. n-th-tribonacci-number/sol.rs create mode 100644 tests/1001-1500/1137. n-th-tribonacci-number/sol.swift create mode 100644 tests/1001-1500/1137. n-th-tribonacci-number/sol.ts create mode 100644 tests/1001-1500/1138. alphabet-board-path/manifest.yaml create mode 100644 tests/1001-1500/1138. alphabet-board-path/sol.cpp create mode 100644 tests/1001-1500/1138. alphabet-board-path/sol.cs create mode 100644 tests/1001-1500/1138. alphabet-board-path/sol.dart create mode 100644 tests/1001-1500/1138. alphabet-board-path/sol.go create mode 100644 tests/1001-1500/1138. alphabet-board-path/sol.java create mode 100644 tests/1001-1500/1138. alphabet-board-path/sol.kt create mode 100644 tests/1001-1500/1138. alphabet-board-path/sol.py create mode 100644 tests/1001-1500/1138. alphabet-board-path/sol.py2 create mode 100644 tests/1001-1500/1138. alphabet-board-path/sol.rb create mode 100644 tests/1001-1500/1138. alphabet-board-path/sol.rs create mode 100644 tests/1001-1500/1138. alphabet-board-path/sol.swift create mode 100644 tests/1001-1500/1138. alphabet-board-path/sol.ts create mode 100644 tests/1001-1500/1139. largest-1-bordered-square/manifest.yaml create mode 100644 tests/1001-1500/1139. largest-1-bordered-square/sol.cpp create mode 100644 tests/1001-1500/1139. largest-1-bordered-square/sol.cs create mode 100644 tests/1001-1500/1139. largest-1-bordered-square/sol.dart create mode 100644 tests/1001-1500/1139. largest-1-bordered-square/sol.go create mode 100644 tests/1001-1500/1139. largest-1-bordered-square/sol.java create mode 100644 tests/1001-1500/1139. largest-1-bordered-square/sol.kt create mode 100644 tests/1001-1500/1139. largest-1-bordered-square/sol.py create mode 100644 tests/1001-1500/1139. largest-1-bordered-square/sol.py2 create mode 100644 tests/1001-1500/1139. largest-1-bordered-square/sol.rb create mode 100644 tests/1001-1500/1139. largest-1-bordered-square/sol.rs create mode 100644 tests/1001-1500/1139. largest-1-bordered-square/sol.swift create mode 100644 tests/1001-1500/1139. largest-1-bordered-square/sol.ts create mode 100644 tests/1001-1500/1140. stone-game-ii/manifest.yaml create mode 100644 tests/1001-1500/1140. stone-game-ii/sol.cpp create mode 100644 tests/1001-1500/1140. stone-game-ii/sol.cs create mode 100644 tests/1001-1500/1140. stone-game-ii/sol.dart create mode 100644 tests/1001-1500/1140. stone-game-ii/sol.go create mode 100644 tests/1001-1500/1140. stone-game-ii/sol.java create mode 100644 tests/1001-1500/1140. stone-game-ii/sol.kt create mode 100644 tests/1001-1500/1140. stone-game-ii/sol.py create mode 100644 tests/1001-1500/1140. stone-game-ii/sol.py2 create mode 100644 tests/1001-1500/1140. stone-game-ii/sol.rb create mode 100644 tests/1001-1500/1140. stone-game-ii/sol.rs create mode 100644 tests/1001-1500/1140. stone-game-ii/sol.swift create mode 100644 tests/1001-1500/1140. stone-game-ii/sol.ts create mode 100644 tests/1001-1500/1143. longest-common-subsequence/manifest.yaml create mode 100644 tests/1001-1500/1143. longest-common-subsequence/sol.cpp create mode 100644 tests/1001-1500/1143. longest-common-subsequence/sol.cs create mode 100644 tests/1001-1500/1143. longest-common-subsequence/sol.dart create mode 100644 tests/1001-1500/1143. longest-common-subsequence/sol.go create mode 100644 tests/1001-1500/1143. longest-common-subsequence/sol.java create mode 100644 tests/1001-1500/1143. longest-common-subsequence/sol.kt create mode 100644 tests/1001-1500/1143. longest-common-subsequence/sol.py create mode 100644 tests/1001-1500/1143. longest-common-subsequence/sol.py2 create mode 100644 tests/1001-1500/1143. longest-common-subsequence/sol.rb create mode 100644 tests/1001-1500/1143. longest-common-subsequence/sol.rs create mode 100644 tests/1001-1500/1143. longest-common-subsequence/sol.swift create mode 100644 tests/1001-1500/1143. longest-common-subsequence/sol.ts create mode 100644 tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/manifest.yaml create mode 100644 tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.cpp create mode 100644 tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.cs create mode 100644 tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.dart create mode 100644 tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.go create mode 100644 tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.java create mode 100644 tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.kt create mode 100644 tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.py create mode 100644 tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.py2 create mode 100644 tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.rb create mode 100644 tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.rs create mode 100644 tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.swift create mode 100644 tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.ts create mode 100644 tests/1001-1500/1145. binary-tree-coloring-game/manifest.yaml create mode 100644 tests/1001-1500/1145. binary-tree-coloring-game/sol.cpp create mode 100644 tests/1001-1500/1145. binary-tree-coloring-game/sol.cs create mode 100644 tests/1001-1500/1145. binary-tree-coloring-game/sol.dart create mode 100644 tests/1001-1500/1145. binary-tree-coloring-game/sol.go create mode 100644 tests/1001-1500/1145. binary-tree-coloring-game/sol.java create mode 100644 tests/1001-1500/1145. binary-tree-coloring-game/sol.kt create mode 100644 tests/1001-1500/1145. binary-tree-coloring-game/sol.py create mode 100644 tests/1001-1500/1145. binary-tree-coloring-game/sol.py2 create mode 100644 tests/1001-1500/1145. binary-tree-coloring-game/sol.rb create mode 100644 tests/1001-1500/1145. binary-tree-coloring-game/sol.rs create mode 100644 tests/1001-1500/1145. binary-tree-coloring-game/sol.swift create mode 100644 tests/1001-1500/1145. binary-tree-coloring-game/sol.ts create mode 100644 tests/1001-1500/1147. longest-chunked-palindrome-decomposition/manifest.yaml create mode 100644 tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.cpp create mode 100644 tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.cs create mode 100644 tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.dart create mode 100644 tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.go create mode 100644 tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.java create mode 100644 tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.kt create mode 100644 tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.py create mode 100644 tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.py2 create mode 100644 tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.rb create mode 100644 tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.rs create mode 100644 tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.swift create mode 100644 tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.ts create mode 100644 tests/1001-1500/1154. day-of-the-year/manifest.yaml create mode 100644 tests/1001-1500/1154. day-of-the-year/sol.cpp create mode 100644 tests/1001-1500/1154. day-of-the-year/sol.cs create mode 100644 tests/1001-1500/1154. day-of-the-year/sol.dart create mode 100644 tests/1001-1500/1154. day-of-the-year/sol.go create mode 100644 tests/1001-1500/1154. day-of-the-year/sol.java create mode 100644 tests/1001-1500/1154. day-of-the-year/sol.kt create mode 100644 tests/1001-1500/1154. day-of-the-year/sol.py create mode 100644 tests/1001-1500/1154. day-of-the-year/sol.py2 create mode 100644 tests/1001-1500/1154. day-of-the-year/sol.rb create mode 100644 tests/1001-1500/1154. day-of-the-year/sol.rs create mode 100644 tests/1001-1500/1154. day-of-the-year/sol.swift create mode 100644 tests/1001-1500/1154. day-of-the-year/sol.ts create mode 100644 tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/manifest.yaml create mode 100644 tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.cpp create mode 100644 tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.cs create mode 100644 tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.dart create mode 100644 tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.go create mode 100644 tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.java create mode 100644 tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.kt create mode 100644 tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.py create mode 100644 tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.py2 create mode 100644 tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.rb create mode 100644 tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.rs create mode 100644 tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.swift create mode 100644 tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.ts create mode 100644 tests/1001-1500/1156. swap-for-longest-repeated-character-substring/manifest.yaml create mode 100644 tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.cpp create mode 100644 tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.cs create mode 100644 tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.dart create mode 100644 tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.go create mode 100644 tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.java create mode 100644 tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.kt create mode 100644 tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.py create mode 100644 tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.py2 create mode 100644 tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.rb create mode 100644 tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.rs create mode 100644 tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.swift create mode 100644 tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.ts create mode 100644 tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/manifest.yaml create mode 100644 tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.cpp create mode 100644 tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.cs create mode 100644 tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.dart create mode 100644 tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.go create mode 100644 tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.java create mode 100644 tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.kt create mode 100644 tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.py create mode 100644 tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.py2 create mode 100644 tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.rb create mode 100644 tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.rs create mode 100644 tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.swift create mode 100644 tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.ts create mode 100644 tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/manifest.yaml create mode 100644 tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.cpp create mode 100644 tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.cs create mode 100644 tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.dart create mode 100644 tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.go create mode 100644 tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.java create mode 100644 tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.kt create mode 100644 tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.py create mode 100644 tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.py2 create mode 100644 tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.rb create mode 100644 tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.rs create mode 100644 tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.swift create mode 100644 tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.ts create mode 100644 tests/1001-1500/1162. as-far-from-land-as-possible/manifest.yaml create mode 100644 tests/1001-1500/1162. as-far-from-land-as-possible/sol.cpp create mode 100644 tests/1001-1500/1162. as-far-from-land-as-possible/sol.cs create mode 100644 tests/1001-1500/1162. as-far-from-land-as-possible/sol.dart create mode 100644 tests/1001-1500/1162. as-far-from-land-as-possible/sol.go create mode 100644 tests/1001-1500/1162. as-far-from-land-as-possible/sol.java create mode 100644 tests/1001-1500/1162. as-far-from-land-as-possible/sol.kt create mode 100644 tests/1001-1500/1162. as-far-from-land-as-possible/sol.py create mode 100644 tests/1001-1500/1162. as-far-from-land-as-possible/sol.py2 create mode 100644 tests/1001-1500/1162. as-far-from-land-as-possible/sol.rb create mode 100644 tests/1001-1500/1162. as-far-from-land-as-possible/sol.rs create mode 100644 tests/1001-1500/1162. as-far-from-land-as-possible/sol.swift create mode 100644 tests/1001-1500/1162. as-far-from-land-as-possible/sol.ts create mode 100644 tests/1001-1500/1163. last-substring-in-lexicographical-order/manifest.yaml create mode 100644 tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.cpp create mode 100644 tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.cs create mode 100644 tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.dart create mode 100644 tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.go create mode 100644 tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.java create mode 100644 tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.kt create mode 100644 tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.py create mode 100644 tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.py2 create mode 100644 tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.rb create mode 100644 tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.rs create mode 100644 tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.swift create mode 100644 tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.ts create mode 100644 tests/1001-1500/1169. invalid-transactions/manifest.yaml create mode 100644 tests/1001-1500/1169. invalid-transactions/sol.cpp create mode 100644 tests/1001-1500/1169. invalid-transactions/sol.cs create mode 100644 tests/1001-1500/1169. invalid-transactions/sol.dart create mode 100644 tests/1001-1500/1169. invalid-transactions/sol.go create mode 100644 tests/1001-1500/1169. invalid-transactions/sol.java create mode 100644 tests/1001-1500/1169. invalid-transactions/sol.kt create mode 100644 tests/1001-1500/1169. invalid-transactions/sol.py create mode 100644 tests/1001-1500/1169. invalid-transactions/sol.py2 create mode 100644 tests/1001-1500/1169. invalid-transactions/sol.rb create mode 100644 tests/1001-1500/1169. invalid-transactions/sol.rs create mode 100644 tests/1001-1500/1169. invalid-transactions/sol.swift create mode 100644 tests/1001-1500/1169. invalid-transactions/sol.ts create mode 100644 tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/manifest.yaml create mode 100644 tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.cpp create mode 100644 tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.cs create mode 100644 tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.dart create mode 100644 tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.go create mode 100644 tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.java create mode 100644 tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.kt create mode 100644 tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.py create mode 100644 tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.py2 create mode 100644 tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.rb create mode 100644 tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.rs create mode 100644 tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.swift create mode 100644 tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.ts create mode 100644 tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/manifest.yaml create mode 100644 tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.cpp create mode 100644 tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.cs create mode 100644 tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.dart create mode 100644 tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.go create mode 100644 tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.java create mode 100644 tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.kt create mode 100644 tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.py create mode 100644 tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.py2 create mode 100644 tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.rb create mode 100644 tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.rs create mode 100644 tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.swift create mode 100644 tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.ts create mode 100644 tests/1001-1500/1175. prime-arrangements/manifest.yaml create mode 100644 tests/1001-1500/1175. prime-arrangements/sol.cpp create mode 100644 tests/1001-1500/1175. prime-arrangements/sol.cs create mode 100644 tests/1001-1500/1175. prime-arrangements/sol.dart create mode 100644 tests/1001-1500/1175. prime-arrangements/sol.go create mode 100644 tests/1001-1500/1175. prime-arrangements/sol.java create mode 100644 tests/1001-1500/1175. prime-arrangements/sol.kt create mode 100644 tests/1001-1500/1175. prime-arrangements/sol.py create mode 100644 tests/1001-1500/1175. prime-arrangements/sol.py2 create mode 100644 tests/1001-1500/1175. prime-arrangements/sol.rb create mode 100644 tests/1001-1500/1175. prime-arrangements/sol.rs create mode 100644 tests/1001-1500/1175. prime-arrangements/sol.swift create mode 100644 tests/1001-1500/1175. prime-arrangements/sol.ts create mode 100644 tests/1001-1500/1177. can-make-palindrome-from-substring/manifest.yaml create mode 100644 tests/1001-1500/1177. can-make-palindrome-from-substring/sol.cpp create mode 100644 tests/1001-1500/1177. can-make-palindrome-from-substring/sol.cs create mode 100644 tests/1001-1500/1177. can-make-palindrome-from-substring/sol.dart create mode 100644 tests/1001-1500/1177. can-make-palindrome-from-substring/sol.go create mode 100644 tests/1001-1500/1177. can-make-palindrome-from-substring/sol.java create mode 100644 tests/1001-1500/1177. can-make-palindrome-from-substring/sol.kt create mode 100644 tests/1001-1500/1177. can-make-palindrome-from-substring/sol.py create mode 100644 tests/1001-1500/1177. can-make-palindrome-from-substring/sol.py2 create mode 100644 tests/1001-1500/1177. can-make-palindrome-from-substring/sol.rb create mode 100644 tests/1001-1500/1177. can-make-palindrome-from-substring/sol.rs create mode 100644 tests/1001-1500/1177. can-make-palindrome-from-substring/sol.swift create mode 100644 tests/1001-1500/1177. can-make-palindrome-from-substring/sol.ts create mode 100644 tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/manifest.yaml create mode 100644 tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.cpp create mode 100644 tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.cs create mode 100644 tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.dart create mode 100644 tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.go create mode 100644 tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.java create mode 100644 tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.kt create mode 100644 tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.py create mode 100644 tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.py2 create mode 100644 tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.rb create mode 100644 tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.rs create mode 100644 tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.swift create mode 100644 tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.ts create mode 100644 tests/1001-1500/1184. distance-between-bus-stops/manifest.yaml create mode 100644 tests/1001-1500/1184. distance-between-bus-stops/sol.cpp create mode 100644 tests/1001-1500/1184. distance-between-bus-stops/sol.cs create mode 100644 tests/1001-1500/1184. distance-between-bus-stops/sol.dart create mode 100644 tests/1001-1500/1184. distance-between-bus-stops/sol.go create mode 100644 tests/1001-1500/1184. distance-between-bus-stops/sol.java create mode 100644 tests/1001-1500/1184. distance-between-bus-stops/sol.kt create mode 100644 tests/1001-1500/1184. distance-between-bus-stops/sol.py create mode 100644 tests/1001-1500/1184. distance-between-bus-stops/sol.py2 create mode 100644 tests/1001-1500/1184. distance-between-bus-stops/sol.rb create mode 100644 tests/1001-1500/1184. distance-between-bus-stops/sol.rs create mode 100644 tests/1001-1500/1184. distance-between-bus-stops/sol.swift create mode 100644 tests/1001-1500/1184. distance-between-bus-stops/sol.ts create mode 100644 tests/1001-1500/1185. day-of-the-week/manifest.yaml create mode 100644 tests/1001-1500/1185. day-of-the-week/sol.cpp create mode 100644 tests/1001-1500/1185. day-of-the-week/sol.cs create mode 100644 tests/1001-1500/1185. day-of-the-week/sol.dart create mode 100644 tests/1001-1500/1185. day-of-the-week/sol.go create mode 100644 tests/1001-1500/1185. day-of-the-week/sol.java create mode 100644 tests/1001-1500/1185. day-of-the-week/sol.kt create mode 100644 tests/1001-1500/1185. day-of-the-week/sol.py create mode 100644 tests/1001-1500/1185. day-of-the-week/sol.py2 create mode 100644 tests/1001-1500/1185. day-of-the-week/sol.rb create mode 100644 tests/1001-1500/1185. day-of-the-week/sol.rs create mode 100644 tests/1001-1500/1185. day-of-the-week/sol.swift create mode 100644 tests/1001-1500/1185. day-of-the-week/sol.ts create mode 100644 tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/manifest.yaml create mode 100644 tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.cpp create mode 100644 tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.cs create mode 100644 tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.dart create mode 100644 tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.go create mode 100644 tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.java create mode 100644 tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.kt create mode 100644 tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.py create mode 100644 tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.py2 create mode 100644 tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.rb create mode 100644 tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.rs create mode 100644 tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.swift create mode 100644 tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.ts create mode 100644 tests/1001-1500/1187. make-array-strictly-increasing/manifest.yaml create mode 100644 tests/1001-1500/1187. make-array-strictly-increasing/sol.cpp create mode 100644 tests/1001-1500/1187. make-array-strictly-increasing/sol.cs create mode 100644 tests/1001-1500/1187. make-array-strictly-increasing/sol.dart create mode 100644 tests/1001-1500/1187. make-array-strictly-increasing/sol.go create mode 100644 tests/1001-1500/1187. make-array-strictly-increasing/sol.java create mode 100644 tests/1001-1500/1187. make-array-strictly-increasing/sol.kt create mode 100644 tests/1001-1500/1187. make-array-strictly-increasing/sol.py create mode 100644 tests/1001-1500/1187. make-array-strictly-increasing/sol.py2 create mode 100644 tests/1001-1500/1187. make-array-strictly-increasing/sol.rb create mode 100644 tests/1001-1500/1187. make-array-strictly-increasing/sol.rs create mode 100644 tests/1001-1500/1187. make-array-strictly-increasing/sol.swift create mode 100644 tests/1001-1500/1187. make-array-strictly-increasing/sol.ts create mode 100644 tests/1001-1500/1189. maximum-number-of-balloons/manifest.yaml create mode 100644 tests/1001-1500/1189. maximum-number-of-balloons/sol.cpp create mode 100644 tests/1001-1500/1189. maximum-number-of-balloons/sol.cs create mode 100644 tests/1001-1500/1189. maximum-number-of-balloons/sol.dart create mode 100644 tests/1001-1500/1189. maximum-number-of-balloons/sol.go create mode 100644 tests/1001-1500/1189. maximum-number-of-balloons/sol.java create mode 100644 tests/1001-1500/1189. maximum-number-of-balloons/sol.kt create mode 100644 tests/1001-1500/1189. maximum-number-of-balloons/sol.py create mode 100644 tests/1001-1500/1189. maximum-number-of-balloons/sol.py2 create mode 100644 tests/1001-1500/1189. maximum-number-of-balloons/sol.rb create mode 100644 tests/1001-1500/1189. maximum-number-of-balloons/sol.rs create mode 100644 tests/1001-1500/1189. maximum-number-of-balloons/sol.swift create mode 100644 tests/1001-1500/1189. maximum-number-of-balloons/sol.ts create mode 100644 tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/manifest.yaml create mode 100644 tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.cpp create mode 100644 tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.cs create mode 100644 tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.dart create mode 100644 tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.go create mode 100644 tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.java create mode 100644 tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.kt create mode 100644 tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.py create mode 100644 tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.py2 create mode 100644 tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.rb create mode 100644 tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.rs create mode 100644 tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.swift create mode 100644 tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.ts create mode 100644 tests/1001-1500/1191. k-concatenation-maximum-sum/manifest.yaml create mode 100644 tests/1001-1500/1191. k-concatenation-maximum-sum/sol.cpp create mode 100644 tests/1001-1500/1191. k-concatenation-maximum-sum/sol.cs create mode 100644 tests/1001-1500/1191. k-concatenation-maximum-sum/sol.dart create mode 100644 tests/1001-1500/1191. k-concatenation-maximum-sum/sol.go create mode 100644 tests/1001-1500/1191. k-concatenation-maximum-sum/sol.java create mode 100644 tests/1001-1500/1191. k-concatenation-maximum-sum/sol.kt create mode 100644 tests/1001-1500/1191. k-concatenation-maximum-sum/sol.py create mode 100644 tests/1001-1500/1191. k-concatenation-maximum-sum/sol.py2 create mode 100644 tests/1001-1500/1191. k-concatenation-maximum-sum/sol.rb create mode 100644 tests/1001-1500/1191. k-concatenation-maximum-sum/sol.rs create mode 100644 tests/1001-1500/1191. k-concatenation-maximum-sum/sol.swift create mode 100644 tests/1001-1500/1191. k-concatenation-maximum-sum/sol.ts create mode 100644 tests/1001-1500/1192. critical-connections-in-a-network/manifest.yaml create mode 100644 tests/1001-1500/1192. critical-connections-in-a-network/sol.cpp create mode 100644 tests/1001-1500/1192. critical-connections-in-a-network/sol.cs create mode 100644 tests/1001-1500/1192. critical-connections-in-a-network/sol.dart create mode 100644 tests/1001-1500/1192. critical-connections-in-a-network/sol.go create mode 100644 tests/1001-1500/1192. critical-connections-in-a-network/sol.java create mode 100644 tests/1001-1500/1192. critical-connections-in-a-network/sol.kt create mode 100644 tests/1001-1500/1192. critical-connections-in-a-network/sol.py create mode 100644 tests/1001-1500/1192. critical-connections-in-a-network/sol.py2 create mode 100644 tests/1001-1500/1192. critical-connections-in-a-network/sol.rb create mode 100644 tests/1001-1500/1192. critical-connections-in-a-network/sol.rs create mode 100644 tests/1001-1500/1192. critical-connections-in-a-network/sol.swift create mode 100644 tests/1001-1500/1192. critical-connections-in-a-network/sol.ts create mode 100644 tests/1001-1500/1200. minimum-absolute-difference/manifest.yaml create mode 100644 tests/1001-1500/1200. minimum-absolute-difference/sol.cpp create mode 100644 tests/1001-1500/1200. minimum-absolute-difference/sol.cs create mode 100644 tests/1001-1500/1200. minimum-absolute-difference/sol.dart create mode 100644 tests/1001-1500/1200. minimum-absolute-difference/sol.go create mode 100644 tests/1001-1500/1200. minimum-absolute-difference/sol.java create mode 100644 tests/1001-1500/1200. minimum-absolute-difference/sol.kt create mode 100644 tests/1001-1500/1200. minimum-absolute-difference/sol.py create mode 100644 tests/1001-1500/1200. minimum-absolute-difference/sol.py2 create mode 100644 tests/1001-1500/1200. minimum-absolute-difference/sol.rb create mode 100644 tests/1001-1500/1200. minimum-absolute-difference/sol.rs create mode 100644 tests/1001-1500/1200. minimum-absolute-difference/sol.swift create mode 100644 tests/1001-1500/1200. minimum-absolute-difference/sol.ts create mode 100644 tests/1001-1500/1201. ugly-number-iii/manifest.yaml create mode 100644 tests/1001-1500/1201. ugly-number-iii/sol.cpp create mode 100644 tests/1001-1500/1201. ugly-number-iii/sol.cs create mode 100644 tests/1001-1500/1201. ugly-number-iii/sol.dart create mode 100644 tests/1001-1500/1201. ugly-number-iii/sol.go create mode 100644 tests/1001-1500/1201. ugly-number-iii/sol.java create mode 100644 tests/1001-1500/1201. ugly-number-iii/sol.kt create mode 100644 tests/1001-1500/1201. ugly-number-iii/sol.py create mode 100644 tests/1001-1500/1201. ugly-number-iii/sol.py2 create mode 100644 tests/1001-1500/1201. ugly-number-iii/sol.rb create mode 100644 tests/1001-1500/1201. ugly-number-iii/sol.rs create mode 100644 tests/1001-1500/1201. ugly-number-iii/sol.swift create mode 100644 tests/1001-1500/1201. ugly-number-iii/sol.ts create mode 100644 tests/1001-1500/1202. smallest-string-with-swaps/manifest.yaml create mode 100644 tests/1001-1500/1202. smallest-string-with-swaps/sol.cpp create mode 100644 tests/1001-1500/1202. smallest-string-with-swaps/sol.cs create mode 100644 tests/1001-1500/1202. smallest-string-with-swaps/sol.dart create mode 100644 tests/1001-1500/1202. smallest-string-with-swaps/sol.go create mode 100644 tests/1001-1500/1202. smallest-string-with-swaps/sol.java create mode 100644 tests/1001-1500/1202. smallest-string-with-swaps/sol.kt create mode 100644 tests/1001-1500/1202. smallest-string-with-swaps/sol.py create mode 100644 tests/1001-1500/1202. smallest-string-with-swaps/sol.py2 create mode 100644 tests/1001-1500/1202. smallest-string-with-swaps/sol.rb create mode 100644 tests/1001-1500/1202. smallest-string-with-swaps/sol.rs create mode 100644 tests/1001-1500/1202. smallest-string-with-swaps/sol.swift create mode 100644 tests/1001-1500/1202. smallest-string-with-swaps/sol.ts create mode 100644 tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/manifest.yaml create mode 100644 tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.cpp create mode 100644 tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.cs create mode 100644 tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.dart create mode 100644 tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.go create mode 100644 tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.java create mode 100644 tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.kt create mode 100644 tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.py create mode 100644 tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.py2 create mode 100644 tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.rb create mode 100644 tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.rs create mode 100644 tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.swift create mode 100644 tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.ts create mode 100644 tests/1001-1500/1207. unique-number-of-occurrences/manifest.yaml create mode 100644 tests/1001-1500/1207. unique-number-of-occurrences/sol.cpp create mode 100644 tests/1001-1500/1207. unique-number-of-occurrences/sol.cs create mode 100644 tests/1001-1500/1207. unique-number-of-occurrences/sol.dart create mode 100644 tests/1001-1500/1207. unique-number-of-occurrences/sol.go create mode 100644 tests/1001-1500/1207. unique-number-of-occurrences/sol.java create mode 100644 tests/1001-1500/1207. unique-number-of-occurrences/sol.kt create mode 100644 tests/1001-1500/1207. unique-number-of-occurrences/sol.py create mode 100644 tests/1001-1500/1207. unique-number-of-occurrences/sol.py2 create mode 100644 tests/1001-1500/1207. unique-number-of-occurrences/sol.rb create mode 100644 tests/1001-1500/1207. unique-number-of-occurrences/sol.rs create mode 100644 tests/1001-1500/1207. unique-number-of-occurrences/sol.swift create mode 100644 tests/1001-1500/1207. unique-number-of-occurrences/sol.ts create mode 100644 tests/1001-1500/1208. get-equal-substrings-within-budget/manifest.yaml create mode 100644 tests/1001-1500/1208. get-equal-substrings-within-budget/sol.cpp create mode 100644 tests/1001-1500/1208. get-equal-substrings-within-budget/sol.cs create mode 100644 tests/1001-1500/1208. get-equal-substrings-within-budget/sol.dart create mode 100644 tests/1001-1500/1208. get-equal-substrings-within-budget/sol.go create mode 100644 tests/1001-1500/1208. get-equal-substrings-within-budget/sol.java create mode 100644 tests/1001-1500/1208. get-equal-substrings-within-budget/sol.kt create mode 100644 tests/1001-1500/1208. get-equal-substrings-within-budget/sol.py create mode 100644 tests/1001-1500/1208. get-equal-substrings-within-budget/sol.py2 create mode 100644 tests/1001-1500/1208. get-equal-substrings-within-budget/sol.rb create mode 100644 tests/1001-1500/1208. get-equal-substrings-within-budget/sol.rs create mode 100644 tests/1001-1500/1208. get-equal-substrings-within-budget/sol.swift create mode 100644 tests/1001-1500/1208. get-equal-substrings-within-budget/sol.ts create mode 100644 tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/manifest.yaml create mode 100644 tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.cpp create mode 100644 tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.cs create mode 100644 tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.dart create mode 100644 tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.go create mode 100644 tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.java create mode 100644 tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.kt create mode 100644 tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.py create mode 100644 tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.py2 create mode 100644 tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.rb create mode 100644 tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.rs create mode 100644 tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.swift create mode 100644 tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.ts create mode 100644 tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/manifest.yaml create mode 100644 tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.cpp create mode 100644 tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.cs create mode 100644 tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.dart create mode 100644 tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.go create mode 100644 tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.java create mode 100644 tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.kt create mode 100644 tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.py create mode 100644 tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.py2 create mode 100644 tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.rb create mode 100644 tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.rs create mode 100644 tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.swift create mode 100644 tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.ts create mode 100644 tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/manifest.yaml create mode 100644 tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.cpp create mode 100644 tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.cs create mode 100644 tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.dart create mode 100644 tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.go create mode 100644 tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.java create mode 100644 tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.kt create mode 100644 tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.py create mode 100644 tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.py2 create mode 100644 tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.rb create mode 100644 tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.rs create mode 100644 tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.swift create mode 100644 tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.ts create mode 100644 tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/manifest.yaml create mode 100644 tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.cpp create mode 100644 tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.cs create mode 100644 tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.dart create mode 100644 tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.go create mode 100644 tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.java create mode 100644 tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.kt create mode 100644 tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.py create mode 100644 tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.py2 create mode 100644 tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.rb create mode 100644 tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.rs create mode 100644 tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.swift create mode 100644 tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.ts create mode 100644 tests/1001-1500/1219. path-with-maximum-gold/manifest.yaml create mode 100644 tests/1001-1500/1219. path-with-maximum-gold/sol.cpp create mode 100644 tests/1001-1500/1219. path-with-maximum-gold/sol.cs create mode 100644 tests/1001-1500/1219. path-with-maximum-gold/sol.dart create mode 100644 tests/1001-1500/1219. path-with-maximum-gold/sol.go create mode 100644 tests/1001-1500/1219. path-with-maximum-gold/sol.java create mode 100644 tests/1001-1500/1219. path-with-maximum-gold/sol.kt create mode 100644 tests/1001-1500/1219. path-with-maximum-gold/sol.py create mode 100644 tests/1001-1500/1219. path-with-maximum-gold/sol.py2 create mode 100644 tests/1001-1500/1219. path-with-maximum-gold/sol.rb create mode 100644 tests/1001-1500/1219. path-with-maximum-gold/sol.rs create mode 100644 tests/1001-1500/1219. path-with-maximum-gold/sol.swift create mode 100644 tests/1001-1500/1219. path-with-maximum-gold/sol.ts create mode 100644 tests/1001-1500/1220. count-vowels-permutation/manifest.yaml create mode 100644 tests/1001-1500/1220. count-vowels-permutation/sol.cpp create mode 100644 tests/1001-1500/1220. count-vowels-permutation/sol.cs create mode 100644 tests/1001-1500/1220. count-vowels-permutation/sol.dart create mode 100644 tests/1001-1500/1220. count-vowels-permutation/sol.go create mode 100644 tests/1001-1500/1220. count-vowels-permutation/sol.java create mode 100644 tests/1001-1500/1220. count-vowels-permutation/sol.kt create mode 100644 tests/1001-1500/1220. count-vowels-permutation/sol.py create mode 100644 tests/1001-1500/1220. count-vowels-permutation/sol.py2 create mode 100644 tests/1001-1500/1220. count-vowels-permutation/sol.rb create mode 100644 tests/1001-1500/1220. count-vowels-permutation/sol.rs create mode 100644 tests/1001-1500/1220. count-vowels-permutation/sol.swift create mode 100644 tests/1001-1500/1220. count-vowels-permutation/sol.ts create mode 100644 tests/1001-1500/1221. split-a-string-in-balanced-strings/manifest.yaml create mode 100644 tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.cpp create mode 100644 tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.cs create mode 100644 tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.dart create mode 100644 tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.go create mode 100644 tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.java create mode 100644 tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.kt create mode 100644 tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.py create mode 100644 tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.py2 create mode 100644 tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.rb create mode 100644 tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.rs create mode 100644 tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.swift create mode 100644 tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.ts create mode 100644 tests/1001-1500/1222. queens-that-can-attack-the-king/manifest.yaml create mode 100644 tests/1001-1500/1222. queens-that-can-attack-the-king/sol.cpp create mode 100644 tests/1001-1500/1222. queens-that-can-attack-the-king/sol.cs create mode 100644 tests/1001-1500/1222. queens-that-can-attack-the-king/sol.dart create mode 100644 tests/1001-1500/1222. queens-that-can-attack-the-king/sol.go create mode 100644 tests/1001-1500/1222. queens-that-can-attack-the-king/sol.java create mode 100644 tests/1001-1500/1222. queens-that-can-attack-the-king/sol.kt create mode 100644 tests/1001-1500/1222. queens-that-can-attack-the-king/sol.py create mode 100644 tests/1001-1500/1222. queens-that-can-attack-the-king/sol.py2 create mode 100644 tests/1001-1500/1222. queens-that-can-attack-the-king/sol.rb create mode 100644 tests/1001-1500/1222. queens-that-can-attack-the-king/sol.rs create mode 100644 tests/1001-1500/1222. queens-that-can-attack-the-king/sol.swift create mode 100644 tests/1001-1500/1222. queens-that-can-attack-the-king/sol.ts create mode 100644 tests/1001-1500/1223. dice-roll-simulation/manifest.yaml create mode 100644 tests/1001-1500/1223. dice-roll-simulation/sol.cpp create mode 100644 tests/1001-1500/1223. dice-roll-simulation/sol.cs create mode 100644 tests/1001-1500/1223. dice-roll-simulation/sol.dart create mode 100644 tests/1001-1500/1223. dice-roll-simulation/sol.go create mode 100644 tests/1001-1500/1223. dice-roll-simulation/sol.java create mode 100644 tests/1001-1500/1223. dice-roll-simulation/sol.kt create mode 100644 tests/1001-1500/1223. dice-roll-simulation/sol.py create mode 100644 tests/1001-1500/1223. dice-roll-simulation/sol.py2 create mode 100644 tests/1001-1500/1223. dice-roll-simulation/sol.rb create mode 100644 tests/1001-1500/1223. dice-roll-simulation/sol.rs create mode 100644 tests/1001-1500/1223. dice-roll-simulation/sol.swift create mode 100644 tests/1001-1500/1223. dice-roll-simulation/sol.ts create mode 100644 tests/1001-1500/1224. maximum-equal-frequency/manifest.yaml create mode 100644 tests/1001-1500/1224. maximum-equal-frequency/sol.cpp create mode 100644 tests/1001-1500/1224. maximum-equal-frequency/sol.cs create mode 100644 tests/1001-1500/1224. maximum-equal-frequency/sol.dart create mode 100644 tests/1001-1500/1224. maximum-equal-frequency/sol.go create mode 100644 tests/1001-1500/1224. maximum-equal-frequency/sol.java create mode 100644 tests/1001-1500/1224. maximum-equal-frequency/sol.kt create mode 100644 tests/1001-1500/1224. maximum-equal-frequency/sol.py create mode 100644 tests/1001-1500/1224. maximum-equal-frequency/sol.py2 create mode 100644 tests/1001-1500/1224. maximum-equal-frequency/sol.rb create mode 100644 tests/1001-1500/1224. maximum-equal-frequency/sol.rs create mode 100644 tests/1001-1500/1224. maximum-equal-frequency/sol.swift create mode 100644 tests/1001-1500/1224. maximum-equal-frequency/sol.ts create mode 100644 tests/1001-1500/1227. airplane-seat-assignment-probability/manifest.yaml create mode 100644 tests/1001-1500/1227. airplane-seat-assignment-probability/sol.cpp create mode 100644 tests/1001-1500/1227. airplane-seat-assignment-probability/sol.cs create mode 100644 tests/1001-1500/1227. airplane-seat-assignment-probability/sol.dart create mode 100644 tests/1001-1500/1227. airplane-seat-assignment-probability/sol.go create mode 100644 tests/1001-1500/1227. airplane-seat-assignment-probability/sol.java create mode 100644 tests/1001-1500/1227. airplane-seat-assignment-probability/sol.kt create mode 100644 tests/1001-1500/1227. airplane-seat-assignment-probability/sol.py create mode 100644 tests/1001-1500/1227. airplane-seat-assignment-probability/sol.py2 create mode 100644 tests/1001-1500/1227. airplane-seat-assignment-probability/sol.rb create mode 100644 tests/1001-1500/1227. airplane-seat-assignment-probability/sol.rs create mode 100644 tests/1001-1500/1227. airplane-seat-assignment-probability/sol.swift create mode 100644 tests/1001-1500/1227. airplane-seat-assignment-probability/sol.ts create mode 100644 tests/1001-1500/1232. check-if-it-is-a-straight-line/manifest.yaml create mode 100644 tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.cpp create mode 100644 tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.cs create mode 100644 tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.dart create mode 100644 tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.go create mode 100644 tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.java create mode 100644 tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.kt create mode 100644 tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.py create mode 100644 tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.py2 create mode 100644 tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.rb create mode 100644 tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.rs create mode 100644 tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.swift create mode 100644 tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.ts create mode 100644 tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/manifest.yaml create mode 100644 tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.cpp create mode 100644 tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.cs create mode 100644 tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.dart create mode 100644 tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.go create mode 100644 tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.java create mode 100644 tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.kt create mode 100644 tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.py create mode 100644 tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.py2 create mode 100644 tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.rb create mode 100644 tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.rs create mode 100644 tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.swift create mode 100644 tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.ts create mode 100644 tests/1001-1500/1234. replace-the-substring-for-balanced-string/manifest.yaml create mode 100644 tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.cpp create mode 100644 tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.cs create mode 100644 tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.dart create mode 100644 tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.go create mode 100644 tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.java create mode 100644 tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.kt create mode 100644 tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.py create mode 100644 tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.py2 create mode 100644 tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.rb create mode 100644 tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.rs create mode 100644 tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.swift create mode 100644 tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.ts create mode 100644 tests/1001-1500/1235. maximum-profit-in-job-scheduling/manifest.yaml create mode 100644 tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.cpp create mode 100644 tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.cs create mode 100644 tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.dart create mode 100644 tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.go create mode 100644 tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.java create mode 100644 tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.kt create mode 100644 tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.py create mode 100644 tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.py2 create mode 100644 tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.rb create mode 100644 tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.rs create mode 100644 tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.swift create mode 100644 tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.ts create mode 100644 tests/1001-1500/1238. circular-permutation-in-binary-representation/manifest.yaml create mode 100644 tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.cpp create mode 100644 tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.cs create mode 100644 tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.dart create mode 100644 tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.go create mode 100644 tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.java create mode 100644 tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.kt create mode 100644 tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.py create mode 100644 tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.py2 create mode 100644 tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.rb create mode 100644 tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.rs create mode 100644 tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.swift create mode 100644 tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.ts create mode 100644 tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/manifest.yaml create mode 100644 tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.cpp create mode 100644 tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.cs create mode 100644 tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.dart create mode 100644 tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.go create mode 100644 tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.java create mode 100644 tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.kt create mode 100644 tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.py create mode 100644 tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.py2 create mode 100644 tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.rb create mode 100644 tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.rs create mode 100644 tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.swift create mode 100644 tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.ts create mode 100644 tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/manifest.yaml create mode 100644 tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.cpp create mode 100644 tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.cs create mode 100644 tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.dart create mode 100644 tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.go create mode 100644 tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.java create mode 100644 tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.kt create mode 100644 tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.py create mode 100644 tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.py2 create mode 100644 tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.rb create mode 100644 tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.rs create mode 100644 tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.swift create mode 100644 tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.ts create mode 100644 tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/manifest.yaml create mode 100644 tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.cpp create mode 100644 tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.cs create mode 100644 tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.dart create mode 100644 tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.go create mode 100644 tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.java create mode 100644 tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.kt create mode 100644 tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.py create mode 100644 tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.py2 create mode 100644 tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.rb create mode 100644 tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.rs create mode 100644 tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.swift create mode 100644 tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.ts create mode 100644 tests/1001-1500/1248. count-number-of-nice-subarrays/manifest.yaml create mode 100644 tests/1001-1500/1248. count-number-of-nice-subarrays/sol.cpp create mode 100644 tests/1001-1500/1248. count-number-of-nice-subarrays/sol.cs create mode 100644 tests/1001-1500/1248. count-number-of-nice-subarrays/sol.dart create mode 100644 tests/1001-1500/1248. count-number-of-nice-subarrays/sol.go create mode 100644 tests/1001-1500/1248. count-number-of-nice-subarrays/sol.java create mode 100644 tests/1001-1500/1248. count-number-of-nice-subarrays/sol.kt create mode 100644 tests/1001-1500/1248. count-number-of-nice-subarrays/sol.py create mode 100644 tests/1001-1500/1248. count-number-of-nice-subarrays/sol.py2 create mode 100644 tests/1001-1500/1248. count-number-of-nice-subarrays/sol.rb create mode 100644 tests/1001-1500/1248. count-number-of-nice-subarrays/sol.rs create mode 100644 tests/1001-1500/1248. count-number-of-nice-subarrays/sol.swift create mode 100644 tests/1001-1500/1248. count-number-of-nice-subarrays/sol.ts create mode 100644 tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/manifest.yaml create mode 100644 tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.cpp create mode 100644 tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.cs create mode 100644 tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.dart create mode 100644 tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.go create mode 100644 tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.java create mode 100644 tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.kt create mode 100644 tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.py create mode 100644 tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.py2 create mode 100644 tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.rb create mode 100644 tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.rs create mode 100644 tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.swift create mode 100644 tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.ts create mode 100644 tests/1001-1500/1250. check-if-it-is-a-good-array/manifest.yaml create mode 100644 tests/1001-1500/1250. check-if-it-is-a-good-array/sol.cpp create mode 100644 tests/1001-1500/1250. check-if-it-is-a-good-array/sol.cs create mode 100644 tests/1001-1500/1250. check-if-it-is-a-good-array/sol.dart create mode 100644 tests/1001-1500/1250. check-if-it-is-a-good-array/sol.go create mode 100644 tests/1001-1500/1250. check-if-it-is-a-good-array/sol.java create mode 100644 tests/1001-1500/1250. check-if-it-is-a-good-array/sol.kt create mode 100644 tests/1001-1500/1250. check-if-it-is-a-good-array/sol.py create mode 100644 tests/1001-1500/1250. check-if-it-is-a-good-array/sol.py2 create mode 100644 tests/1001-1500/1250. check-if-it-is-a-good-array/sol.rb create mode 100644 tests/1001-1500/1250. check-if-it-is-a-good-array/sol.rs create mode 100644 tests/1001-1500/1250. check-if-it-is-a-good-array/sol.swift create mode 100644 tests/1001-1500/1250. check-if-it-is-a-good-array/sol.ts create mode 100644 tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/manifest.yaml create mode 100644 tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.cpp create mode 100644 tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.cs create mode 100644 tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.dart create mode 100644 tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.go create mode 100644 tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.java create mode 100644 tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.kt create mode 100644 tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.py create mode 100644 tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.py2 create mode 100644 tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.rb create mode 100644 tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.rs create mode 100644 tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.swift create mode 100644 tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.ts create mode 100644 tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/manifest.yaml create mode 100644 tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.cpp create mode 100644 tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.cs create mode 100644 tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.dart create mode 100644 tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.go create mode 100644 tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.java create mode 100644 tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.kt create mode 100644 tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.py create mode 100644 tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.py2 create mode 100644 tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.rb create mode 100644 tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.rs create mode 100644 tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.swift create mode 100644 tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.ts create mode 100644 tests/1001-1500/1254. number-of-closed-islands/manifest.yaml create mode 100644 tests/1001-1500/1254. number-of-closed-islands/sol.cpp create mode 100644 tests/1001-1500/1254. number-of-closed-islands/sol.cs create mode 100644 tests/1001-1500/1254. number-of-closed-islands/sol.dart create mode 100644 tests/1001-1500/1254. number-of-closed-islands/sol.go create mode 100644 tests/1001-1500/1254. number-of-closed-islands/sol.java create mode 100644 tests/1001-1500/1254. number-of-closed-islands/sol.kt create mode 100644 tests/1001-1500/1254. number-of-closed-islands/sol.py create mode 100644 tests/1001-1500/1254. number-of-closed-islands/sol.py2 create mode 100644 tests/1001-1500/1254. number-of-closed-islands/sol.rb create mode 100644 tests/1001-1500/1254. number-of-closed-islands/sol.rs create mode 100644 tests/1001-1500/1254. number-of-closed-islands/sol.swift create mode 100644 tests/1001-1500/1254. number-of-closed-islands/sol.ts create mode 100644 tests/1001-1500/1255. maximum-score-words-formed-by-letters/manifest.yaml create mode 100644 tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.cpp create mode 100644 tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.cs create mode 100644 tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.dart create mode 100644 tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.go create mode 100644 tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.java create mode 100644 tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.kt create mode 100644 tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.py create mode 100644 tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.py2 create mode 100644 tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.rb create mode 100644 tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.rs create mode 100644 tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.swift create mode 100644 tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.ts create mode 100644 tests/1001-1500/1260. shift-2d-grid/manifest.yaml create mode 100644 tests/1001-1500/1260. shift-2d-grid/sol.cpp create mode 100644 tests/1001-1500/1260. shift-2d-grid/sol.cs create mode 100644 tests/1001-1500/1260. shift-2d-grid/sol.dart create mode 100644 tests/1001-1500/1260. shift-2d-grid/sol.go create mode 100644 tests/1001-1500/1260. shift-2d-grid/sol.java create mode 100644 tests/1001-1500/1260. shift-2d-grid/sol.kt create mode 100644 tests/1001-1500/1260. shift-2d-grid/sol.py create mode 100644 tests/1001-1500/1260. shift-2d-grid/sol.py2 create mode 100644 tests/1001-1500/1260. shift-2d-grid/sol.rb create mode 100644 tests/1001-1500/1260. shift-2d-grid/sol.rs create mode 100644 tests/1001-1500/1260. shift-2d-grid/sol.swift create mode 100644 tests/1001-1500/1260. shift-2d-grid/sol.ts create mode 100644 tests/1001-1500/1262. greatest-sum-divisible-by-three/manifest.yaml create mode 100644 tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.cpp create mode 100644 tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.cs create mode 100644 tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.dart create mode 100644 tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.go create mode 100644 tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.java create mode 100644 tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.kt create mode 100644 tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.py create mode 100644 tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.py2 create mode 100644 tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.rb create mode 100644 tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.rs create mode 100644 tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.swift create mode 100644 tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.ts create mode 100644 tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/manifest.yaml create mode 100644 tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.cpp create mode 100644 tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.cs create mode 100644 tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.dart create mode 100644 tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.go create mode 100644 tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.java create mode 100644 tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.kt create mode 100644 tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.py create mode 100644 tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.py2 create mode 100644 tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.rb create mode 100644 tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.rs create mode 100644 tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.swift create mode 100644 tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.ts create mode 100644 tests/1001-1500/1266. minimum-time-visiting-all-points/manifest.yaml create mode 100644 tests/1001-1500/1266. minimum-time-visiting-all-points/sol.cpp create mode 100644 tests/1001-1500/1266. minimum-time-visiting-all-points/sol.cs create mode 100644 tests/1001-1500/1266. minimum-time-visiting-all-points/sol.dart create mode 100644 tests/1001-1500/1266. minimum-time-visiting-all-points/sol.go create mode 100644 tests/1001-1500/1266. minimum-time-visiting-all-points/sol.java create mode 100644 tests/1001-1500/1266. minimum-time-visiting-all-points/sol.kt create mode 100644 tests/1001-1500/1266. minimum-time-visiting-all-points/sol.py create mode 100644 tests/1001-1500/1266. minimum-time-visiting-all-points/sol.py2 create mode 100644 tests/1001-1500/1266. minimum-time-visiting-all-points/sol.rb create mode 100644 tests/1001-1500/1266. minimum-time-visiting-all-points/sol.rs create mode 100644 tests/1001-1500/1266. minimum-time-visiting-all-points/sol.swift create mode 100644 tests/1001-1500/1266. minimum-time-visiting-all-points/sol.ts create mode 100644 tests/1001-1500/1267. count-servers-that-communicate/manifest.yaml create mode 100644 tests/1001-1500/1267. count-servers-that-communicate/sol.cpp create mode 100644 tests/1001-1500/1267. count-servers-that-communicate/sol.cs create mode 100644 tests/1001-1500/1267. count-servers-that-communicate/sol.dart create mode 100644 tests/1001-1500/1267. count-servers-that-communicate/sol.go create mode 100644 tests/1001-1500/1267. count-servers-that-communicate/sol.java create mode 100644 tests/1001-1500/1267. count-servers-that-communicate/sol.kt create mode 100644 tests/1001-1500/1267. count-servers-that-communicate/sol.py create mode 100644 tests/1001-1500/1267. count-servers-that-communicate/sol.py2 create mode 100644 tests/1001-1500/1267. count-servers-that-communicate/sol.rb create mode 100644 tests/1001-1500/1267. count-servers-that-communicate/sol.rs create mode 100644 tests/1001-1500/1267. count-servers-that-communicate/sol.swift create mode 100644 tests/1001-1500/1267. count-servers-that-communicate/sol.ts create mode 100644 tests/1001-1500/1268. search-suggestions-system/manifest.yaml create mode 100644 tests/1001-1500/1268. search-suggestions-system/sol.cpp create mode 100644 tests/1001-1500/1268. search-suggestions-system/sol.cs create mode 100644 tests/1001-1500/1268. search-suggestions-system/sol.dart create mode 100644 tests/1001-1500/1268. search-suggestions-system/sol.go create mode 100644 tests/1001-1500/1268. search-suggestions-system/sol.java create mode 100644 tests/1001-1500/1268. search-suggestions-system/sol.kt create mode 100644 tests/1001-1500/1268. search-suggestions-system/sol.py create mode 100644 tests/1001-1500/1268. search-suggestions-system/sol.py2 create mode 100644 tests/1001-1500/1268. search-suggestions-system/sol.rb create mode 100644 tests/1001-1500/1268. search-suggestions-system/sol.rs create mode 100644 tests/1001-1500/1268. search-suggestions-system/sol.swift create mode 100644 tests/1001-1500/1268. search-suggestions-system/sol.ts create mode 100644 tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/manifest.yaml create mode 100644 tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.cpp create mode 100644 tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.cs create mode 100644 tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.dart create mode 100644 tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.go create mode 100644 tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.java create mode 100644 tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.kt create mode 100644 tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.py create mode 100644 tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.py2 create mode 100644 tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.rb create mode 100644 tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.rs create mode 100644 tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.swift create mode 100644 tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.ts create mode 100644 tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/manifest.yaml create mode 100644 tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.cpp create mode 100644 tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.cs create mode 100644 tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.dart create mode 100644 tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.go create mode 100644 tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.java create mode 100644 tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.kt create mode 100644 tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.py create mode 100644 tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.py2 create mode 100644 tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.rb create mode 100644 tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.rs create mode 100644 tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.swift create mode 100644 tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.ts create mode 100644 tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/manifest.yaml create mode 100644 tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.cpp create mode 100644 tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.cs create mode 100644 tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.dart create mode 100644 tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.go create mode 100644 tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.java create mode 100644 tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.kt create mode 100644 tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.py create mode 100644 tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.py2 create mode 100644 tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.rb create mode 100644 tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.rs create mode 100644 tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.swift create mode 100644 tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.ts create mode 100644 tests/1001-1500/1277. count-square-submatrices-with-all-ones/manifest.yaml create mode 100644 tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.cpp create mode 100644 tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.cs create mode 100644 tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.dart create mode 100644 tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.go create mode 100644 tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.java create mode 100644 tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.kt create mode 100644 tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.py create mode 100644 tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.py2 create mode 100644 tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.rb create mode 100644 tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.rs create mode 100644 tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.swift create mode 100644 tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.ts create mode 100644 tests/1001-1500/1278. palindrome-partitioning-iii/manifest.yaml create mode 100644 tests/1001-1500/1278. palindrome-partitioning-iii/sol.cpp create mode 100644 tests/1001-1500/1278. palindrome-partitioning-iii/sol.cs create mode 100644 tests/1001-1500/1278. palindrome-partitioning-iii/sol.dart create mode 100644 tests/1001-1500/1278. palindrome-partitioning-iii/sol.go create mode 100644 tests/1001-1500/1278. palindrome-partitioning-iii/sol.java create mode 100644 tests/1001-1500/1278. palindrome-partitioning-iii/sol.kt create mode 100644 tests/1001-1500/1278. palindrome-partitioning-iii/sol.py create mode 100644 tests/1001-1500/1278. palindrome-partitioning-iii/sol.py2 create mode 100644 tests/1001-1500/1278. palindrome-partitioning-iii/sol.rb create mode 100644 tests/1001-1500/1278. palindrome-partitioning-iii/sol.rs create mode 100644 tests/1001-1500/1278. palindrome-partitioning-iii/sol.swift create mode 100644 tests/1001-1500/1278. palindrome-partitioning-iii/sol.ts create mode 100644 tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/manifest.yaml create mode 100644 tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.cpp create mode 100644 tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.cs create mode 100644 tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.dart create mode 100644 tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.go create mode 100644 tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.java create mode 100644 tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.kt create mode 100644 tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.py create mode 100644 tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.py2 create mode 100644 tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.rb create mode 100644 tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.rs create mode 100644 tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.swift create mode 100644 tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.ts create mode 100644 tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/manifest.yaml create mode 100644 tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.cpp create mode 100644 tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.cs create mode 100644 tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.dart create mode 100644 tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.go create mode 100644 tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.java create mode 100644 tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.kt create mode 100644 tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.py create mode 100644 tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.py2 create mode 100644 tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.rb create mode 100644 tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.rs create mode 100644 tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.swift create mode 100644 tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.ts create mode 100644 tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/manifest.yaml create mode 100644 tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.cpp create mode 100644 tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.cs create mode 100644 tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.dart create mode 100644 tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.go create mode 100644 tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.java create mode 100644 tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.kt create mode 100644 tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.py create mode 100644 tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.py2 create mode 100644 tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.rb create mode 100644 tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.rs create mode 100644 tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.swift create mode 100644 tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.ts create mode 100644 tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/manifest.yaml create mode 100644 tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.cpp create mode 100644 tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.cs create mode 100644 tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.dart create mode 100644 tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.go create mode 100644 tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.java create mode 100644 tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.kt create mode 100644 tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.py create mode 100644 tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.py2 create mode 100644 tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.rb create mode 100644 tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.rs create mode 100644 tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.swift create mode 100644 tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.ts create mode 100644 tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/manifest.yaml create mode 100644 tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.cpp create mode 100644 tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.cs create mode 100644 tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.dart create mode 100644 tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.go create mode 100644 tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.java create mode 100644 tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.kt create mode 100644 tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.py create mode 100644 tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.py2 create mode 100644 tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.rb create mode 100644 tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.rs create mode 100644 tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.swift create mode 100644 tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.ts create mode 100644 tests/1001-1500/1288. remove-covered-intervals/manifest.yaml create mode 100644 tests/1001-1500/1288. remove-covered-intervals/sol.cpp create mode 100644 tests/1001-1500/1288. remove-covered-intervals/sol.cs create mode 100644 tests/1001-1500/1288. remove-covered-intervals/sol.dart create mode 100644 tests/1001-1500/1288. remove-covered-intervals/sol.go create mode 100644 tests/1001-1500/1288. remove-covered-intervals/sol.java create mode 100644 tests/1001-1500/1288. remove-covered-intervals/sol.kt create mode 100644 tests/1001-1500/1288. remove-covered-intervals/sol.py create mode 100644 tests/1001-1500/1288. remove-covered-intervals/sol.py2 create mode 100644 tests/1001-1500/1288. remove-covered-intervals/sol.rb create mode 100644 tests/1001-1500/1288. remove-covered-intervals/sol.rs create mode 100644 tests/1001-1500/1288. remove-covered-intervals/sol.swift create mode 100644 tests/1001-1500/1288. remove-covered-intervals/sol.ts create mode 100644 tests/1001-1500/1289. minimum-falling-path-sum-ii/manifest.yaml create mode 100644 tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.cpp create mode 100644 tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.cs create mode 100644 tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.dart create mode 100644 tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.go create mode 100644 tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.java create mode 100644 tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.kt create mode 100644 tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.py create mode 100644 tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.py2 create mode 100644 tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.rb create mode 100644 tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.rs create mode 100644 tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.swift create mode 100644 tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.ts create mode 100644 tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/manifest.yaml create mode 100644 tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.cpp create mode 100644 tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.cs create mode 100644 tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.dart create mode 100644 tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.go create mode 100644 tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.java create mode 100644 tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.kt create mode 100644 tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.py create mode 100644 tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.py2 create mode 100644 tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.rb create mode 100644 tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.rs create mode 100644 tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.swift create mode 100644 tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.ts create mode 100644 tests/1001-1500/1291. sequential-digits/manifest.yaml create mode 100644 tests/1001-1500/1291. sequential-digits/sol.cpp create mode 100644 tests/1001-1500/1291. sequential-digits/sol.cs create mode 100644 tests/1001-1500/1291. sequential-digits/sol.dart create mode 100644 tests/1001-1500/1291. sequential-digits/sol.go create mode 100644 tests/1001-1500/1291. sequential-digits/sol.java create mode 100644 tests/1001-1500/1291. sequential-digits/sol.kt create mode 100644 tests/1001-1500/1291. sequential-digits/sol.py create mode 100644 tests/1001-1500/1291. sequential-digits/sol.py2 create mode 100644 tests/1001-1500/1291. sequential-digits/sol.rb create mode 100644 tests/1001-1500/1291. sequential-digits/sol.rs create mode 100644 tests/1001-1500/1291. sequential-digits/sol.swift create mode 100644 tests/1001-1500/1291. sequential-digits/sol.ts create mode 100644 tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/manifest.yaml create mode 100644 tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.cpp create mode 100644 tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.cs create mode 100644 tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.dart create mode 100644 tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.go create mode 100644 tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.java create mode 100644 tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.kt create mode 100644 tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.py create mode 100644 tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.py2 create mode 100644 tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.rb create mode 100644 tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.rs create mode 100644 tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.swift create mode 100644 tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.ts create mode 100644 tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/manifest.yaml create mode 100644 tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.cpp create mode 100644 tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.cs create mode 100644 tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.dart create mode 100644 tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.go create mode 100644 tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.java create mode 100644 tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.kt create mode 100644 tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.py create mode 100644 tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.py2 create mode 100644 tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.rb create mode 100644 tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.rs create mode 100644 tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.swift create mode 100644 tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.ts create mode 100644 tests/1001-1500/1295. find-numbers-with-even-number-of-digits/manifest.yaml create mode 100644 tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.cpp create mode 100644 tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.cs create mode 100644 tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.dart create mode 100644 tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.go create mode 100644 tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.java create mode 100644 tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.kt create mode 100644 tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.py create mode 100644 tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.py2 create mode 100644 tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.rb create mode 100644 tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.rs create mode 100644 tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.swift create mode 100644 tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.ts create mode 100644 tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/manifest.yaml create mode 100644 tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.cpp create mode 100644 tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.cs create mode 100644 tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.dart create mode 100644 tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.go create mode 100644 tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.java create mode 100644 tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.kt create mode 100644 tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.py create mode 100644 tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.py2 create mode 100644 tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.rb create mode 100644 tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.rs create mode 100644 tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.swift create mode 100644 tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.ts create mode 100644 tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/manifest.yaml create mode 100644 tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.cpp create mode 100644 tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.cs create mode 100644 tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.dart create mode 100644 tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.go create mode 100644 tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.java create mode 100644 tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.kt create mode 100644 tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.py create mode 100644 tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.py2 create mode 100644 tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.rb create mode 100644 tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.rs create mode 100644 tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.swift create mode 100644 tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.ts create mode 100644 tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/manifest.yaml create mode 100644 tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.cpp create mode 100644 tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.cs create mode 100644 tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.dart create mode 100644 tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.go create mode 100644 tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.java create mode 100644 tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.kt create mode 100644 tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.py create mode 100644 tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.py2 create mode 100644 tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.rb create mode 100644 tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.rs create mode 100644 tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.swift create mode 100644 tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.ts create mode 100644 tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/manifest.yaml create mode 100644 tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.cpp create mode 100644 tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.cs create mode 100644 tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.dart create mode 100644 tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.go create mode 100644 tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.java create mode 100644 tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.kt create mode 100644 tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.py create mode 100644 tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.py2 create mode 100644 tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.rb create mode 100644 tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.rs create mode 100644 tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.swift create mode 100644 tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.ts create mode 100644 tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/manifest.yaml create mode 100644 tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.cpp create mode 100644 tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.cs create mode 100644 tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.dart create mode 100644 tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.go create mode 100644 tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.java create mode 100644 tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.kt create mode 100644 tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.py create mode 100644 tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.py2 create mode 100644 tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.rb create mode 100644 tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.rs create mode 100644 tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.swift create mode 100644 tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.ts create mode 100644 tests/1001-1500/1301. number-of-paths-with-max-score/manifest.yaml create mode 100644 tests/1001-1500/1301. number-of-paths-with-max-score/sol.cpp create mode 100644 tests/1001-1500/1301. number-of-paths-with-max-score/sol.cs create mode 100644 tests/1001-1500/1301. number-of-paths-with-max-score/sol.dart create mode 100644 tests/1001-1500/1301. number-of-paths-with-max-score/sol.go create mode 100644 tests/1001-1500/1301. number-of-paths-with-max-score/sol.java create mode 100644 tests/1001-1500/1301. number-of-paths-with-max-score/sol.kt create mode 100644 tests/1001-1500/1301. number-of-paths-with-max-score/sol.py create mode 100644 tests/1001-1500/1301. number-of-paths-with-max-score/sol.py2 create mode 100644 tests/1001-1500/1301. number-of-paths-with-max-score/sol.rb create mode 100644 tests/1001-1500/1301. number-of-paths-with-max-score/sol.rs create mode 100644 tests/1001-1500/1301. number-of-paths-with-max-score/sol.swift create mode 100644 tests/1001-1500/1301. number-of-paths-with-max-score/sol.ts create mode 100644 tests/1001-1500/1302. deepest-leaves-sum/manifest.yaml create mode 100644 tests/1001-1500/1302. deepest-leaves-sum/sol.cpp create mode 100644 tests/1001-1500/1302. deepest-leaves-sum/sol.cs create mode 100644 tests/1001-1500/1302. deepest-leaves-sum/sol.dart create mode 100644 tests/1001-1500/1302. deepest-leaves-sum/sol.go create mode 100644 tests/1001-1500/1302. deepest-leaves-sum/sol.java create mode 100644 tests/1001-1500/1302. deepest-leaves-sum/sol.kt create mode 100644 tests/1001-1500/1302. deepest-leaves-sum/sol.py create mode 100644 tests/1001-1500/1302. deepest-leaves-sum/sol.py2 create mode 100644 tests/1001-1500/1302. deepest-leaves-sum/sol.rb create mode 100644 tests/1001-1500/1302. deepest-leaves-sum/sol.rs create mode 100644 tests/1001-1500/1302. deepest-leaves-sum/sol.swift create mode 100644 tests/1001-1500/1302. deepest-leaves-sum/sol.ts create mode 100644 tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/manifest.yaml create mode 100644 tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.cpp create mode 100644 tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.cs create mode 100644 tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.dart create mode 100644 tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.go create mode 100644 tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.java create mode 100644 tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.kt create mode 100644 tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.py create mode 100644 tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.py2 create mode 100644 tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.rb create mode 100644 tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.rs create mode 100644 tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.swift create mode 100644 tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.ts create mode 100644 tests/1001-1500/1305. all-elements-in-two-binary-search-trees/manifest.yaml create mode 100644 tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.cpp create mode 100644 tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.cs create mode 100644 tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.dart create mode 100644 tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.go create mode 100644 tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.java create mode 100644 tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.kt create mode 100644 tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.py create mode 100644 tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.py2 create mode 100644 tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.rb create mode 100644 tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.rs create mode 100644 tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.swift create mode 100644 tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.ts create mode 100644 tests/1001-1500/1306. jump-game-iii/manifest.yaml create mode 100644 tests/1001-1500/1306. jump-game-iii/sol.cpp create mode 100644 tests/1001-1500/1306. jump-game-iii/sol.cs create mode 100644 tests/1001-1500/1306. jump-game-iii/sol.dart create mode 100644 tests/1001-1500/1306. jump-game-iii/sol.go create mode 100644 tests/1001-1500/1306. jump-game-iii/sol.java create mode 100644 tests/1001-1500/1306. jump-game-iii/sol.kt create mode 100644 tests/1001-1500/1306. jump-game-iii/sol.py create mode 100644 tests/1001-1500/1306. jump-game-iii/sol.py2 create mode 100644 tests/1001-1500/1306. jump-game-iii/sol.rb create mode 100644 tests/1001-1500/1306. jump-game-iii/sol.rs create mode 100644 tests/1001-1500/1306. jump-game-iii/sol.swift create mode 100644 tests/1001-1500/1306. jump-game-iii/sol.ts create mode 100644 tests/1001-1500/1307. verbal-arithmetic-puzzle/manifest.yaml create mode 100644 tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.cpp create mode 100644 tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.cs create mode 100644 tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.dart create mode 100644 tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.go create mode 100644 tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.java create mode 100644 tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.kt create mode 100644 tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.py create mode 100644 tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.py2 create mode 100644 tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.rb create mode 100644 tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.rs create mode 100644 tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.swift create mode 100644 tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.ts create mode 100644 tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/manifest.yaml create mode 100644 tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.cpp create mode 100644 tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.cs create mode 100644 tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.dart create mode 100644 tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.go create mode 100644 tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.java create mode 100644 tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.kt create mode 100644 tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.py create mode 100644 tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.py2 create mode 100644 tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.rb create mode 100644 tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.rs create mode 100644 tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.swift create mode 100644 tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.ts create mode 100644 tests/1001-1500/1310. xor-queries-of-a-subarray/manifest.yaml create mode 100644 tests/1001-1500/1310. xor-queries-of-a-subarray/sol.cpp create mode 100644 tests/1001-1500/1310. xor-queries-of-a-subarray/sol.cs create mode 100644 tests/1001-1500/1310. xor-queries-of-a-subarray/sol.dart create mode 100644 tests/1001-1500/1310. xor-queries-of-a-subarray/sol.go create mode 100644 tests/1001-1500/1310. xor-queries-of-a-subarray/sol.java create mode 100644 tests/1001-1500/1310. xor-queries-of-a-subarray/sol.kt create mode 100644 tests/1001-1500/1310. xor-queries-of-a-subarray/sol.py create mode 100644 tests/1001-1500/1310. xor-queries-of-a-subarray/sol.py2 create mode 100644 tests/1001-1500/1310. xor-queries-of-a-subarray/sol.rb create mode 100644 tests/1001-1500/1310. xor-queries-of-a-subarray/sol.rs create mode 100644 tests/1001-1500/1310. xor-queries-of-a-subarray/sol.swift create mode 100644 tests/1001-1500/1310. xor-queries-of-a-subarray/sol.ts create mode 100644 tests/1001-1500/1311. get-watched-videos-by-your-friends/manifest.yaml create mode 100644 tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.cpp create mode 100644 tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.cs create mode 100644 tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.dart create mode 100644 tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.go create mode 100644 tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.java create mode 100644 tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.kt create mode 100644 tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.py create mode 100644 tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.py2 create mode 100644 tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.rb create mode 100644 tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.rs create mode 100644 tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.swift create mode 100644 tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.ts create mode 100644 tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/manifest.yaml create mode 100644 tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.cpp create mode 100644 tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.cs create mode 100644 tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.dart create mode 100644 tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.go create mode 100644 tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.java create mode 100644 tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.kt create mode 100644 tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.py create mode 100644 tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.py2 create mode 100644 tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.rb create mode 100644 tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.rs create mode 100644 tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.swift create mode 100644 tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.ts create mode 100644 tests/1001-1500/1313. decompress-run-length-encoded-list/manifest.yaml create mode 100644 tests/1001-1500/1313. decompress-run-length-encoded-list/sol.cpp create mode 100644 tests/1001-1500/1313. decompress-run-length-encoded-list/sol.cs create mode 100644 tests/1001-1500/1313. decompress-run-length-encoded-list/sol.dart create mode 100644 tests/1001-1500/1313. decompress-run-length-encoded-list/sol.go create mode 100644 tests/1001-1500/1313. decompress-run-length-encoded-list/sol.java create mode 100644 tests/1001-1500/1313. decompress-run-length-encoded-list/sol.kt create mode 100644 tests/1001-1500/1313. decompress-run-length-encoded-list/sol.py create mode 100644 tests/1001-1500/1313. decompress-run-length-encoded-list/sol.py2 create mode 100644 tests/1001-1500/1313. decompress-run-length-encoded-list/sol.rb create mode 100644 tests/1001-1500/1313. decompress-run-length-encoded-list/sol.rs create mode 100644 tests/1001-1500/1313. decompress-run-length-encoded-list/sol.swift create mode 100644 tests/1001-1500/1313. decompress-run-length-encoded-list/sol.ts create mode 100644 tests/1001-1500/1314. matrix-block-sum/manifest.yaml create mode 100644 tests/1001-1500/1314. matrix-block-sum/sol.cpp create mode 100644 tests/1001-1500/1314. matrix-block-sum/sol.cs create mode 100644 tests/1001-1500/1314. matrix-block-sum/sol.dart create mode 100644 tests/1001-1500/1314. matrix-block-sum/sol.go create mode 100644 tests/1001-1500/1314. matrix-block-sum/sol.java create mode 100644 tests/1001-1500/1314. matrix-block-sum/sol.kt create mode 100644 tests/1001-1500/1314. matrix-block-sum/sol.py create mode 100644 tests/1001-1500/1314. matrix-block-sum/sol.py2 create mode 100644 tests/1001-1500/1314. matrix-block-sum/sol.rb create mode 100644 tests/1001-1500/1314. matrix-block-sum/sol.rs create mode 100644 tests/1001-1500/1314. matrix-block-sum/sol.swift create mode 100644 tests/1001-1500/1314. matrix-block-sum/sol.ts create mode 100644 tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/manifest.yaml create mode 100644 tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.cpp create mode 100644 tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.cs create mode 100644 tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.dart create mode 100644 tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.go create mode 100644 tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.java create mode 100644 tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.kt create mode 100644 tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.py create mode 100644 tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.py2 create mode 100644 tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.rb create mode 100644 tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.rs create mode 100644 tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.swift create mode 100644 tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.ts create mode 100644 tests/1001-1500/1316. distinct-echo-substrings/manifest.yaml create mode 100644 tests/1001-1500/1316. distinct-echo-substrings/sol.cpp create mode 100644 tests/1001-1500/1316. distinct-echo-substrings/sol.cs create mode 100644 tests/1001-1500/1316. distinct-echo-substrings/sol.dart create mode 100644 tests/1001-1500/1316. distinct-echo-substrings/sol.go create mode 100644 tests/1001-1500/1316. distinct-echo-substrings/sol.java create mode 100644 tests/1001-1500/1316. distinct-echo-substrings/sol.kt create mode 100644 tests/1001-1500/1316. distinct-echo-substrings/sol.py create mode 100644 tests/1001-1500/1316. distinct-echo-substrings/sol.py2 create mode 100644 tests/1001-1500/1316. distinct-echo-substrings/sol.rb create mode 100644 tests/1001-1500/1316. distinct-echo-substrings/sol.rs create mode 100644 tests/1001-1500/1316. distinct-echo-substrings/sol.swift create mode 100644 tests/1001-1500/1316. distinct-echo-substrings/sol.ts create mode 100644 tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/manifest.yaml create mode 100644 tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.cpp create mode 100644 tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.cs create mode 100644 tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.dart create mode 100644 tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.go create mode 100644 tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.java create mode 100644 tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.kt create mode 100644 tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.py create mode 100644 tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.py2 create mode 100644 tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.rb create mode 100644 tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.rs create mode 100644 tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.swift create mode 100644 tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.ts create mode 100644 tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/manifest.yaml create mode 100644 tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.cpp create mode 100644 tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.cs create mode 100644 tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.dart create mode 100644 tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.go create mode 100644 tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.java create mode 100644 tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.kt create mode 100644 tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.py create mode 100644 tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.py2 create mode 100644 tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.rb create mode 100644 tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.rs create mode 100644 tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.swift create mode 100644 tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.ts create mode 100644 tests/1001-1500/1319. number-of-operations-to-make-network-connected/manifest.yaml create mode 100644 tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.cpp create mode 100644 tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.cs create mode 100644 tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.dart create mode 100644 tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.go create mode 100644 tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.java create mode 100644 tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.kt create mode 100644 tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.py create mode 100644 tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.py2 create mode 100644 tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.rb create mode 100644 tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.rs create mode 100644 tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.swift create mode 100644 tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.ts create mode 100644 tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/manifest.yaml create mode 100644 tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.cpp create mode 100644 tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.cs create mode 100644 tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.dart create mode 100644 tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.go create mode 100644 tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.java create mode 100644 tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.kt create mode 100644 tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.py create mode 100644 tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.py2 create mode 100644 tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.rb create mode 100644 tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.rs create mode 100644 tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.swift create mode 100644 tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.ts create mode 100644 tests/1001-1500/1323. maximum-69-number/manifest.yaml create mode 100644 tests/1001-1500/1323. maximum-69-number/sol.cpp create mode 100644 tests/1001-1500/1323. maximum-69-number/sol.cs create mode 100644 tests/1001-1500/1323. maximum-69-number/sol.dart create mode 100644 tests/1001-1500/1323. maximum-69-number/sol.go create mode 100644 tests/1001-1500/1323. maximum-69-number/sol.java create mode 100644 tests/1001-1500/1323. maximum-69-number/sol.kt create mode 100644 tests/1001-1500/1323. maximum-69-number/sol.py create mode 100644 tests/1001-1500/1323. maximum-69-number/sol.py2 create mode 100644 tests/1001-1500/1323. maximum-69-number/sol.rb create mode 100644 tests/1001-1500/1323. maximum-69-number/sol.rs create mode 100644 tests/1001-1500/1323. maximum-69-number/sol.swift create mode 100644 tests/1001-1500/1323. maximum-69-number/sol.ts create mode 100644 tests/1001-1500/1324. print-words-vertically/manifest.yaml create mode 100644 tests/1001-1500/1324. print-words-vertically/sol.cpp create mode 100644 tests/1001-1500/1324. print-words-vertically/sol.cs create mode 100644 tests/1001-1500/1324. print-words-vertically/sol.dart create mode 100644 tests/1001-1500/1324. print-words-vertically/sol.go create mode 100644 tests/1001-1500/1324. print-words-vertically/sol.java create mode 100644 tests/1001-1500/1324. print-words-vertically/sol.kt create mode 100644 tests/1001-1500/1324. print-words-vertically/sol.py create mode 100644 tests/1001-1500/1324. print-words-vertically/sol.py2 create mode 100644 tests/1001-1500/1324. print-words-vertically/sol.rb create mode 100644 tests/1001-1500/1324. print-words-vertically/sol.rs create mode 100644 tests/1001-1500/1324. print-words-vertically/sol.swift create mode 100644 tests/1001-1500/1324. print-words-vertically/sol.ts create mode 100644 tests/1001-1500/1325. delete-leaves-with-a-given-value/manifest.yaml create mode 100644 tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.cpp create mode 100644 tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.cs create mode 100644 tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.dart create mode 100644 tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.go create mode 100644 tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.java create mode 100644 tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.kt create mode 100644 tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.py create mode 100644 tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.py2 create mode 100644 tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.rb create mode 100644 tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.rs create mode 100644 tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.swift create mode 100644 tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.ts create mode 100644 tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/manifest.yaml create mode 100644 tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.cpp create mode 100644 tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.cs create mode 100644 tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.dart create mode 100644 tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.go create mode 100644 tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.java create mode 100644 tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.kt create mode 100644 tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.py create mode 100644 tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.py2 create mode 100644 tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.rb create mode 100644 tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.rs create mode 100644 tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.swift create mode 100644 tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.ts create mode 100644 tests/1001-1500/1328. break-a-palindrome/manifest.yaml create mode 100644 tests/1001-1500/1328. break-a-palindrome/sol.cpp create mode 100644 tests/1001-1500/1328. break-a-palindrome/sol.cs create mode 100644 tests/1001-1500/1328. break-a-palindrome/sol.dart create mode 100644 tests/1001-1500/1328. break-a-palindrome/sol.go create mode 100644 tests/1001-1500/1328. break-a-palindrome/sol.java create mode 100644 tests/1001-1500/1328. break-a-palindrome/sol.kt create mode 100644 tests/1001-1500/1328. break-a-palindrome/sol.py create mode 100644 tests/1001-1500/1328. break-a-palindrome/sol.py2 create mode 100644 tests/1001-1500/1328. break-a-palindrome/sol.rb create mode 100644 tests/1001-1500/1328. break-a-palindrome/sol.rs create mode 100644 tests/1001-1500/1328. break-a-palindrome/sol.swift create mode 100644 tests/1001-1500/1328. break-a-palindrome/sol.ts create mode 100644 tests/1001-1500/1329. sort-the-matrix-diagonally/manifest.yaml create mode 100644 tests/1001-1500/1329. sort-the-matrix-diagonally/sol.cpp create mode 100644 tests/1001-1500/1329. sort-the-matrix-diagonally/sol.cs create mode 100644 tests/1001-1500/1329. sort-the-matrix-diagonally/sol.dart create mode 100644 tests/1001-1500/1329. sort-the-matrix-diagonally/sol.go create mode 100644 tests/1001-1500/1329. sort-the-matrix-diagonally/sol.java create mode 100644 tests/1001-1500/1329. sort-the-matrix-diagonally/sol.kt create mode 100644 tests/1001-1500/1329. sort-the-matrix-diagonally/sol.py create mode 100644 tests/1001-1500/1329. sort-the-matrix-diagonally/sol.py2 create mode 100644 tests/1001-1500/1329. sort-the-matrix-diagonally/sol.rb create mode 100644 tests/1001-1500/1329. sort-the-matrix-diagonally/sol.rs create mode 100644 tests/1001-1500/1329. sort-the-matrix-diagonally/sol.swift create mode 100644 tests/1001-1500/1329. sort-the-matrix-diagonally/sol.ts create mode 100644 tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/manifest.yaml create mode 100644 tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.cpp create mode 100644 tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.cs create mode 100644 tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.dart create mode 100644 tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.go create mode 100644 tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.java create mode 100644 tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.kt create mode 100644 tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.py create mode 100644 tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.py2 create mode 100644 tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.rb create mode 100644 tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.rs create mode 100644 tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.swift create mode 100644 tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.ts create mode 100644 tests/1001-1500/1331. rank-transform-of-an-array/manifest.yaml create mode 100644 tests/1001-1500/1331. rank-transform-of-an-array/sol.cpp create mode 100644 tests/1001-1500/1331. rank-transform-of-an-array/sol.cs create mode 100644 tests/1001-1500/1331. rank-transform-of-an-array/sol.dart create mode 100644 tests/1001-1500/1331. rank-transform-of-an-array/sol.go create mode 100644 tests/1001-1500/1331. rank-transform-of-an-array/sol.java create mode 100644 tests/1001-1500/1331. rank-transform-of-an-array/sol.kt create mode 100644 tests/1001-1500/1331. rank-transform-of-an-array/sol.py create mode 100644 tests/1001-1500/1331. rank-transform-of-an-array/sol.py2 create mode 100644 tests/1001-1500/1331. rank-transform-of-an-array/sol.rb create mode 100644 tests/1001-1500/1331. rank-transform-of-an-array/sol.rs create mode 100644 tests/1001-1500/1331. rank-transform-of-an-array/sol.swift create mode 100644 tests/1001-1500/1331. rank-transform-of-an-array/sol.ts create mode 100644 tests/1001-1500/1332. remove-palindromic-subsequences/manifest.yaml create mode 100644 tests/1001-1500/1332. remove-palindromic-subsequences/sol.cpp create mode 100644 tests/1001-1500/1332. remove-palindromic-subsequences/sol.cs create mode 100644 tests/1001-1500/1332. remove-palindromic-subsequences/sol.dart create mode 100644 tests/1001-1500/1332. remove-palindromic-subsequences/sol.go create mode 100644 tests/1001-1500/1332. remove-palindromic-subsequences/sol.java create mode 100644 tests/1001-1500/1332. remove-palindromic-subsequences/sol.kt create mode 100644 tests/1001-1500/1332. remove-palindromic-subsequences/sol.py create mode 100644 tests/1001-1500/1332. remove-palindromic-subsequences/sol.py2 create mode 100644 tests/1001-1500/1332. remove-palindromic-subsequences/sol.rb create mode 100644 tests/1001-1500/1332. remove-palindromic-subsequences/sol.rs create mode 100644 tests/1001-1500/1332. remove-palindromic-subsequences/sol.swift create mode 100644 tests/1001-1500/1332. remove-palindromic-subsequences/sol.ts create mode 100644 tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/manifest.yaml create mode 100644 tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.cpp create mode 100644 tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.cs create mode 100644 tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.dart create mode 100644 tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.go create mode 100644 tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.java create mode 100644 tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.kt create mode 100644 tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.py create mode 100644 tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.py2 create mode 100644 tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.rb create mode 100644 tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.rs create mode 100644 tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.swift create mode 100644 tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.ts create mode 100644 tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/manifest.yaml create mode 100644 tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.cpp create mode 100644 tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.cs create mode 100644 tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.dart create mode 100644 tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.go create mode 100644 tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.java create mode 100644 tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.kt create mode 100644 tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.py create mode 100644 tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.py2 create mode 100644 tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.rb create mode 100644 tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.rs create mode 100644 tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.swift create mode 100644 tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.ts create mode 100644 tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/manifest.yaml create mode 100644 tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.cpp create mode 100644 tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.cs create mode 100644 tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.dart create mode 100644 tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.go create mode 100644 tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.java create mode 100644 tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.kt create mode 100644 tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.py create mode 100644 tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.py2 create mode 100644 tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.rb create mode 100644 tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.rs create mode 100644 tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.swift create mode 100644 tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.ts create mode 100644 tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/manifest.yaml create mode 100644 tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.cpp create mode 100644 tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.cs create mode 100644 tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.dart create mode 100644 tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.go create mode 100644 tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.java create mode 100644 tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.kt create mode 100644 tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.py create mode 100644 tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.py2 create mode 100644 tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.rb create mode 100644 tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.rs create mode 100644 tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.swift create mode 100644 tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.ts create mode 100644 tests/1001-1500/1338. reduce-array-size-to-the-half/manifest.yaml create mode 100644 tests/1001-1500/1338. reduce-array-size-to-the-half/sol.cpp create mode 100644 tests/1001-1500/1338. reduce-array-size-to-the-half/sol.cs create mode 100644 tests/1001-1500/1338. reduce-array-size-to-the-half/sol.dart create mode 100644 tests/1001-1500/1338. reduce-array-size-to-the-half/sol.go create mode 100644 tests/1001-1500/1338. reduce-array-size-to-the-half/sol.java create mode 100644 tests/1001-1500/1338. reduce-array-size-to-the-half/sol.kt create mode 100644 tests/1001-1500/1338. reduce-array-size-to-the-half/sol.py create mode 100644 tests/1001-1500/1338. reduce-array-size-to-the-half/sol.py2 create mode 100644 tests/1001-1500/1338. reduce-array-size-to-the-half/sol.rb create mode 100644 tests/1001-1500/1338. reduce-array-size-to-the-half/sol.rs create mode 100644 tests/1001-1500/1338. reduce-array-size-to-the-half/sol.swift create mode 100644 tests/1001-1500/1338. reduce-array-size-to-the-half/sol.ts create mode 100644 tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/manifest.yaml create mode 100644 tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.cpp create mode 100644 tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.cs create mode 100644 tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.dart create mode 100644 tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.go create mode 100644 tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.java create mode 100644 tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.kt create mode 100644 tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.py create mode 100644 tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.py2 create mode 100644 tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.rb create mode 100644 tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.rs create mode 100644 tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.swift create mode 100644 tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.ts create mode 100644 tests/1001-1500/1340. jump-game-v/manifest.yaml create mode 100644 tests/1001-1500/1340. jump-game-v/sol.cpp create mode 100644 tests/1001-1500/1340. jump-game-v/sol.cs create mode 100644 tests/1001-1500/1340. jump-game-v/sol.dart create mode 100644 tests/1001-1500/1340. jump-game-v/sol.go create mode 100644 tests/1001-1500/1340. jump-game-v/sol.java create mode 100644 tests/1001-1500/1340. jump-game-v/sol.kt create mode 100644 tests/1001-1500/1340. jump-game-v/sol.py create mode 100644 tests/1001-1500/1340. jump-game-v/sol.py2 create mode 100644 tests/1001-1500/1340. jump-game-v/sol.rb create mode 100644 tests/1001-1500/1340. jump-game-v/sol.rs create mode 100644 tests/1001-1500/1340. jump-game-v/sol.swift create mode 100644 tests/1001-1500/1340. jump-game-v/sol.ts create mode 100644 tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/manifest.yaml create mode 100644 tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.cpp create mode 100644 tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.cs create mode 100644 tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.dart create mode 100644 tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.go create mode 100644 tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.java create mode 100644 tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.kt create mode 100644 tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.py create mode 100644 tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.py2 create mode 100644 tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.rb create mode 100644 tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.rs create mode 100644 tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.swift create mode 100644 tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.ts create mode 100644 tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/manifest.yaml create mode 100644 tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.cpp create mode 100644 tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.cs create mode 100644 tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.dart create mode 100644 tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.go create mode 100644 tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.java create mode 100644 tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.kt create mode 100644 tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.py create mode 100644 tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.py2 create mode 100644 tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.rb create mode 100644 tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.rs create mode 100644 tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.swift create mode 100644 tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.ts create mode 100644 tests/1001-1500/1344. angle-between-hands-of-a-clock/manifest.yaml create mode 100644 tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.cpp create mode 100644 tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.cs create mode 100644 tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.dart create mode 100644 tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.go create mode 100644 tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.java create mode 100644 tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.kt create mode 100644 tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.py create mode 100644 tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.py2 create mode 100644 tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.rb create mode 100644 tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.rs create mode 100644 tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.swift create mode 100644 tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.ts create mode 100644 tests/1001-1500/1345. jump-game-iv/manifest.yaml create mode 100644 tests/1001-1500/1345. jump-game-iv/sol.cpp create mode 100644 tests/1001-1500/1345. jump-game-iv/sol.cs create mode 100644 tests/1001-1500/1345. jump-game-iv/sol.dart create mode 100644 tests/1001-1500/1345. jump-game-iv/sol.go create mode 100644 tests/1001-1500/1345. jump-game-iv/sol.java create mode 100644 tests/1001-1500/1345. jump-game-iv/sol.kt create mode 100644 tests/1001-1500/1345. jump-game-iv/sol.py create mode 100644 tests/1001-1500/1345. jump-game-iv/sol.py2 create mode 100644 tests/1001-1500/1345. jump-game-iv/sol.rb create mode 100644 tests/1001-1500/1345. jump-game-iv/sol.rs create mode 100644 tests/1001-1500/1345. jump-game-iv/sol.swift create mode 100644 tests/1001-1500/1345. jump-game-iv/sol.ts create mode 100644 tests/1001-1500/1346. check-if-n-and-its-double-exist/manifest.yaml create mode 100644 tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.cpp create mode 100644 tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.cs create mode 100644 tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.dart create mode 100644 tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.go create mode 100644 tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.java create mode 100644 tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.kt create mode 100644 tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.py create mode 100644 tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.py2 create mode 100644 tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.rb create mode 100644 tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.rs create mode 100644 tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.swift create mode 100644 tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.ts create mode 100644 tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/manifest.yaml create mode 100644 tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.cpp create mode 100644 tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.cs create mode 100644 tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.dart create mode 100644 tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.go create mode 100644 tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.java create mode 100644 tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.kt create mode 100644 tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.py create mode 100644 tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.py2 create mode 100644 tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.rb create mode 100644 tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.rs create mode 100644 tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.swift create mode 100644 tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.ts create mode 100644 tests/1001-1500/1349. maximum-students-taking-exam/manifest.yaml create mode 100644 tests/1001-1500/1349. maximum-students-taking-exam/sol.cpp create mode 100644 tests/1001-1500/1349. maximum-students-taking-exam/sol.cs create mode 100644 tests/1001-1500/1349. maximum-students-taking-exam/sol.dart create mode 100644 tests/1001-1500/1349. maximum-students-taking-exam/sol.go create mode 100644 tests/1001-1500/1349. maximum-students-taking-exam/sol.java create mode 100644 tests/1001-1500/1349. maximum-students-taking-exam/sol.kt create mode 100644 tests/1001-1500/1349. maximum-students-taking-exam/sol.py create mode 100644 tests/1001-1500/1349. maximum-students-taking-exam/sol.py2 create mode 100644 tests/1001-1500/1349. maximum-students-taking-exam/sol.rb create mode 100644 tests/1001-1500/1349. maximum-students-taking-exam/sol.rs create mode 100644 tests/1001-1500/1349. maximum-students-taking-exam/sol.swift create mode 100644 tests/1001-1500/1349. maximum-students-taking-exam/sol.ts create mode 100644 tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/manifest.yaml create mode 100644 tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.cpp create mode 100644 tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.cs create mode 100644 tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.dart create mode 100644 tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.go create mode 100644 tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.java create mode 100644 tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.kt create mode 100644 tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.py create mode 100644 tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.py2 create mode 100644 tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.rb create mode 100644 tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.rs create mode 100644 tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.swift create mode 100644 tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.ts create mode 100644 tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/manifest.yaml create mode 100644 tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.cpp create mode 100644 tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.cs create mode 100644 tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.dart create mode 100644 tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.go create mode 100644 tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.java create mode 100644 tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.kt create mode 100644 tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.py create mode 100644 tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.py2 create mode 100644 tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.rb create mode 100644 tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.rs create mode 100644 tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.swift create mode 100644 tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.ts create mode 100644 tests/1001-1500/1354. construct-target-array-with-multiple-sums/manifest.yaml create mode 100644 tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.cpp create mode 100644 tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.cs create mode 100644 tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.dart create mode 100644 tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.go create mode 100644 tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.java create mode 100644 tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.kt create mode 100644 tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.py create mode 100644 tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.py2 create mode 100644 tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.rb create mode 100644 tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.rs create mode 100644 tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.swift create mode 100644 tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.ts create mode 100644 tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/manifest.yaml create mode 100644 tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.cpp create mode 100644 tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.cs create mode 100644 tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.dart create mode 100644 tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.go create mode 100644 tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.java create mode 100644 tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.kt create mode 100644 tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.py create mode 100644 tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.py2 create mode 100644 tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.rb create mode 100644 tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.rs create mode 100644 tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.swift create mode 100644 tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.ts create mode 100644 tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/manifest.yaml create mode 100644 tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.cpp create mode 100644 tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.cs create mode 100644 tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.dart create mode 100644 tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.go create mode 100644 tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.java create mode 100644 tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.kt create mode 100644 tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.py create mode 100644 tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.py2 create mode 100644 tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.rb create mode 100644 tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.rs create mode 100644 tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.swift create mode 100644 tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.ts create mode 100644 tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/manifest.yaml create mode 100644 tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.cpp create mode 100644 tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.cs create mode 100644 tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.dart create mode 100644 tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.go create mode 100644 tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.java create mode 100644 tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.kt create mode 100644 tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.py create mode 100644 tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.py2 create mode 100644 tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.rb create mode 100644 tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.rs create mode 100644 tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.swift create mode 100644 tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.ts create mode 100644 tests/1001-1500/1360. number-of-days-between-two-dates/manifest.yaml create mode 100644 tests/1001-1500/1360. number-of-days-between-two-dates/sol.cpp create mode 100644 tests/1001-1500/1360. number-of-days-between-two-dates/sol.cs create mode 100644 tests/1001-1500/1360. number-of-days-between-two-dates/sol.dart create mode 100644 tests/1001-1500/1360. number-of-days-between-two-dates/sol.go create mode 100644 tests/1001-1500/1360. number-of-days-between-two-dates/sol.java create mode 100644 tests/1001-1500/1360. number-of-days-between-two-dates/sol.kt create mode 100644 tests/1001-1500/1360. number-of-days-between-two-dates/sol.py create mode 100644 tests/1001-1500/1360. number-of-days-between-two-dates/sol.py2 create mode 100644 tests/1001-1500/1360. number-of-days-between-two-dates/sol.rb create mode 100644 tests/1001-1500/1360. number-of-days-between-two-dates/sol.rs create mode 100644 tests/1001-1500/1360. number-of-days-between-two-dates/sol.swift create mode 100644 tests/1001-1500/1360. number-of-days-between-two-dates/sol.ts create mode 100644 tests/1001-1500/1361. validate-binary-tree-nodes/manifest.yaml create mode 100644 tests/1001-1500/1361. validate-binary-tree-nodes/sol.cpp create mode 100644 tests/1001-1500/1361. validate-binary-tree-nodes/sol.cs create mode 100644 tests/1001-1500/1361. validate-binary-tree-nodes/sol.dart create mode 100644 tests/1001-1500/1361. validate-binary-tree-nodes/sol.go create mode 100644 tests/1001-1500/1361. validate-binary-tree-nodes/sol.java create mode 100644 tests/1001-1500/1361. validate-binary-tree-nodes/sol.kt create mode 100644 tests/1001-1500/1361. validate-binary-tree-nodes/sol.py create mode 100644 tests/1001-1500/1361. validate-binary-tree-nodes/sol.py2 create mode 100644 tests/1001-1500/1361. validate-binary-tree-nodes/sol.rb create mode 100644 tests/1001-1500/1361. validate-binary-tree-nodes/sol.rs create mode 100644 tests/1001-1500/1361. validate-binary-tree-nodes/sol.swift create mode 100644 tests/1001-1500/1361. validate-binary-tree-nodes/sol.ts create mode 100644 tests/1001-1500/1362. closest-divisors/manifest.yaml create mode 100644 tests/1001-1500/1362. closest-divisors/sol.cpp create mode 100644 tests/1001-1500/1362. closest-divisors/sol.cs create mode 100644 tests/1001-1500/1362. closest-divisors/sol.dart create mode 100644 tests/1001-1500/1362. closest-divisors/sol.go create mode 100644 tests/1001-1500/1362. closest-divisors/sol.java create mode 100644 tests/1001-1500/1362. closest-divisors/sol.kt create mode 100644 tests/1001-1500/1362. closest-divisors/sol.py create mode 100644 tests/1001-1500/1362. closest-divisors/sol.py2 create mode 100644 tests/1001-1500/1362. closest-divisors/sol.rb create mode 100644 tests/1001-1500/1362. closest-divisors/sol.rs create mode 100644 tests/1001-1500/1362. closest-divisors/sol.swift create mode 100644 tests/1001-1500/1362. closest-divisors/sol.ts create mode 100644 tests/1001-1500/1363. largest-multiple-of-three/manifest.yaml create mode 100644 tests/1001-1500/1363. largest-multiple-of-three/sol.cpp create mode 100644 tests/1001-1500/1363. largest-multiple-of-three/sol.cs create mode 100644 tests/1001-1500/1363. largest-multiple-of-three/sol.dart create mode 100644 tests/1001-1500/1363. largest-multiple-of-three/sol.go create mode 100644 tests/1001-1500/1363. largest-multiple-of-three/sol.java create mode 100644 tests/1001-1500/1363. largest-multiple-of-three/sol.kt create mode 100644 tests/1001-1500/1363. largest-multiple-of-three/sol.py create mode 100644 tests/1001-1500/1363. largest-multiple-of-three/sol.py2 create mode 100644 tests/1001-1500/1363. largest-multiple-of-three/sol.rb create mode 100644 tests/1001-1500/1363. largest-multiple-of-three/sol.rs create mode 100644 tests/1001-1500/1363. largest-multiple-of-three/sol.swift create mode 100644 tests/1001-1500/1363. largest-multiple-of-three/sol.ts create mode 100644 tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/manifest.yaml create mode 100644 tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.cpp create mode 100644 tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.cs create mode 100644 tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.dart create mode 100644 tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.go create mode 100644 tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.java create mode 100644 tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.kt create mode 100644 tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.py create mode 100644 tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.py2 create mode 100644 tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.rb create mode 100644 tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.rs create mode 100644 tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.swift create mode 100644 tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.ts create mode 100644 tests/1001-1500/1366. rank-teams-by-votes/manifest.yaml create mode 100644 tests/1001-1500/1366. rank-teams-by-votes/sol.cpp create mode 100644 tests/1001-1500/1366. rank-teams-by-votes/sol.cs create mode 100644 tests/1001-1500/1366. rank-teams-by-votes/sol.dart create mode 100644 tests/1001-1500/1366. rank-teams-by-votes/sol.go create mode 100644 tests/1001-1500/1366. rank-teams-by-votes/sol.java create mode 100644 tests/1001-1500/1366. rank-teams-by-votes/sol.kt create mode 100644 tests/1001-1500/1366. rank-teams-by-votes/sol.py create mode 100644 tests/1001-1500/1366. rank-teams-by-votes/sol.py2 create mode 100644 tests/1001-1500/1366. rank-teams-by-votes/sol.rb create mode 100644 tests/1001-1500/1366. rank-teams-by-votes/sol.rs create mode 100644 tests/1001-1500/1366. rank-teams-by-votes/sol.swift create mode 100644 tests/1001-1500/1366. rank-teams-by-votes/sol.ts create mode 100644 tests/1001-1500/1367. linked-list-in-binary-tree/manifest.yaml create mode 100644 tests/1001-1500/1367. linked-list-in-binary-tree/sol.cpp create mode 100644 tests/1001-1500/1367. linked-list-in-binary-tree/sol.cs create mode 100644 tests/1001-1500/1367. linked-list-in-binary-tree/sol.dart create mode 100644 tests/1001-1500/1367. linked-list-in-binary-tree/sol.go create mode 100644 tests/1001-1500/1367. linked-list-in-binary-tree/sol.java create mode 100644 tests/1001-1500/1367. linked-list-in-binary-tree/sol.kt create mode 100644 tests/1001-1500/1367. linked-list-in-binary-tree/sol.py create mode 100644 tests/1001-1500/1367. linked-list-in-binary-tree/sol.py2 create mode 100644 tests/1001-1500/1367. linked-list-in-binary-tree/sol.rb create mode 100644 tests/1001-1500/1367. linked-list-in-binary-tree/sol.rs create mode 100644 tests/1001-1500/1367. linked-list-in-binary-tree/sol.swift create mode 100644 tests/1001-1500/1367. linked-list-in-binary-tree/sol.ts create mode 100644 tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/manifest.yaml create mode 100644 tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.cpp create mode 100644 tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.cs create mode 100644 tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.dart create mode 100644 tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.go create mode 100644 tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.java create mode 100644 tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.kt create mode 100644 tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.py create mode 100644 tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.py2 create mode 100644 tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.rb create mode 100644 tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.rs create mode 100644 tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.swift create mode 100644 tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.ts create mode 100644 tests/1001-1500/1370. increasing-decreasing-string/manifest.yaml create mode 100644 tests/1001-1500/1370. increasing-decreasing-string/sol.cpp create mode 100644 tests/1001-1500/1370. increasing-decreasing-string/sol.cs create mode 100644 tests/1001-1500/1370. increasing-decreasing-string/sol.dart create mode 100644 tests/1001-1500/1370. increasing-decreasing-string/sol.go create mode 100644 tests/1001-1500/1370. increasing-decreasing-string/sol.java create mode 100644 tests/1001-1500/1370. increasing-decreasing-string/sol.kt create mode 100644 tests/1001-1500/1370. increasing-decreasing-string/sol.py create mode 100644 tests/1001-1500/1370. increasing-decreasing-string/sol.py2 create mode 100644 tests/1001-1500/1370. increasing-decreasing-string/sol.rb create mode 100644 tests/1001-1500/1370. increasing-decreasing-string/sol.rs create mode 100644 tests/1001-1500/1370. increasing-decreasing-string/sol.swift create mode 100644 tests/1001-1500/1370. increasing-decreasing-string/sol.ts create mode 100644 tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/manifest.yaml create mode 100644 tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.cpp create mode 100644 tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.cs create mode 100644 tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.dart create mode 100644 tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.go create mode 100644 tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.java create mode 100644 tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.kt create mode 100644 tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.py create mode 100644 tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.py2 create mode 100644 tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.rb create mode 100644 tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.rs create mode 100644 tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.swift create mode 100644 tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.ts create mode 100644 tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/manifest.yaml create mode 100644 tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.cpp create mode 100644 tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.cs create mode 100644 tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.dart create mode 100644 tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.go create mode 100644 tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.java create mode 100644 tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.kt create mode 100644 tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.py create mode 100644 tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.py2 create mode 100644 tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.rb create mode 100644 tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.rs create mode 100644 tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.swift create mode 100644 tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.ts create mode 100644 tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/manifest.yaml create mode 100644 tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.cpp create mode 100644 tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.cs create mode 100644 tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.dart create mode 100644 tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.go create mode 100644 tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.java create mode 100644 tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.kt create mode 100644 tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.py create mode 100644 tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.py2 create mode 100644 tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.rb create mode 100644 tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.rs create mode 100644 tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.swift create mode 100644 tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.ts create mode 100644 tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/manifest.yaml create mode 100644 tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.cpp create mode 100644 tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.cs create mode 100644 tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.dart create mode 100644 tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.go create mode 100644 tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.java create mode 100644 tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.kt create mode 100644 tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.py create mode 100644 tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.py2 create mode 100644 tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.rb create mode 100644 tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.rs create mode 100644 tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.swift create mode 100644 tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.ts create mode 100644 tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/manifest.yaml create mode 100644 tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.cpp create mode 100644 tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.cs create mode 100644 tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.dart create mode 100644 tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.go create mode 100644 tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.java create mode 100644 tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.kt create mode 100644 tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.py create mode 100644 tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.py2 create mode 100644 tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.rb create mode 100644 tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.rs create mode 100644 tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.swift create mode 100644 tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.ts create mode 100644 tests/1001-1500/1376. time-needed-to-inform-all-employees/manifest.yaml create mode 100644 tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.cpp create mode 100644 tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.cs create mode 100644 tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.dart create mode 100644 tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.go create mode 100644 tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.java create mode 100644 tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.kt create mode 100644 tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.py create mode 100644 tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.py2 create mode 100644 tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.rb create mode 100644 tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.rs create mode 100644 tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.swift create mode 100644 tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.ts create mode 100644 tests/1001-1500/1377. frog-position-after-t-seconds/manifest.yaml create mode 100644 tests/1001-1500/1377. frog-position-after-t-seconds/sol.cpp create mode 100644 tests/1001-1500/1377. frog-position-after-t-seconds/sol.cs create mode 100644 tests/1001-1500/1377. frog-position-after-t-seconds/sol.dart create mode 100644 tests/1001-1500/1377. frog-position-after-t-seconds/sol.go create mode 100644 tests/1001-1500/1377. frog-position-after-t-seconds/sol.java create mode 100644 tests/1001-1500/1377. frog-position-after-t-seconds/sol.kt create mode 100644 tests/1001-1500/1377. frog-position-after-t-seconds/sol.py create mode 100644 tests/1001-1500/1377. frog-position-after-t-seconds/sol.py2 create mode 100644 tests/1001-1500/1377. frog-position-after-t-seconds/sol.rb create mode 100644 tests/1001-1500/1377. frog-position-after-t-seconds/sol.rs create mode 100644 tests/1001-1500/1377. frog-position-after-t-seconds/sol.swift create mode 100644 tests/1001-1500/1377. frog-position-after-t-seconds/sol.ts create mode 100644 tests/1001-1500/1380. lucky-numbers-in-a-matrix/manifest.yaml create mode 100644 tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.cpp create mode 100644 tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.cs create mode 100644 tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.dart create mode 100644 tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.go create mode 100644 tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.java create mode 100644 tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.kt create mode 100644 tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.py create mode 100644 tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.py2 create mode 100644 tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.rb create mode 100644 tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.rs create mode 100644 tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.swift create mode 100644 tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.ts create mode 100644 tests/1001-1500/1382. balance-a-binary-search-tree/manifest.yaml create mode 100644 tests/1001-1500/1382. balance-a-binary-search-tree/sol.cpp create mode 100644 tests/1001-1500/1382. balance-a-binary-search-tree/sol.cs create mode 100644 tests/1001-1500/1382. balance-a-binary-search-tree/sol.dart create mode 100644 tests/1001-1500/1382. balance-a-binary-search-tree/sol.go create mode 100644 tests/1001-1500/1382. balance-a-binary-search-tree/sol.java create mode 100644 tests/1001-1500/1382. balance-a-binary-search-tree/sol.kt create mode 100644 tests/1001-1500/1382. balance-a-binary-search-tree/sol.py create mode 100644 tests/1001-1500/1382. balance-a-binary-search-tree/sol.py2 create mode 100644 tests/1001-1500/1382. balance-a-binary-search-tree/sol.rb create mode 100644 tests/1001-1500/1382. balance-a-binary-search-tree/sol.rs create mode 100644 tests/1001-1500/1382. balance-a-binary-search-tree/sol.swift create mode 100644 tests/1001-1500/1382. balance-a-binary-search-tree/sol.ts create mode 100644 tests/1001-1500/1383. maximum-performance-of-a-team/manifest.yaml create mode 100644 tests/1001-1500/1383. maximum-performance-of-a-team/sol.cpp create mode 100644 tests/1001-1500/1383. maximum-performance-of-a-team/sol.cs create mode 100644 tests/1001-1500/1383. maximum-performance-of-a-team/sol.dart create mode 100644 tests/1001-1500/1383. maximum-performance-of-a-team/sol.go create mode 100644 tests/1001-1500/1383. maximum-performance-of-a-team/sol.java create mode 100644 tests/1001-1500/1383. maximum-performance-of-a-team/sol.kt create mode 100644 tests/1001-1500/1383. maximum-performance-of-a-team/sol.py create mode 100644 tests/1001-1500/1383. maximum-performance-of-a-team/sol.py2 create mode 100644 tests/1001-1500/1383. maximum-performance-of-a-team/sol.rb create mode 100644 tests/1001-1500/1383. maximum-performance-of-a-team/sol.rs create mode 100644 tests/1001-1500/1383. maximum-performance-of-a-team/sol.swift create mode 100644 tests/1001-1500/1383. maximum-performance-of-a-team/sol.ts create mode 100644 tests/1001-1500/1385. find-the-distance-value-between-two-arrays/manifest.yaml create mode 100644 tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.cpp create mode 100644 tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.cs create mode 100644 tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.dart create mode 100644 tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.go create mode 100644 tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.java create mode 100644 tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.kt create mode 100644 tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.py create mode 100644 tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.py2 create mode 100644 tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.rb create mode 100644 tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.rs create mode 100644 tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.swift create mode 100644 tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.ts create mode 100644 tests/1001-1500/1386. cinema-seat-allocation/manifest.yaml create mode 100644 tests/1001-1500/1386. cinema-seat-allocation/sol.cpp create mode 100644 tests/1001-1500/1386. cinema-seat-allocation/sol.cs create mode 100644 tests/1001-1500/1386. cinema-seat-allocation/sol.dart create mode 100644 tests/1001-1500/1386. cinema-seat-allocation/sol.go create mode 100644 tests/1001-1500/1386. cinema-seat-allocation/sol.java create mode 100644 tests/1001-1500/1386. cinema-seat-allocation/sol.kt create mode 100644 tests/1001-1500/1386. cinema-seat-allocation/sol.py create mode 100644 tests/1001-1500/1386. cinema-seat-allocation/sol.py2 create mode 100644 tests/1001-1500/1386. cinema-seat-allocation/sol.rb create mode 100644 tests/1001-1500/1386. cinema-seat-allocation/sol.rs create mode 100644 tests/1001-1500/1386. cinema-seat-allocation/sol.swift create mode 100644 tests/1001-1500/1386. cinema-seat-allocation/sol.ts create mode 100644 tests/1001-1500/1387. sort-integers-by-the-power-value/manifest.yaml create mode 100644 tests/1001-1500/1387. sort-integers-by-the-power-value/sol.cpp create mode 100644 tests/1001-1500/1387. sort-integers-by-the-power-value/sol.cs create mode 100644 tests/1001-1500/1387. sort-integers-by-the-power-value/sol.dart create mode 100644 tests/1001-1500/1387. sort-integers-by-the-power-value/sol.go create mode 100644 tests/1001-1500/1387. sort-integers-by-the-power-value/sol.java create mode 100644 tests/1001-1500/1387. sort-integers-by-the-power-value/sol.kt create mode 100644 tests/1001-1500/1387. sort-integers-by-the-power-value/sol.py create mode 100644 tests/1001-1500/1387. sort-integers-by-the-power-value/sol.py2 create mode 100644 tests/1001-1500/1387. sort-integers-by-the-power-value/sol.rb create mode 100644 tests/1001-1500/1387. sort-integers-by-the-power-value/sol.rs create mode 100644 tests/1001-1500/1387. sort-integers-by-the-power-value/sol.swift create mode 100644 tests/1001-1500/1387. sort-integers-by-the-power-value/sol.ts create mode 100644 tests/1001-1500/1388. pizza-with-3n-slices/manifest.yaml create mode 100644 tests/1001-1500/1388. pizza-with-3n-slices/sol.cpp create mode 100644 tests/1001-1500/1388. pizza-with-3n-slices/sol.cs create mode 100644 tests/1001-1500/1388. pizza-with-3n-slices/sol.dart create mode 100644 tests/1001-1500/1388. pizza-with-3n-slices/sol.go create mode 100644 tests/1001-1500/1388. pizza-with-3n-slices/sol.java create mode 100644 tests/1001-1500/1388. pizza-with-3n-slices/sol.kt create mode 100644 tests/1001-1500/1388. pizza-with-3n-slices/sol.py create mode 100644 tests/1001-1500/1388. pizza-with-3n-slices/sol.py2 create mode 100644 tests/1001-1500/1388. pizza-with-3n-slices/sol.rb create mode 100644 tests/1001-1500/1388. pizza-with-3n-slices/sol.rs create mode 100644 tests/1001-1500/1388. pizza-with-3n-slices/sol.swift create mode 100644 tests/1001-1500/1388. pizza-with-3n-slices/sol.ts create mode 100644 tests/1001-1500/1389. create-target-array-in-the-given-order/manifest.yaml create mode 100644 tests/1001-1500/1389. create-target-array-in-the-given-order/sol.cpp create mode 100644 tests/1001-1500/1389. create-target-array-in-the-given-order/sol.cs create mode 100644 tests/1001-1500/1389. create-target-array-in-the-given-order/sol.dart create mode 100644 tests/1001-1500/1389. create-target-array-in-the-given-order/sol.go create mode 100644 tests/1001-1500/1389. create-target-array-in-the-given-order/sol.java create mode 100644 tests/1001-1500/1389. create-target-array-in-the-given-order/sol.kt create mode 100644 tests/1001-1500/1389. create-target-array-in-the-given-order/sol.py create mode 100644 tests/1001-1500/1389. create-target-array-in-the-given-order/sol.py2 create mode 100644 tests/1001-1500/1389. create-target-array-in-the-given-order/sol.rb create mode 100644 tests/1001-1500/1389. create-target-array-in-the-given-order/sol.rs create mode 100644 tests/1001-1500/1389. create-target-array-in-the-given-order/sol.swift create mode 100644 tests/1001-1500/1389. create-target-array-in-the-given-order/sol.ts create mode 100644 tests/1001-1500/1390. four-divisors/manifest.yaml create mode 100644 tests/1001-1500/1390. four-divisors/sol.cpp create mode 100644 tests/1001-1500/1390. four-divisors/sol.cs create mode 100644 tests/1001-1500/1390. four-divisors/sol.dart create mode 100644 tests/1001-1500/1390. four-divisors/sol.go create mode 100644 tests/1001-1500/1390. four-divisors/sol.java create mode 100644 tests/1001-1500/1390. four-divisors/sol.kt create mode 100644 tests/1001-1500/1390. four-divisors/sol.py create mode 100644 tests/1001-1500/1390. four-divisors/sol.py2 create mode 100644 tests/1001-1500/1390. four-divisors/sol.rb create mode 100644 tests/1001-1500/1390. four-divisors/sol.rs create mode 100644 tests/1001-1500/1390. four-divisors/sol.swift create mode 100644 tests/1001-1500/1390. four-divisors/sol.ts create mode 100644 tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/manifest.yaml create mode 100644 tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.cpp create mode 100644 tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.cs create mode 100644 tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.dart create mode 100644 tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.go create mode 100644 tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.java create mode 100644 tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.kt create mode 100644 tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.py create mode 100644 tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.py2 create mode 100644 tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.rb create mode 100644 tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.rs create mode 100644 tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.swift create mode 100644 tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.ts create mode 100644 tests/1001-1500/1392. longest-happy-prefix/manifest.yaml create mode 100644 tests/1001-1500/1392. longest-happy-prefix/sol.cpp create mode 100644 tests/1001-1500/1392. longest-happy-prefix/sol.cs create mode 100644 tests/1001-1500/1392. longest-happy-prefix/sol.dart create mode 100644 tests/1001-1500/1392. longest-happy-prefix/sol.go create mode 100644 tests/1001-1500/1392. longest-happy-prefix/sol.java create mode 100644 tests/1001-1500/1392. longest-happy-prefix/sol.kt create mode 100644 tests/1001-1500/1392. longest-happy-prefix/sol.py create mode 100644 tests/1001-1500/1392. longest-happy-prefix/sol.py2 create mode 100644 tests/1001-1500/1392. longest-happy-prefix/sol.rb create mode 100644 tests/1001-1500/1392. longest-happy-prefix/sol.rs create mode 100644 tests/1001-1500/1392. longest-happy-prefix/sol.swift create mode 100644 tests/1001-1500/1392. longest-happy-prefix/sol.ts create mode 100644 tests/1001-1500/1394. find-lucky-integer-in-an-array/manifest.yaml create mode 100644 tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.cpp create mode 100644 tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.cs create mode 100644 tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.dart create mode 100644 tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.go create mode 100644 tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.java create mode 100644 tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.kt create mode 100644 tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.py create mode 100644 tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.py2 create mode 100644 tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.rb create mode 100644 tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.rs create mode 100644 tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.swift create mode 100644 tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.ts create mode 100644 tests/1001-1500/1395. count-number-of-teams/manifest.yaml create mode 100644 tests/1001-1500/1395. count-number-of-teams/sol.cpp create mode 100644 tests/1001-1500/1395. count-number-of-teams/sol.cs create mode 100644 tests/1001-1500/1395. count-number-of-teams/sol.dart create mode 100644 tests/1001-1500/1395. count-number-of-teams/sol.go create mode 100644 tests/1001-1500/1395. count-number-of-teams/sol.java create mode 100644 tests/1001-1500/1395. count-number-of-teams/sol.kt create mode 100644 tests/1001-1500/1395. count-number-of-teams/sol.py create mode 100644 tests/1001-1500/1395. count-number-of-teams/sol.py2 create mode 100644 tests/1001-1500/1395. count-number-of-teams/sol.rb create mode 100644 tests/1001-1500/1395. count-number-of-teams/sol.rs create mode 100644 tests/1001-1500/1395. count-number-of-teams/sol.swift create mode 100644 tests/1001-1500/1395. count-number-of-teams/sol.ts create mode 100644 tests/1001-1500/1397. find-all-good-strings/manifest.yaml create mode 100644 tests/1001-1500/1397. find-all-good-strings/sol.cpp create mode 100644 tests/1001-1500/1397. find-all-good-strings/sol.cs create mode 100644 tests/1001-1500/1397. find-all-good-strings/sol.dart create mode 100644 tests/1001-1500/1397. find-all-good-strings/sol.go create mode 100644 tests/1001-1500/1397. find-all-good-strings/sol.java create mode 100644 tests/1001-1500/1397. find-all-good-strings/sol.kt create mode 100644 tests/1001-1500/1397. find-all-good-strings/sol.py create mode 100644 tests/1001-1500/1397. find-all-good-strings/sol.py2 create mode 100644 tests/1001-1500/1397. find-all-good-strings/sol.rb create mode 100644 tests/1001-1500/1397. find-all-good-strings/sol.rs create mode 100644 tests/1001-1500/1397. find-all-good-strings/sol.swift create mode 100644 tests/1001-1500/1397. find-all-good-strings/sol.ts create mode 100644 tests/1001-1500/1399. count-largest-group/manifest.yaml create mode 100644 tests/1001-1500/1399. count-largest-group/sol.cpp create mode 100644 tests/1001-1500/1399. count-largest-group/sol.cs create mode 100644 tests/1001-1500/1399. count-largest-group/sol.dart create mode 100644 tests/1001-1500/1399. count-largest-group/sol.go create mode 100644 tests/1001-1500/1399. count-largest-group/sol.java create mode 100644 tests/1001-1500/1399. count-largest-group/sol.kt create mode 100644 tests/1001-1500/1399. count-largest-group/sol.py create mode 100644 tests/1001-1500/1399. count-largest-group/sol.py2 create mode 100644 tests/1001-1500/1399. count-largest-group/sol.rb create mode 100644 tests/1001-1500/1399. count-largest-group/sol.rs create mode 100644 tests/1001-1500/1399. count-largest-group/sol.swift create mode 100644 tests/1001-1500/1399. count-largest-group/sol.ts create mode 100644 tests/1001-1500/1400. construct-k-palindrome-strings/manifest.yaml create mode 100644 tests/1001-1500/1400. construct-k-palindrome-strings/sol.cpp create mode 100644 tests/1001-1500/1400. construct-k-palindrome-strings/sol.cs create mode 100644 tests/1001-1500/1400. construct-k-palindrome-strings/sol.dart create mode 100644 tests/1001-1500/1400. construct-k-palindrome-strings/sol.go create mode 100644 tests/1001-1500/1400. construct-k-palindrome-strings/sol.java create mode 100644 tests/1001-1500/1400. construct-k-palindrome-strings/sol.kt create mode 100644 tests/1001-1500/1400. construct-k-palindrome-strings/sol.py create mode 100644 tests/1001-1500/1400. construct-k-palindrome-strings/sol.py2 create mode 100644 tests/1001-1500/1400. construct-k-palindrome-strings/sol.rb create mode 100644 tests/1001-1500/1400. construct-k-palindrome-strings/sol.rs create mode 100644 tests/1001-1500/1400. construct-k-palindrome-strings/sol.swift create mode 100644 tests/1001-1500/1400. construct-k-palindrome-strings/sol.ts create mode 100644 tests/1001-1500/1401. circle-and-rectangle-overlapping/manifest.yaml create mode 100644 tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.cpp create mode 100644 tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.cs create mode 100644 tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.dart create mode 100644 tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.go create mode 100644 tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.java create mode 100644 tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.kt create mode 100644 tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.py create mode 100644 tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.py2 create mode 100644 tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.rb create mode 100644 tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.rs create mode 100644 tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.swift create mode 100644 tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.ts create mode 100644 tests/1001-1500/1402. reducing-dishes/manifest.yaml create mode 100644 tests/1001-1500/1402. reducing-dishes/sol.cpp create mode 100644 tests/1001-1500/1402. reducing-dishes/sol.cs create mode 100644 tests/1001-1500/1402. reducing-dishes/sol.dart create mode 100644 tests/1001-1500/1402. reducing-dishes/sol.go create mode 100644 tests/1001-1500/1402. reducing-dishes/sol.java create mode 100644 tests/1001-1500/1402. reducing-dishes/sol.kt create mode 100644 tests/1001-1500/1402. reducing-dishes/sol.py create mode 100644 tests/1001-1500/1402. reducing-dishes/sol.py2 create mode 100644 tests/1001-1500/1402. reducing-dishes/sol.rb create mode 100644 tests/1001-1500/1402. reducing-dishes/sol.rs create mode 100644 tests/1001-1500/1402. reducing-dishes/sol.swift create mode 100644 tests/1001-1500/1402. reducing-dishes/sol.ts create mode 100644 tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/manifest.yaml create mode 100644 tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.cpp create mode 100644 tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.cs create mode 100644 tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.dart create mode 100644 tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.go create mode 100644 tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.java create mode 100644 tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.kt create mode 100644 tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.py create mode 100644 tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.py2 create mode 100644 tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.rb create mode 100644 tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.rs create mode 100644 tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.swift create mode 100644 tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.ts create mode 100644 tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/manifest.yaml create mode 100644 tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.cpp create mode 100644 tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.cs create mode 100644 tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.dart create mode 100644 tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.go create mode 100644 tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.java create mode 100644 tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.kt create mode 100644 tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.py create mode 100644 tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.py2 create mode 100644 tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.rb create mode 100644 tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.rs create mode 100644 tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.swift create mode 100644 tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.ts create mode 100644 tests/1001-1500/1405. longest-happy-string/manifest.yaml create mode 100644 tests/1001-1500/1405. longest-happy-string/sol.cpp create mode 100644 tests/1001-1500/1405. longest-happy-string/sol.cs create mode 100644 tests/1001-1500/1405. longest-happy-string/sol.dart create mode 100644 tests/1001-1500/1405. longest-happy-string/sol.go create mode 100644 tests/1001-1500/1405. longest-happy-string/sol.java create mode 100644 tests/1001-1500/1405. longest-happy-string/sol.kt create mode 100644 tests/1001-1500/1405. longest-happy-string/sol.py create mode 100644 tests/1001-1500/1405. longest-happy-string/sol.py2 create mode 100644 tests/1001-1500/1405. longest-happy-string/sol.rb create mode 100644 tests/1001-1500/1405. longest-happy-string/sol.rs create mode 100644 tests/1001-1500/1405. longest-happy-string/sol.swift create mode 100644 tests/1001-1500/1405. longest-happy-string/sol.ts create mode 100644 tests/1001-1500/1406. stone-game-iii/manifest.yaml create mode 100644 tests/1001-1500/1406. stone-game-iii/sol.cpp create mode 100644 tests/1001-1500/1406. stone-game-iii/sol.cs create mode 100644 tests/1001-1500/1406. stone-game-iii/sol.dart create mode 100644 tests/1001-1500/1406. stone-game-iii/sol.go create mode 100644 tests/1001-1500/1406. stone-game-iii/sol.java create mode 100644 tests/1001-1500/1406. stone-game-iii/sol.kt create mode 100644 tests/1001-1500/1406. stone-game-iii/sol.py create mode 100644 tests/1001-1500/1406. stone-game-iii/sol.py2 create mode 100644 tests/1001-1500/1406. stone-game-iii/sol.rb create mode 100644 tests/1001-1500/1406. stone-game-iii/sol.rs create mode 100644 tests/1001-1500/1406. stone-game-iii/sol.swift create mode 100644 tests/1001-1500/1406. stone-game-iii/sol.ts create mode 100644 tests/1001-1500/1408. string-matching-in-an-array/manifest.yaml create mode 100644 tests/1001-1500/1408. string-matching-in-an-array/sol.cpp create mode 100644 tests/1001-1500/1408. string-matching-in-an-array/sol.cs create mode 100644 tests/1001-1500/1408. string-matching-in-an-array/sol.dart create mode 100644 tests/1001-1500/1408. string-matching-in-an-array/sol.go create mode 100644 tests/1001-1500/1408. string-matching-in-an-array/sol.java create mode 100644 tests/1001-1500/1408. string-matching-in-an-array/sol.kt create mode 100644 tests/1001-1500/1408. string-matching-in-an-array/sol.py create mode 100644 tests/1001-1500/1408. string-matching-in-an-array/sol.py2 create mode 100644 tests/1001-1500/1408. string-matching-in-an-array/sol.rb create mode 100644 tests/1001-1500/1408. string-matching-in-an-array/sol.rs create mode 100644 tests/1001-1500/1408. string-matching-in-an-array/sol.swift create mode 100644 tests/1001-1500/1408. string-matching-in-an-array/sol.ts create mode 100644 tests/1001-1500/1409. queries-on-a-permutation-with-key/manifest.yaml create mode 100644 tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.cpp create mode 100644 tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.cs create mode 100644 tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.dart create mode 100644 tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.go create mode 100644 tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.java create mode 100644 tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.kt create mode 100644 tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.py create mode 100644 tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.py2 create mode 100644 tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.rb create mode 100644 tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.rs create mode 100644 tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.swift create mode 100644 tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.ts create mode 100644 tests/1001-1500/1410. html-entity-parser/manifest.yaml create mode 100644 tests/1001-1500/1410. html-entity-parser/sol.cpp create mode 100644 tests/1001-1500/1410. html-entity-parser/sol.cs create mode 100644 tests/1001-1500/1410. html-entity-parser/sol.dart create mode 100644 tests/1001-1500/1410. html-entity-parser/sol.go create mode 100644 tests/1001-1500/1410. html-entity-parser/sol.java create mode 100644 tests/1001-1500/1410. html-entity-parser/sol.kt create mode 100644 tests/1001-1500/1410. html-entity-parser/sol.py create mode 100644 tests/1001-1500/1410. html-entity-parser/sol.py2 create mode 100644 tests/1001-1500/1410. html-entity-parser/sol.rb create mode 100644 tests/1001-1500/1410. html-entity-parser/sol.rs create mode 100644 tests/1001-1500/1410. html-entity-parser/sol.swift create mode 100644 tests/1001-1500/1410. html-entity-parser/sol.ts create mode 100644 tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/manifest.yaml create mode 100644 tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.cpp create mode 100644 tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.cs create mode 100644 tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.dart create mode 100644 tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.go create mode 100644 tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.java create mode 100644 tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.kt create mode 100644 tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.py create mode 100644 tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.py2 create mode 100644 tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.rb create mode 100644 tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.rs create mode 100644 tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.swift create mode 100644 tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.ts create mode 100644 tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/manifest.yaml create mode 100644 tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.cpp create mode 100644 tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.cs create mode 100644 tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.dart create mode 100644 tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.go create mode 100644 tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.java create mode 100644 tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.kt create mode 100644 tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.py create mode 100644 tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.py2 create mode 100644 tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.rb create mode 100644 tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.rs create mode 100644 tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.swift create mode 100644 tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.ts create mode 100644 tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/manifest.yaml create mode 100644 tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.cpp create mode 100644 tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.cs create mode 100644 tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.dart create mode 100644 tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.go create mode 100644 tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.java create mode 100644 tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.kt create mode 100644 tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.py create mode 100644 tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.py2 create mode 100644 tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.rb create mode 100644 tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.rs create mode 100644 tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.swift create mode 100644 tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.ts create mode 100644 tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/manifest.yaml create mode 100644 tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.cpp create mode 100644 tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.cs create mode 100644 tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.dart create mode 100644 tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.go create mode 100644 tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.java create mode 100644 tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.kt create mode 100644 tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.py create mode 100644 tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.py2 create mode 100644 tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.rb create mode 100644 tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.rs create mode 100644 tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.swift create mode 100644 tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.ts create mode 100644 tests/1001-1500/1416. restore-the-array/manifest.yaml create mode 100644 tests/1001-1500/1416. restore-the-array/sol.cpp create mode 100644 tests/1001-1500/1416. restore-the-array/sol.cs create mode 100644 tests/1001-1500/1416. restore-the-array/sol.dart create mode 100644 tests/1001-1500/1416. restore-the-array/sol.go create mode 100644 tests/1001-1500/1416. restore-the-array/sol.java create mode 100644 tests/1001-1500/1416. restore-the-array/sol.kt create mode 100644 tests/1001-1500/1416. restore-the-array/sol.py create mode 100644 tests/1001-1500/1416. restore-the-array/sol.py2 create mode 100644 tests/1001-1500/1416. restore-the-array/sol.rb create mode 100644 tests/1001-1500/1416. restore-the-array/sol.rs create mode 100644 tests/1001-1500/1416. restore-the-array/sol.swift create mode 100644 tests/1001-1500/1416. restore-the-array/sol.ts create mode 100644 tests/1001-1500/1417. reformat-the-string/manifest.yaml create mode 100644 tests/1001-1500/1417. reformat-the-string/sol.cpp create mode 100644 tests/1001-1500/1417. reformat-the-string/sol.cs create mode 100644 tests/1001-1500/1417. reformat-the-string/sol.dart create mode 100644 tests/1001-1500/1417. reformat-the-string/sol.go create mode 100644 tests/1001-1500/1417. reformat-the-string/sol.java create mode 100644 tests/1001-1500/1417. reformat-the-string/sol.kt create mode 100644 tests/1001-1500/1417. reformat-the-string/sol.py create mode 100644 tests/1001-1500/1417. reformat-the-string/sol.py2 create mode 100644 tests/1001-1500/1417. reformat-the-string/sol.rb create mode 100644 tests/1001-1500/1417. reformat-the-string/sol.rs create mode 100644 tests/1001-1500/1417. reformat-the-string/sol.swift create mode 100644 tests/1001-1500/1417. reformat-the-string/sol.ts create mode 100644 tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/manifest.yaml create mode 100644 tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.cpp create mode 100644 tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.cs create mode 100644 tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.dart create mode 100644 tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.go create mode 100644 tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.java create mode 100644 tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.kt create mode 100644 tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.py create mode 100644 tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.py2 create mode 100644 tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.rb create mode 100644 tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.rs create mode 100644 tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.swift create mode 100644 tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.ts create mode 100644 tests/1001-1500/1419. minimum-number-of-frogs-croaking/manifest.yaml create mode 100644 tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.cpp create mode 100644 tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.cs create mode 100644 tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.dart create mode 100644 tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.go create mode 100644 tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.java create mode 100644 tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.kt create mode 100644 tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.py create mode 100644 tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.py2 create mode 100644 tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.rb create mode 100644 tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.rs create mode 100644 tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.swift create mode 100644 tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.ts create mode 100644 tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/manifest.yaml create mode 100644 tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.cpp create mode 100644 tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.cs create mode 100644 tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.dart create mode 100644 tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.go create mode 100644 tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.java create mode 100644 tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.kt create mode 100644 tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.py create mode 100644 tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.py2 create mode 100644 tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.rb create mode 100644 tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.rs create mode 100644 tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.swift create mode 100644 tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.ts create mode 100644 tests/1001-1500/1422. maximum-score-after-splitting-a-string/manifest.yaml create mode 100644 tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.cpp create mode 100644 tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.cs create mode 100644 tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.dart create mode 100644 tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.go create mode 100644 tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.java create mode 100644 tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.kt create mode 100644 tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.py create mode 100644 tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.py2 create mode 100644 tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.rb create mode 100644 tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.rs create mode 100644 tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.swift create mode 100644 tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.ts create mode 100644 tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/manifest.yaml create mode 100644 tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.cpp create mode 100644 tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.cs create mode 100644 tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.dart create mode 100644 tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.go create mode 100644 tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.java create mode 100644 tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.kt create mode 100644 tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.py create mode 100644 tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.py2 create mode 100644 tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.rb create mode 100644 tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.rs create mode 100644 tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.swift create mode 100644 tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.ts create mode 100644 tests/1001-1500/1424. diagonal-traverse-ii/manifest.yaml create mode 100644 tests/1001-1500/1424. diagonal-traverse-ii/sol.cpp create mode 100644 tests/1001-1500/1424. diagonal-traverse-ii/sol.cs create mode 100644 tests/1001-1500/1424. diagonal-traverse-ii/sol.dart create mode 100644 tests/1001-1500/1424. diagonal-traverse-ii/sol.go create mode 100644 tests/1001-1500/1424. diagonal-traverse-ii/sol.java create mode 100644 tests/1001-1500/1424. diagonal-traverse-ii/sol.kt create mode 100644 tests/1001-1500/1424. diagonal-traverse-ii/sol.py create mode 100644 tests/1001-1500/1424. diagonal-traverse-ii/sol.py2 create mode 100644 tests/1001-1500/1424. diagonal-traverse-ii/sol.rb create mode 100644 tests/1001-1500/1424. diagonal-traverse-ii/sol.rs create mode 100644 tests/1001-1500/1424. diagonal-traverse-ii/sol.swift create mode 100644 tests/1001-1500/1424. diagonal-traverse-ii/sol.ts create mode 100644 tests/1001-1500/1425. constrained-subsequence-sum/manifest.yaml create mode 100644 tests/1001-1500/1425. constrained-subsequence-sum/sol.cpp create mode 100644 tests/1001-1500/1425. constrained-subsequence-sum/sol.cs create mode 100644 tests/1001-1500/1425. constrained-subsequence-sum/sol.dart create mode 100644 tests/1001-1500/1425. constrained-subsequence-sum/sol.go create mode 100644 tests/1001-1500/1425. constrained-subsequence-sum/sol.java create mode 100644 tests/1001-1500/1425. constrained-subsequence-sum/sol.kt create mode 100644 tests/1001-1500/1425. constrained-subsequence-sum/sol.py create mode 100644 tests/1001-1500/1425. constrained-subsequence-sum/sol.py2 create mode 100644 tests/1001-1500/1425. constrained-subsequence-sum/sol.rb create mode 100644 tests/1001-1500/1425. constrained-subsequence-sum/sol.rs create mode 100644 tests/1001-1500/1425. constrained-subsequence-sum/sol.swift create mode 100644 tests/1001-1500/1425. constrained-subsequence-sum/sol.ts create mode 100644 tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/manifest.yaml create mode 100644 tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.cpp create mode 100644 tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.cs create mode 100644 tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.dart create mode 100644 tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.go create mode 100644 tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.java create mode 100644 tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.kt create mode 100644 tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.py create mode 100644 tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.py2 create mode 100644 tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.rb create mode 100644 tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.rs create mode 100644 tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.swift create mode 100644 tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.ts create mode 100644 tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/manifest.yaml create mode 100644 tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.cpp create mode 100644 tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.cs create mode 100644 tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.dart create mode 100644 tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.go create mode 100644 tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.java create mode 100644 tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.kt create mode 100644 tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.py create mode 100644 tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.py2 create mode 100644 tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.rb create mode 100644 tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.rs create mode 100644 tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.swift create mode 100644 tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.ts create mode 100644 tests/1001-1500/1433. check-if-a-string-can-break-another-string/manifest.yaml create mode 100644 tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.cpp create mode 100644 tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.cs create mode 100644 tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.dart create mode 100644 tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.go create mode 100644 tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.java create mode 100644 tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.kt create mode 100644 tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.py create mode 100644 tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.py2 create mode 100644 tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.rb create mode 100644 tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.rs create mode 100644 tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.swift create mode 100644 tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.ts create mode 100644 tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/manifest.yaml create mode 100644 tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.cpp create mode 100644 tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.cs create mode 100644 tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.dart create mode 100644 tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.go create mode 100644 tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.java create mode 100644 tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.kt create mode 100644 tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.py create mode 100644 tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.py2 create mode 100644 tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.rb create mode 100644 tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.rs create mode 100644 tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.swift create mode 100644 tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.ts create mode 100644 tests/1001-1500/1436. destination-city/manifest.yaml create mode 100644 tests/1001-1500/1436. destination-city/sol.cpp create mode 100644 tests/1001-1500/1436. destination-city/sol.cs create mode 100644 tests/1001-1500/1436. destination-city/sol.dart create mode 100644 tests/1001-1500/1436. destination-city/sol.go create mode 100644 tests/1001-1500/1436. destination-city/sol.java create mode 100644 tests/1001-1500/1436. destination-city/sol.kt create mode 100644 tests/1001-1500/1436. destination-city/sol.py create mode 100644 tests/1001-1500/1436. destination-city/sol.py2 create mode 100644 tests/1001-1500/1436. destination-city/sol.rb create mode 100644 tests/1001-1500/1436. destination-city/sol.rs create mode 100644 tests/1001-1500/1436. destination-city/sol.swift create mode 100644 tests/1001-1500/1436. destination-city/sol.ts create mode 100644 tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/manifest.yaml create mode 100644 tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.cpp create mode 100644 tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.cs create mode 100644 tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.dart create mode 100644 tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.go create mode 100644 tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.java create mode 100644 tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.kt create mode 100644 tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.py create mode 100644 tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.py2 create mode 100644 tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.rb create mode 100644 tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.rs create mode 100644 tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.swift create mode 100644 tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.ts create mode 100644 tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/manifest.yaml create mode 100644 tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.cpp create mode 100644 tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.cs create mode 100644 tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.dart create mode 100644 tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.go create mode 100644 tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.java create mode 100644 tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.kt create mode 100644 tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.py create mode 100644 tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.py2 create mode 100644 tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.rb create mode 100644 tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.rs create mode 100644 tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.swift create mode 100644 tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.ts create mode 100644 tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/manifest.yaml create mode 100644 tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.cpp create mode 100644 tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.cs create mode 100644 tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.dart create mode 100644 tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.go create mode 100644 tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.java create mode 100644 tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.kt create mode 100644 tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.py create mode 100644 tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.py2 create mode 100644 tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.rb create mode 100644 tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.rs create mode 100644 tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.swift create mode 100644 tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.ts create mode 100644 tests/1001-1500/1441. build-an-array-with-stack-operations/manifest.yaml create mode 100644 tests/1001-1500/1441. build-an-array-with-stack-operations/sol.cpp create mode 100644 tests/1001-1500/1441. build-an-array-with-stack-operations/sol.cs create mode 100644 tests/1001-1500/1441. build-an-array-with-stack-operations/sol.dart create mode 100644 tests/1001-1500/1441. build-an-array-with-stack-operations/sol.go create mode 100644 tests/1001-1500/1441. build-an-array-with-stack-operations/sol.java create mode 100644 tests/1001-1500/1441. build-an-array-with-stack-operations/sol.kt create mode 100644 tests/1001-1500/1441. build-an-array-with-stack-operations/sol.py create mode 100644 tests/1001-1500/1441. build-an-array-with-stack-operations/sol.py2 create mode 100644 tests/1001-1500/1441. build-an-array-with-stack-operations/sol.rb create mode 100644 tests/1001-1500/1441. build-an-array-with-stack-operations/sol.rs create mode 100644 tests/1001-1500/1441. build-an-array-with-stack-operations/sol.swift create mode 100644 tests/1001-1500/1441. build-an-array-with-stack-operations/sol.ts create mode 100644 tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/manifest.yaml create mode 100644 tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.cpp create mode 100644 tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.cs create mode 100644 tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.dart create mode 100644 tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.go create mode 100644 tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.java create mode 100644 tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.kt create mode 100644 tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.py create mode 100644 tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.py2 create mode 100644 tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.rb create mode 100644 tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.rs create mode 100644 tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.swift create mode 100644 tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.ts create mode 100644 tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/manifest.yaml create mode 100644 tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.cpp create mode 100644 tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.cs create mode 100644 tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.dart create mode 100644 tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.go create mode 100644 tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.java create mode 100644 tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.kt create mode 100644 tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.py create mode 100644 tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.py2 create mode 100644 tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.rb create mode 100644 tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.rs create mode 100644 tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.swift create mode 100644 tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.ts create mode 100644 tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/manifest.yaml create mode 100644 tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.cpp create mode 100644 tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.cs create mode 100644 tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.dart create mode 100644 tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.go create mode 100644 tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.java create mode 100644 tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.kt create mode 100644 tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.py create mode 100644 tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.py2 create mode 100644 tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.rb create mode 100644 tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.rs create mode 100644 tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.swift create mode 100644 tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.ts create mode 100644 tests/1001-1500/1446. consecutive-characters/manifest.yaml create mode 100644 tests/1001-1500/1446. consecutive-characters/sol.cpp create mode 100644 tests/1001-1500/1446. consecutive-characters/sol.cs create mode 100644 tests/1001-1500/1446. consecutive-characters/sol.dart create mode 100644 tests/1001-1500/1446. consecutive-characters/sol.go create mode 100644 tests/1001-1500/1446. consecutive-characters/sol.java create mode 100644 tests/1001-1500/1446. consecutive-characters/sol.kt create mode 100644 tests/1001-1500/1446. consecutive-characters/sol.py create mode 100644 tests/1001-1500/1446. consecutive-characters/sol.py2 create mode 100644 tests/1001-1500/1446. consecutive-characters/sol.rb create mode 100644 tests/1001-1500/1446. consecutive-characters/sol.rs create mode 100644 tests/1001-1500/1446. consecutive-characters/sol.swift create mode 100644 tests/1001-1500/1446. consecutive-characters/sol.ts create mode 100644 tests/1001-1500/1447. simplified-fractions/manifest.yaml create mode 100644 tests/1001-1500/1447. simplified-fractions/sol.cpp create mode 100644 tests/1001-1500/1447. simplified-fractions/sol.cs create mode 100644 tests/1001-1500/1447. simplified-fractions/sol.dart create mode 100644 tests/1001-1500/1447. simplified-fractions/sol.go create mode 100644 tests/1001-1500/1447. simplified-fractions/sol.java create mode 100644 tests/1001-1500/1447. simplified-fractions/sol.kt create mode 100644 tests/1001-1500/1447. simplified-fractions/sol.py create mode 100644 tests/1001-1500/1447. simplified-fractions/sol.py2 create mode 100644 tests/1001-1500/1447. simplified-fractions/sol.rb create mode 100644 tests/1001-1500/1447. simplified-fractions/sol.rs create mode 100644 tests/1001-1500/1447. simplified-fractions/sol.swift create mode 100644 tests/1001-1500/1447. simplified-fractions/sol.ts create mode 100644 tests/1001-1500/1448. count-good-nodes-in-binary-tree/manifest.yaml create mode 100644 tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.cpp create mode 100644 tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.cs create mode 100644 tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.dart create mode 100644 tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.go create mode 100644 tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.java create mode 100644 tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.kt create mode 100644 tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.py create mode 100644 tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.py2 create mode 100644 tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.rb create mode 100644 tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.rs create mode 100644 tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.swift create mode 100644 tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.ts create mode 100644 tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/manifest.yaml create mode 100644 tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.cpp create mode 100644 tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.cs create mode 100644 tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.dart create mode 100644 tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.go create mode 100644 tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.java create mode 100644 tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.kt create mode 100644 tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.py create mode 100644 tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.py2 create mode 100644 tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.rb create mode 100644 tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.rs create mode 100644 tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.swift create mode 100644 tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.ts create mode 100644 tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/manifest.yaml create mode 100644 tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.cpp create mode 100644 tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.cs create mode 100644 tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.dart create mode 100644 tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.go create mode 100644 tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.java create mode 100644 tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.kt create mode 100644 tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.py create mode 100644 tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.py2 create mode 100644 tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.rb create mode 100644 tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.rs create mode 100644 tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.swift create mode 100644 tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.ts create mode 100644 tests/1001-1500/1451. rearrange-words-in-a-sentence/manifest.yaml create mode 100644 tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.cpp create mode 100644 tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.cs create mode 100644 tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.dart create mode 100644 tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.go create mode 100644 tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.java create mode 100644 tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.kt create mode 100644 tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.py create mode 100644 tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.py2 create mode 100644 tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.rb create mode 100644 tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.rs create mode 100644 tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.swift create mode 100644 tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.ts create mode 100644 tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/manifest.yaml create mode 100644 tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.cpp create mode 100644 tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.cs create mode 100644 tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.dart create mode 100644 tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.go create mode 100644 tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.java create mode 100644 tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.kt create mode 100644 tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.py create mode 100644 tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.py2 create mode 100644 tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.rb create mode 100644 tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.rs create mode 100644 tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.swift create mode 100644 tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.ts create mode 100644 tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/manifest.yaml create mode 100644 tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.cpp create mode 100644 tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.cs create mode 100644 tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.dart create mode 100644 tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.go create mode 100644 tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.java create mode 100644 tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.kt create mode 100644 tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.py create mode 100644 tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.py2 create mode 100644 tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.rb create mode 100644 tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.rs create mode 100644 tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.swift create mode 100644 tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.ts create mode 100644 tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/manifest.yaml create mode 100644 tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.cpp create mode 100644 tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.cs create mode 100644 tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.dart create mode 100644 tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.go create mode 100644 tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.java create mode 100644 tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.kt create mode 100644 tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.py create mode 100644 tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.py2 create mode 100644 tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.rb create mode 100644 tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.rs create mode 100644 tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.swift create mode 100644 tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.ts create mode 100644 tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/manifest.yaml create mode 100644 tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.cpp create mode 100644 tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.cs create mode 100644 tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.dart create mode 100644 tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.go create mode 100644 tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.java create mode 100644 tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.kt create mode 100644 tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.py create mode 100644 tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.py2 create mode 100644 tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.rb create mode 100644 tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.rs create mode 100644 tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.swift create mode 100644 tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.ts create mode 100644 tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/manifest.yaml create mode 100644 tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.cpp create mode 100644 tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.cs create mode 100644 tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.dart create mode 100644 tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.go create mode 100644 tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.java create mode 100644 tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.kt create mode 100644 tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.py create mode 100644 tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.py2 create mode 100644 tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.rb create mode 100644 tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.rs create mode 100644 tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.swift create mode 100644 tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.ts create mode 100644 tests/1001-1500/1458. max-dot-product-of-two-subsequences/manifest.yaml create mode 100644 tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.cpp create mode 100644 tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.cs create mode 100644 tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.dart create mode 100644 tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.go create mode 100644 tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.java create mode 100644 tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.kt create mode 100644 tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.py create mode 100644 tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.py2 create mode 100644 tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.rb create mode 100644 tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.rs create mode 100644 tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.swift create mode 100644 tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.ts create mode 100644 tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/manifest.yaml create mode 100644 tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.cpp create mode 100644 tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.cs create mode 100644 tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.dart create mode 100644 tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.go create mode 100644 tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.java create mode 100644 tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.kt create mode 100644 tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.py create mode 100644 tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.py2 create mode 100644 tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.rb create mode 100644 tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.rs create mode 100644 tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.swift create mode 100644 tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.ts create mode 100644 tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/manifest.yaml create mode 100644 tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.cpp create mode 100644 tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.cs create mode 100644 tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.dart create mode 100644 tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.go create mode 100644 tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.java create mode 100644 tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.kt create mode 100644 tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.py create mode 100644 tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.py2 create mode 100644 tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.rb create mode 100644 tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.rs create mode 100644 tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.swift create mode 100644 tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.ts create mode 100644 tests/1001-1500/1462. course-schedule-iv/manifest.yaml create mode 100644 tests/1001-1500/1462. course-schedule-iv/sol.cpp create mode 100644 tests/1001-1500/1462. course-schedule-iv/sol.cs create mode 100644 tests/1001-1500/1462. course-schedule-iv/sol.dart create mode 100644 tests/1001-1500/1462. course-schedule-iv/sol.go create mode 100644 tests/1001-1500/1462. course-schedule-iv/sol.java create mode 100644 tests/1001-1500/1462. course-schedule-iv/sol.kt create mode 100644 tests/1001-1500/1462. course-schedule-iv/sol.py create mode 100644 tests/1001-1500/1462. course-schedule-iv/sol.py2 create mode 100644 tests/1001-1500/1462. course-schedule-iv/sol.rb create mode 100644 tests/1001-1500/1462. course-schedule-iv/sol.rs create mode 100644 tests/1001-1500/1462. course-schedule-iv/sol.swift create mode 100644 tests/1001-1500/1462. course-schedule-iv/sol.ts create mode 100644 tests/1001-1500/1463. cherry-pickup-ii/manifest.yaml create mode 100644 tests/1001-1500/1463. cherry-pickup-ii/sol.cpp create mode 100644 tests/1001-1500/1463. cherry-pickup-ii/sol.cs create mode 100644 tests/1001-1500/1463. cherry-pickup-ii/sol.dart create mode 100644 tests/1001-1500/1463. cherry-pickup-ii/sol.go create mode 100644 tests/1001-1500/1463. cherry-pickup-ii/sol.java create mode 100644 tests/1001-1500/1463. cherry-pickup-ii/sol.kt create mode 100644 tests/1001-1500/1463. cherry-pickup-ii/sol.py create mode 100644 tests/1001-1500/1463. cherry-pickup-ii/sol.py2 create mode 100644 tests/1001-1500/1463. cherry-pickup-ii/sol.rb create mode 100644 tests/1001-1500/1463. cherry-pickup-ii/sol.rs create mode 100644 tests/1001-1500/1463. cherry-pickup-ii/sol.swift create mode 100644 tests/1001-1500/1463. cherry-pickup-ii/sol.ts create mode 100644 tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/manifest.yaml create mode 100644 tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.cpp create mode 100644 tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.cs create mode 100644 tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.dart create mode 100644 tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.go create mode 100644 tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.java create mode 100644 tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.kt create mode 100644 tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.py create mode 100644 tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.py2 create mode 100644 tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.rb create mode 100644 tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.rs create mode 100644 tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.swift create mode 100644 tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.ts create mode 100644 tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/manifest.yaml create mode 100644 tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.cpp create mode 100644 tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.cs create mode 100644 tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.dart create mode 100644 tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.go create mode 100644 tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.java create mode 100644 tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.kt create mode 100644 tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.py create mode 100644 tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.py2 create mode 100644 tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.rb create mode 100644 tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.rs create mode 100644 tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.swift create mode 100644 tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.ts create mode 100644 tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/manifest.yaml create mode 100644 tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.cpp create mode 100644 tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.cs create mode 100644 tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.dart create mode 100644 tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.go create mode 100644 tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.java create mode 100644 tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.kt create mode 100644 tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.py create mode 100644 tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.py2 create mode 100644 tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.rb create mode 100644 tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.rs create mode 100644 tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.swift create mode 100644 tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.ts create mode 100644 tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/manifest.yaml create mode 100644 tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.cpp create mode 100644 tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.cs create mode 100644 tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.dart create mode 100644 tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.go create mode 100644 tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.java create mode 100644 tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.kt create mode 100644 tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.py create mode 100644 tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.py2 create mode 100644 tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.rb create mode 100644 tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.rs create mode 100644 tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.swift create mode 100644 tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.ts create mode 100644 tests/1001-1500/1470. shuffle-the-array/manifest.yaml create mode 100644 tests/1001-1500/1470. shuffle-the-array/sol.cpp create mode 100644 tests/1001-1500/1470. shuffle-the-array/sol.cs create mode 100644 tests/1001-1500/1470. shuffle-the-array/sol.dart create mode 100644 tests/1001-1500/1470. shuffle-the-array/sol.go create mode 100644 tests/1001-1500/1470. shuffle-the-array/sol.java create mode 100644 tests/1001-1500/1470. shuffle-the-array/sol.kt create mode 100644 tests/1001-1500/1470. shuffle-the-array/sol.py create mode 100644 tests/1001-1500/1470. shuffle-the-array/sol.py2 create mode 100644 tests/1001-1500/1470. shuffle-the-array/sol.rb create mode 100644 tests/1001-1500/1470. shuffle-the-array/sol.rs create mode 100644 tests/1001-1500/1470. shuffle-the-array/sol.swift create mode 100644 tests/1001-1500/1470. shuffle-the-array/sol.ts create mode 100644 tests/1001-1500/1471. the-k-strongest-values-in-an-array/manifest.yaml create mode 100644 tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.cpp create mode 100644 tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.cs create mode 100644 tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.dart create mode 100644 tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.go create mode 100644 tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.java create mode 100644 tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.kt create mode 100644 tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.py create mode 100644 tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.py2 create mode 100644 tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.rb create mode 100644 tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.rs create mode 100644 tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.swift create mode 100644 tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.ts create mode 100644 tests/1001-1500/1473. paint-house-iii/manifest.yaml create mode 100644 tests/1001-1500/1473. paint-house-iii/sol.cpp create mode 100644 tests/1001-1500/1473. paint-house-iii/sol.cs create mode 100644 tests/1001-1500/1473. paint-house-iii/sol.dart create mode 100644 tests/1001-1500/1473. paint-house-iii/sol.go create mode 100644 tests/1001-1500/1473. paint-house-iii/sol.java create mode 100644 tests/1001-1500/1473. paint-house-iii/sol.kt create mode 100644 tests/1001-1500/1473. paint-house-iii/sol.py create mode 100644 tests/1001-1500/1473. paint-house-iii/sol.py2 create mode 100644 tests/1001-1500/1473. paint-house-iii/sol.rb create mode 100644 tests/1001-1500/1473. paint-house-iii/sol.rs create mode 100644 tests/1001-1500/1473. paint-house-iii/sol.swift create mode 100644 tests/1001-1500/1473. paint-house-iii/sol.ts create mode 100644 tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/manifest.yaml create mode 100644 tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.cpp create mode 100644 tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.cs create mode 100644 tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.dart create mode 100644 tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.go create mode 100644 tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.java create mode 100644 tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.kt create mode 100644 tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.py create mode 100644 tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.py2 create mode 100644 tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.rb create mode 100644 tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.rs create mode 100644 tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.swift create mode 100644 tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.ts create mode 100644 tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/manifest.yaml create mode 100644 tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.cpp create mode 100644 tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.cs create mode 100644 tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.dart create mode 100644 tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.go create mode 100644 tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.java create mode 100644 tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.kt create mode 100644 tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.py create mode 100644 tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.py2 create mode 100644 tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.rb create mode 100644 tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.rs create mode 100644 tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.swift create mode 100644 tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.ts create mode 100644 tests/1001-1500/1478. allocate-mailboxes/manifest.yaml create mode 100644 tests/1001-1500/1478. allocate-mailboxes/sol.cpp create mode 100644 tests/1001-1500/1478. allocate-mailboxes/sol.cs create mode 100644 tests/1001-1500/1478. allocate-mailboxes/sol.dart create mode 100644 tests/1001-1500/1478. allocate-mailboxes/sol.go create mode 100644 tests/1001-1500/1478. allocate-mailboxes/sol.java create mode 100644 tests/1001-1500/1478. allocate-mailboxes/sol.kt create mode 100644 tests/1001-1500/1478. allocate-mailboxes/sol.py create mode 100644 tests/1001-1500/1478. allocate-mailboxes/sol.py2 create mode 100644 tests/1001-1500/1478. allocate-mailboxes/sol.rb create mode 100644 tests/1001-1500/1478. allocate-mailboxes/sol.rs create mode 100644 tests/1001-1500/1478. allocate-mailboxes/sol.swift create mode 100644 tests/1001-1500/1478. allocate-mailboxes/sol.ts create mode 100644 tests/1001-1500/1480. running-sum-of-1d-array/manifest.yaml create mode 100644 tests/1001-1500/1480. running-sum-of-1d-array/sol.cpp create mode 100644 tests/1001-1500/1480. running-sum-of-1d-array/sol.cs create mode 100644 tests/1001-1500/1480. running-sum-of-1d-array/sol.dart create mode 100644 tests/1001-1500/1480. running-sum-of-1d-array/sol.go create mode 100644 tests/1001-1500/1480. running-sum-of-1d-array/sol.java create mode 100644 tests/1001-1500/1480. running-sum-of-1d-array/sol.kt create mode 100644 tests/1001-1500/1480. running-sum-of-1d-array/sol.py create mode 100644 tests/1001-1500/1480. running-sum-of-1d-array/sol.py2 create mode 100644 tests/1001-1500/1480. running-sum-of-1d-array/sol.rb create mode 100644 tests/1001-1500/1480. running-sum-of-1d-array/sol.rs create mode 100644 tests/1001-1500/1480. running-sum-of-1d-array/sol.swift create mode 100644 tests/1001-1500/1480. running-sum-of-1d-array/sol.ts create mode 100644 tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/manifest.yaml create mode 100644 tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.cpp create mode 100644 tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.cs create mode 100644 tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.dart create mode 100644 tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.go create mode 100644 tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.java create mode 100644 tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.kt create mode 100644 tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.py create mode 100644 tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.py2 create mode 100644 tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.rb create mode 100644 tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.rs create mode 100644 tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.swift create mode 100644 tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.ts create mode 100644 tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/manifest.yaml create mode 100644 tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.cpp create mode 100644 tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.cs create mode 100644 tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.dart create mode 100644 tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.go create mode 100644 tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.java create mode 100644 tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.kt create mode 100644 tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.py create mode 100644 tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.py2 create mode 100644 tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.rb create mode 100644 tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.rs create mode 100644 tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.swift create mode 100644 tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.ts create mode 100644 tests/1001-1500/1486. xor-operation-in-an-array/manifest.yaml create mode 100644 tests/1001-1500/1486. xor-operation-in-an-array/sol.cpp create mode 100644 tests/1001-1500/1486. xor-operation-in-an-array/sol.cs create mode 100644 tests/1001-1500/1486. xor-operation-in-an-array/sol.dart create mode 100644 tests/1001-1500/1486. xor-operation-in-an-array/sol.go create mode 100644 tests/1001-1500/1486. xor-operation-in-an-array/sol.java create mode 100644 tests/1001-1500/1486. xor-operation-in-an-array/sol.kt create mode 100644 tests/1001-1500/1486. xor-operation-in-an-array/sol.py create mode 100644 tests/1001-1500/1486. xor-operation-in-an-array/sol.py2 create mode 100644 tests/1001-1500/1486. xor-operation-in-an-array/sol.rb create mode 100644 tests/1001-1500/1486. xor-operation-in-an-array/sol.rs create mode 100644 tests/1001-1500/1486. xor-operation-in-an-array/sol.swift create mode 100644 tests/1001-1500/1486. xor-operation-in-an-array/sol.ts create mode 100644 tests/1001-1500/1487. making-file-names-unique/manifest.yaml create mode 100644 tests/1001-1500/1487. making-file-names-unique/sol.cpp create mode 100644 tests/1001-1500/1487. making-file-names-unique/sol.cs create mode 100644 tests/1001-1500/1487. making-file-names-unique/sol.dart create mode 100644 tests/1001-1500/1487. making-file-names-unique/sol.go create mode 100644 tests/1001-1500/1487. making-file-names-unique/sol.java create mode 100644 tests/1001-1500/1487. making-file-names-unique/sol.kt create mode 100644 tests/1001-1500/1487. making-file-names-unique/sol.py create mode 100644 tests/1001-1500/1487. making-file-names-unique/sol.py2 create mode 100644 tests/1001-1500/1487. making-file-names-unique/sol.rb create mode 100644 tests/1001-1500/1487. making-file-names-unique/sol.rs create mode 100644 tests/1001-1500/1487. making-file-names-unique/sol.swift create mode 100644 tests/1001-1500/1487. making-file-names-unique/sol.ts create mode 100644 tests/1001-1500/1488. avoid-flood-in-the-city/manifest.yaml create mode 100644 tests/1001-1500/1488. avoid-flood-in-the-city/sol.cpp create mode 100644 tests/1001-1500/1488. avoid-flood-in-the-city/sol.cs create mode 100644 tests/1001-1500/1488. avoid-flood-in-the-city/sol.dart create mode 100644 tests/1001-1500/1488. avoid-flood-in-the-city/sol.go create mode 100644 tests/1001-1500/1488. avoid-flood-in-the-city/sol.java create mode 100644 tests/1001-1500/1488. avoid-flood-in-the-city/sol.kt create mode 100644 tests/1001-1500/1488. avoid-flood-in-the-city/sol.py create mode 100644 tests/1001-1500/1488. avoid-flood-in-the-city/sol.py2 create mode 100644 tests/1001-1500/1488. avoid-flood-in-the-city/sol.rb create mode 100644 tests/1001-1500/1488. avoid-flood-in-the-city/sol.rs create mode 100644 tests/1001-1500/1488. avoid-flood-in-the-city/sol.swift create mode 100644 tests/1001-1500/1488. avoid-flood-in-the-city/sol.ts create mode 100644 tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/manifest.yaml create mode 100644 tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.cpp create mode 100644 tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.cs create mode 100644 tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.dart create mode 100644 tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.go create mode 100644 tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.java create mode 100644 tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.kt create mode 100644 tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.py create mode 100644 tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.py2 create mode 100644 tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.rb create mode 100644 tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.rs create mode 100644 tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.swift create mode 100644 tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.ts create mode 100644 tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/manifest.yaml create mode 100644 tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.cpp create mode 100644 tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.cs create mode 100644 tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.dart create mode 100644 tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.go create mode 100644 tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.java create mode 100644 tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.kt create mode 100644 tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.py create mode 100644 tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.py2 create mode 100644 tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.rb create mode 100644 tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.rs create mode 100644 tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.swift create mode 100644 tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.ts create mode 100644 tests/1001-1500/1492. the-kth-factor-of-n/manifest.yaml create mode 100644 tests/1001-1500/1492. the-kth-factor-of-n/sol.cpp create mode 100644 tests/1001-1500/1492. the-kth-factor-of-n/sol.cs create mode 100644 tests/1001-1500/1492. the-kth-factor-of-n/sol.dart create mode 100644 tests/1001-1500/1492. the-kth-factor-of-n/sol.go create mode 100644 tests/1001-1500/1492. the-kth-factor-of-n/sol.java create mode 100644 tests/1001-1500/1492. the-kth-factor-of-n/sol.kt create mode 100644 tests/1001-1500/1492. the-kth-factor-of-n/sol.py create mode 100644 tests/1001-1500/1492. the-kth-factor-of-n/sol.py2 create mode 100644 tests/1001-1500/1492. the-kth-factor-of-n/sol.rb create mode 100644 tests/1001-1500/1492. the-kth-factor-of-n/sol.rs create mode 100644 tests/1001-1500/1492. the-kth-factor-of-n/sol.swift create mode 100644 tests/1001-1500/1492. the-kth-factor-of-n/sol.ts create mode 100644 tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/manifest.yaml create mode 100644 tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.cpp create mode 100644 tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.cs create mode 100644 tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.dart create mode 100644 tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.go create mode 100644 tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.java create mode 100644 tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.kt create mode 100644 tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.py create mode 100644 tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.py2 create mode 100644 tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.rb create mode 100644 tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.rs create mode 100644 tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.swift create mode 100644 tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.ts create mode 100644 tests/1001-1500/1494. parallel-courses-ii/manifest.yaml create mode 100644 tests/1001-1500/1494. parallel-courses-ii/sol.cpp create mode 100644 tests/1001-1500/1494. parallel-courses-ii/sol.cs create mode 100644 tests/1001-1500/1494. parallel-courses-ii/sol.dart create mode 100644 tests/1001-1500/1494. parallel-courses-ii/sol.go create mode 100644 tests/1001-1500/1494. parallel-courses-ii/sol.java create mode 100644 tests/1001-1500/1494. parallel-courses-ii/sol.kt create mode 100644 tests/1001-1500/1494. parallel-courses-ii/sol.py create mode 100644 tests/1001-1500/1494. parallel-courses-ii/sol.py2 create mode 100644 tests/1001-1500/1494. parallel-courses-ii/sol.rb create mode 100644 tests/1001-1500/1494. parallel-courses-ii/sol.rs create mode 100644 tests/1001-1500/1494. parallel-courses-ii/sol.swift create mode 100644 tests/1001-1500/1494. parallel-courses-ii/sol.ts create mode 100644 tests/1001-1500/1496. path-crossing/manifest.yaml create mode 100644 tests/1001-1500/1496. path-crossing/sol.cpp create mode 100644 tests/1001-1500/1496. path-crossing/sol.cs create mode 100644 tests/1001-1500/1496. path-crossing/sol.dart create mode 100644 tests/1001-1500/1496. path-crossing/sol.go create mode 100644 tests/1001-1500/1496. path-crossing/sol.java create mode 100644 tests/1001-1500/1496. path-crossing/sol.kt create mode 100644 tests/1001-1500/1496. path-crossing/sol.py create mode 100644 tests/1001-1500/1496. path-crossing/sol.py2 create mode 100644 tests/1001-1500/1496. path-crossing/sol.rb create mode 100644 tests/1001-1500/1496. path-crossing/sol.rs create mode 100644 tests/1001-1500/1496. path-crossing/sol.swift create mode 100644 tests/1001-1500/1496. path-crossing/sol.ts create mode 100644 tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/manifest.yaml create mode 100644 tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.cpp create mode 100644 tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.cs create mode 100644 tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.dart create mode 100644 tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.go create mode 100644 tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.java create mode 100644 tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.kt create mode 100644 tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.py create mode 100644 tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.py2 create mode 100644 tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.rb create mode 100644 tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.rs create mode 100644 tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.swift create mode 100644 tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.ts create mode 100644 tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/manifest.yaml create mode 100644 tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.cpp create mode 100644 tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.cs create mode 100644 tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.dart create mode 100644 tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.go create mode 100644 tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.java create mode 100644 tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.kt create mode 100644 tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.py create mode 100644 tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.py2 create mode 100644 tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.rb create mode 100644 tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.rs create mode 100644 tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.swift create mode 100644 tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.ts create mode 100644 tests/1001-1500/1499. max-value-of-equation/manifest.yaml create mode 100644 tests/1001-1500/1499. max-value-of-equation/sol.cpp create mode 100644 tests/1001-1500/1499. max-value-of-equation/sol.cs create mode 100644 tests/1001-1500/1499. max-value-of-equation/sol.dart create mode 100644 tests/1001-1500/1499. max-value-of-equation/sol.go create mode 100644 tests/1001-1500/1499. max-value-of-equation/sol.java create mode 100644 tests/1001-1500/1499. max-value-of-equation/sol.kt create mode 100644 tests/1001-1500/1499. max-value-of-equation/sol.py create mode 100644 tests/1001-1500/1499. max-value-of-equation/sol.py2 create mode 100644 tests/1001-1500/1499. max-value-of-equation/sol.rb create mode 100644 tests/1001-1500/1499. max-value-of-equation/sol.rs create mode 100644 tests/1001-1500/1499. max-value-of-equation/sol.swift create mode 100644 tests/1001-1500/1499. max-value-of-equation/sol.ts create mode 100644 tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/manifest.yaml create mode 100644 tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.cpp create mode 100644 tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.cs create mode 100644 tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.dart create mode 100644 tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.go create mode 100644 tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.java create mode 100644 tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.kt create mode 100644 tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.py create mode 100644 tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.py2 create mode 100644 tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.rb create mode 100644 tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.rs create mode 100644 tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.swift create mode 100644 tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.ts create mode 100644 tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/manifest.yaml create mode 100644 tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.cpp create mode 100644 tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.cs create mode 100644 tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.dart create mode 100644 tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.go create mode 100644 tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.java create mode 100644 tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.kt create mode 100644 tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.py create mode 100644 tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.py2 create mode 100644 tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.rb create mode 100644 tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.rs create mode 100644 tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.swift create mode 100644 tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.ts create mode 100644 tests/1501-2000/1504. count-submatrices-with-all-ones/manifest.yaml create mode 100644 tests/1501-2000/1504. count-submatrices-with-all-ones/sol.cpp create mode 100644 tests/1501-2000/1504. count-submatrices-with-all-ones/sol.cs create mode 100644 tests/1501-2000/1504. count-submatrices-with-all-ones/sol.dart create mode 100644 tests/1501-2000/1504. count-submatrices-with-all-ones/sol.go create mode 100644 tests/1501-2000/1504. count-submatrices-with-all-ones/sol.java create mode 100644 tests/1501-2000/1504. count-submatrices-with-all-ones/sol.kt create mode 100644 tests/1501-2000/1504. count-submatrices-with-all-ones/sol.py create mode 100644 tests/1501-2000/1504. count-submatrices-with-all-ones/sol.py2 create mode 100644 tests/1501-2000/1504. count-submatrices-with-all-ones/sol.rb create mode 100644 tests/1501-2000/1504. count-submatrices-with-all-ones/sol.rs create mode 100644 tests/1501-2000/1504. count-submatrices-with-all-ones/sol.swift create mode 100644 tests/1501-2000/1504. count-submatrices-with-all-ones/sol.ts create mode 100644 tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/manifest.yaml create mode 100644 tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.cpp create mode 100644 tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.cs create mode 100644 tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.dart create mode 100644 tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.go create mode 100644 tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.java create mode 100644 tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.kt create mode 100644 tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.py create mode 100644 tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.py2 create mode 100644 tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.rb create mode 100644 tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.rs create mode 100644 tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.swift create mode 100644 tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.ts create mode 100644 tests/1501-2000/1507. reformat-date/manifest.yaml create mode 100644 tests/1501-2000/1507. reformat-date/sol.cpp create mode 100644 tests/1501-2000/1507. reformat-date/sol.cs create mode 100644 tests/1501-2000/1507. reformat-date/sol.dart create mode 100644 tests/1501-2000/1507. reformat-date/sol.go create mode 100644 tests/1501-2000/1507. reformat-date/sol.java create mode 100644 tests/1501-2000/1507. reformat-date/sol.kt create mode 100644 tests/1501-2000/1507. reformat-date/sol.py create mode 100644 tests/1501-2000/1507. reformat-date/sol.py2 create mode 100644 tests/1501-2000/1507. reformat-date/sol.rb create mode 100644 tests/1501-2000/1507. reformat-date/sol.rs create mode 100644 tests/1501-2000/1507. reformat-date/sol.swift create mode 100644 tests/1501-2000/1507. reformat-date/sol.ts create mode 100644 tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/manifest.yaml create mode 100644 tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.cpp create mode 100644 tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.cs create mode 100644 tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.dart create mode 100644 tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.go create mode 100644 tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.java create mode 100644 tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.kt create mode 100644 tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.py create mode 100644 tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.py2 create mode 100644 tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.rb create mode 100644 tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.rs create mode 100644 tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.swift create mode 100644 tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.ts create mode 100644 tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/manifest.yaml create mode 100644 tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.cpp create mode 100644 tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.cs create mode 100644 tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.dart create mode 100644 tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.go create mode 100644 tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.java create mode 100644 tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.kt create mode 100644 tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.py create mode 100644 tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.py2 create mode 100644 tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.rb create mode 100644 tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.rs create mode 100644 tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.swift create mode 100644 tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.ts create mode 100644 tests/1501-2000/1510. stone-game-iv/manifest.yaml create mode 100644 tests/1501-2000/1510. stone-game-iv/sol.cpp create mode 100644 tests/1501-2000/1510. stone-game-iv/sol.cs create mode 100644 tests/1501-2000/1510. stone-game-iv/sol.dart create mode 100644 tests/1501-2000/1510. stone-game-iv/sol.go create mode 100644 tests/1501-2000/1510. stone-game-iv/sol.java create mode 100644 tests/1501-2000/1510. stone-game-iv/sol.kt create mode 100644 tests/1501-2000/1510. stone-game-iv/sol.py create mode 100644 tests/1501-2000/1510. stone-game-iv/sol.py2 create mode 100644 tests/1501-2000/1510. stone-game-iv/sol.rb create mode 100644 tests/1501-2000/1510. stone-game-iv/sol.rs create mode 100644 tests/1501-2000/1510. stone-game-iv/sol.swift create mode 100644 tests/1501-2000/1510. stone-game-iv/sol.ts create mode 100644 tests/1501-2000/1512. number-of-good-pairs/manifest.yaml create mode 100644 tests/1501-2000/1512. number-of-good-pairs/sol.cpp create mode 100644 tests/1501-2000/1512. number-of-good-pairs/sol.cs create mode 100644 tests/1501-2000/1512. number-of-good-pairs/sol.dart create mode 100644 tests/1501-2000/1512. number-of-good-pairs/sol.go create mode 100644 tests/1501-2000/1512. number-of-good-pairs/sol.java create mode 100644 tests/1501-2000/1512. number-of-good-pairs/sol.kt create mode 100644 tests/1501-2000/1512. number-of-good-pairs/sol.py create mode 100644 tests/1501-2000/1512. number-of-good-pairs/sol.py2 create mode 100644 tests/1501-2000/1512. number-of-good-pairs/sol.rb create mode 100644 tests/1501-2000/1512. number-of-good-pairs/sol.rs create mode 100644 tests/1501-2000/1512. number-of-good-pairs/sol.swift create mode 100644 tests/1501-2000/1512. number-of-good-pairs/sol.ts create mode 100644 tests/1501-2000/1513. number-of-substrings-with-only-1s/manifest.yaml create mode 100644 tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.cpp create mode 100644 tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.cs create mode 100644 tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.dart create mode 100644 tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.go create mode 100644 tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.java create mode 100644 tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.kt create mode 100644 tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.py create mode 100644 tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.py2 create mode 100644 tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.rb create mode 100644 tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.rs create mode 100644 tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.swift create mode 100644 tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.ts create mode 100644 tests/1501-2000/1514. path-with-maximum-probability/manifest.yaml create mode 100644 tests/1501-2000/1514. path-with-maximum-probability/sol.cpp create mode 100644 tests/1501-2000/1514. path-with-maximum-probability/sol.cs create mode 100644 tests/1501-2000/1514. path-with-maximum-probability/sol.dart create mode 100644 tests/1501-2000/1514. path-with-maximum-probability/sol.go create mode 100644 tests/1501-2000/1514. path-with-maximum-probability/sol.java create mode 100644 tests/1501-2000/1514. path-with-maximum-probability/sol.kt create mode 100644 tests/1501-2000/1514. path-with-maximum-probability/sol.py create mode 100644 tests/1501-2000/1514. path-with-maximum-probability/sol.py2 create mode 100644 tests/1501-2000/1514. path-with-maximum-probability/sol.rb create mode 100644 tests/1501-2000/1514. path-with-maximum-probability/sol.rs create mode 100644 tests/1501-2000/1514. path-with-maximum-probability/sol.swift create mode 100644 tests/1501-2000/1514. path-with-maximum-probability/sol.ts create mode 100644 tests/1501-2000/1515. best-position-for-a-service-centre/manifest.yaml create mode 100644 tests/1501-2000/1515. best-position-for-a-service-centre/sol.cpp create mode 100644 tests/1501-2000/1515. best-position-for-a-service-centre/sol.cs create mode 100644 tests/1501-2000/1515. best-position-for-a-service-centre/sol.dart create mode 100644 tests/1501-2000/1515. best-position-for-a-service-centre/sol.go create mode 100644 tests/1501-2000/1515. best-position-for-a-service-centre/sol.java create mode 100644 tests/1501-2000/1515. best-position-for-a-service-centre/sol.kt create mode 100644 tests/1501-2000/1515. best-position-for-a-service-centre/sol.py create mode 100644 tests/1501-2000/1515. best-position-for-a-service-centre/sol.py2 create mode 100644 tests/1501-2000/1515. best-position-for-a-service-centre/sol.rb create mode 100644 tests/1501-2000/1515. best-position-for-a-service-centre/sol.rs create mode 100644 tests/1501-2000/1515. best-position-for-a-service-centre/sol.swift create mode 100644 tests/1501-2000/1515. best-position-for-a-service-centre/sol.ts create mode 100644 tests/1501-2000/1518. water-bottles/manifest.yaml create mode 100644 tests/1501-2000/1518. water-bottles/sol.cpp create mode 100644 tests/1501-2000/1518. water-bottles/sol.cs create mode 100644 tests/1501-2000/1518. water-bottles/sol.dart create mode 100644 tests/1501-2000/1518. water-bottles/sol.go create mode 100644 tests/1501-2000/1518. water-bottles/sol.java create mode 100644 tests/1501-2000/1518. water-bottles/sol.kt create mode 100644 tests/1501-2000/1518. water-bottles/sol.py create mode 100644 tests/1501-2000/1518. water-bottles/sol.py2 create mode 100644 tests/1501-2000/1518. water-bottles/sol.rb create mode 100644 tests/1501-2000/1518. water-bottles/sol.rs create mode 100644 tests/1501-2000/1518. water-bottles/sol.swift create mode 100644 tests/1501-2000/1518. water-bottles/sol.ts create mode 100644 tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/manifest.yaml create mode 100644 tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.cpp create mode 100644 tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.cs create mode 100644 tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.dart create mode 100644 tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.go create mode 100644 tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.java create mode 100644 tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.kt create mode 100644 tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.py create mode 100644 tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.py2 create mode 100644 tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.rb create mode 100644 tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.rs create mode 100644 tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.swift create mode 100644 tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.ts diff --git a/tests/1001-1500/1124. longest-well-performing-interval/manifest.yaml b/tests/1001-1500/1124. longest-well-performing-interval/manifest.yaml index 29bfad87..41ac28ca 100644 --- a/tests/1001-1500/1124. longest-well-performing-interval/manifest.yaml +++ b/tests/1001-1500/1124. longest-well-performing-interval/manifest.yaml @@ -7,18 +7,18 @@ entry: items: type: int call: - python3: Solution().longestWPI({hours}) - python2: Solution().longestWPI({hours}) - cpp: Solution().longestWPI({hours}) - rust: Solution::longest_wpi({hours}) - ruby: longest_wpi({hours}) - java: new Solution().longestWPI({hours}) - csharp: new Solution().LongestWPI({hours}) - kotlin: Solution().longestWPI({hours}) - go: longestWPI({hours}) - dart: Solution().longestWPI({hours}) - swift: Solution().longestWPI({hours}) - typescript: longestWPI({hours}) + cpp: "Solution().longestWPI({hours})" + rust: "Solution::longest_wpi({hours})" + python3: "Solution().longestWPI({hours})" + python2: "Solution().longestWPI({hours})" + ruby: "longest_wpi({hours})" + java: "new Solution().longestWPI({hours})" + csharp: "new Solution().LongestWPI({hours})" + kotlin: "Solution().longestWPI({hours})" + go: "longestWPI({hours})" + dart: "Solution().longestWPI({hours})" + swift: "Solution().longestWPI({hours})" + typescript: "longestWPI({hours})" judge: type: exact limits: @@ -26,375 +26,247 @@ limits: memory_mb: 256 oracle: python3: - call: Checker().longestWPI(hours, {result}) - checker: - "class Checker:\n def longestWPI(self, hours, result):\n if\ - \ not isinstance(hours, list):\n return False\n if not isinstance(result,\ - \ int):\n return False\n score = 0\n best = 0\n \ - \ seen_at = {0: -1}\n for i, h in enumerate(hours):\n \ - \ if not isinstance(h, int) or h < 0 or h > 16:\n return False\n\ - \ score += 1 if h > 8 else -1\n if score > 0:\n \ - \ best = i + 1\n elif score - 1 in seen_at:\n \ - \ best = max(best, i - seen_at[score - 1])\n if score not in\ - \ seen_at:\n seen_at[score] = i\n return result == best\n" + call: "Checker().longestWPI(hours, {result})" + checker: | + class Checker: + def longestWPI(self, hours, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if not isinstance(hours, list) or not 1 <= len(hours) <= 10000: + return False + if any(not isinstance(h, int) or isinstance(h, bool) or not 0 <= h <= 16 for h in hours): + return False + prefix = [0] + for hour in hours: + prefix.append(prefix[-1] + (1 if hour > 8 else -1)) + decreasing = [] + for index, value in enumerate(prefix): + if not decreasing or value < prefix[decreasing[-1]]: + decreasing.append(index) + best = 0 + for right in range(len(prefix) - 1, -1, -1): + while decreasing and prefix[right] > prefix[decreasing[-1]]: + best = max(best, right - decreasing.pop()) + return result == best seed: 1124 tests: - - name: single_tiring + - name: example_one in: - hours: - - 9 - - name: single_non_tiring + hours: [9, 9, 6, 0, 6, 6, 9] + out: 3 + - name: example_two in: - hours: - - 6 - - name: single_boundary + hours: [6, 6, 6] + out: 0 + - name: one_tiring in: - hours: - - 8 - - name: single_high + hours: [9] + out: 1 + - name: one_non_tiring in: - hours: - - 10 - - name: single_zero + hours: [8] + out: 0 + - name: minimum_value in: - hours: - - 0 - - name: single_max_value + hours: [0] + out: 0 + - name: maximum_value in: - hours: - - 16 - - name: two_all_tiring + hours: [16] + out: 1 + - name: threshold_values in: - hours: - - 9 - - 9 - - name: two_all_non_tiring + hours: [8, 9, 8, 9, 8] + out: 3 + - name: all_tiring in: - hours: - - 6 - - 6 - - name: tiring_then_non_tiring + hours: [9, 10, 11, 12, 13, 14, 15, 16] + out: 8 + - name: all_non_tiring in: - hours: - - 9 - - 6 - - name: non_tiring_then_tiring + hours: [0, 1, 7, 8, 8, 2] + out: 0 + - name: tiring_then_rest in: - hours: - - 6 - - 9 - - name: example_one + hours: [9, 8] + out: 1 + - name: rest_then_tiring in: - hours: - - 9 - - 9 - - 6 - - 0 - - 6 - - 6 - - 9 - - name: example_two + hours: [8, 9] + out: 1 + - name: balanced_pair in: - hours: - - 6 - - 6 - - 6 - - name: all_prefix_positive + hours: [9, 8, 8, 9] + out: 1 + - name: late_positive in: - hours: - - 9 - - 6 - - 9 - - name: alternating_small + hours: [8, 8, 9] + out: 1 + - name: early_positive in: - hours: - - 6 - - 9 - - 6 - - name: long_first_block + hours: [9, 8, 8] + out: 1 + - name: buried_interval in: - hours: - - 9 - - 9 - - 9 - - 6 - - 6 - - name: long_last_block + hours: [8, 8, 9, 9, 8, 8, 9] + out: 5 + - name: alternating_tiring_start in: - hours: - - 6 - - 6 - - 9 - - 9 - - 9 - - name: boundary_alternation + hours: [9, 8, 9, 8, 9, 8, 9, 8] + out: 7 + - name: alternating_rest_start in: - hours: - - 8 - - 9 - - 8 - - 9 - - 8 - - name: mixed_with_prefix_gain + hours: [8, 9, 8, 9, 8, 9, 8, 9] + out: 7 + - name: negative_prefix_recovery in: - hours: - - 9 - - 8 - - 8 - - 9 - - 9 - - 8 - - name: all_nontiring_small + hours: [8, 8, 8, 9, 9, 9, 9] + out: 7 + - name: positive_prefix_decay in: - hours: - - 1 - - 2 - - 3 - - 4 - - 5 - - name: all_tiring_small + hours: [9, 9, 9, 8, 8, 8, 9] + out: 7 + - name: isolated_tiring in: - hours: - - 9 - - 10 - - 11 - - 12 - - 13 - - name: late_long_interval + hours: [8, 8, 9, 8, 8] + out: 1 + - name: two_islands in: - hours: - - 9 - - 6 - - 6 - - 9 - - 6 - - 9 - - 9 - - name: early_long_interval + hours: [9, 9, 8, 8, 8, 9, 9, 9] + out: 8 + - name: values_do_not_matter in: - hours: - - 6 - - 9 - - 9 - - 6 - - 9 - - 6 - - 6 - - 9 - - name: one_tiring_in_four + hours: [0, 16, 1, 15, 8, 9] + out: 5 + - name: long_balanced in: - hours: - - 8 - - 8 - - 8 - - 9 - - name: tiring_then_three_boundaries + hours: [9, 9, 9, 8, 8, 8, 9, 8, 8, 9] + out: 7 + - name: all_boundary in: - hours: - - 9 - - 8 - - 8 - - 8 - - name: repeated_short_waves + hours: [8, 8, 8, 8, 8, 8, 8, 8, 8, 8] + out: 0 + - name: recovery_after_deep_loss in: - hours: - - 8 - - 9 - - 8 - - 8 - - 9 - - 8 - - 8 - - 9 - - name: strong_middle_run + hours: [8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9] + out: 13 + - name: maximum_even_balance in: - hours: - - 9 - - 9 - - 8 - - 8 - - 8 - - 9 - - 9 - - 9 - - name: mixed_tail + hours: [9, 8, 9, 8, 8, 9, 8, 9, 8, 9, 8, 9] + out: 7 + - name: mixed_extremes in: - hours: - - 6 - - 6 - - 6 - - 9 - - 9 - - 9 - - 6 - - 6 - - 9 - - name: alternating_start_tiring + hours: [16, 0, 16, 0, 0, 16, 8, 9, 1, 15] + out: 5 + - name: repeated_runs in: - hours: - - 9 - - 6 - - 9 - - 6 - - 9 - - 6 - - 9 - - 6 - - name: alternating_start_non_tiring + hours: [9, 9, 8, 8, 9, 9, 8, 8, 9, 9, 9, 8] + out: 12 + - name: short_final_gain in: - hours: - - 6 - - 9 - - 6 - - 9 - - 6 - - 9 - - 6 - - 9 - - name: mixed_block_one + hours: [8, 8, 8, 8, 9, 9, 9, 9, 9] + out: 9 + - name: one_tiring_among_low in: - hours: - - 9 - - 9 - - 6 - - 9 - - 6 - - 6 - - 9 - - 9 - - 6 - - 6 - - 9 - - name: mixed_block_two + hours: [0, 8, 9, 8, 0, 8] + out: 1 + - name: three_tiring_window in: - hours: - - 6 - - 6 - - 9 - - 6 - - 9 - - 9 - - 6 - - 6 - - 9 - - 9 - - 9 - - name: all_tiring_large + hours: [0, 9, 10, 8, 0, 0] + out: 3 + - name: long_prefix_wins + in: + hours: [9, 16, 8, 0, 9, 8, 9, 0, 8, 9, 9] + out: 11 + - name: single_late_tiring + in: + hours: [0, 0, 0, 0, 16] + out: 1 + - name: equal_runs + in: + hours: [9, 9, 9, 8, 8, 8] + out: 5 + - name: generated_small_mixed + seed: 11 in: hours: - gen: array - len: 10000 + gen: "array" + len: + gen: "int" + min: 1 + max: 25 of: - gen: int - min: 9 + gen: "int" + min: 0 max: 16 distinct: false sorted: false - elemType: int - - name: all_non_tiring_large + elemType: "int" + - name: generated_medium_boundary + seed: 22 in: hours: - gen: array + gen: "array" + len: + gen: "int" + min: 100 + max: 500 + of: + gen: "int" + min: 7 + max: 9 + distinct: false + sorted: false + elemType: "int" + - name: generated_large_all_non_tiring + seed: 33 + in: + hours: + gen: "array" len: 10000 of: - gen: int + gen: "int" min: 0 max: 8 distinct: false sorted: false - elemType: int - - name: all_boundary_large - in: - hours: - - 8 - - 8 - - 8 - - 8 - - 8 - - 8 - - 8 - - 8 - - 8 - - 8 - - 8 - - 8 - - 8 - - 8 - - 8 - - 8 - - 8 - - 8 - - 8 - - 8 - - 8 - - 8 - - 8 - - 8 - - 8 - - 8 - - 8 - - 8 - - 8 - - 8 - - name: tiring_then_non_tiring_blocks - in: - hours: - - 9 - - 9 - - 9 - - 9 - - 9 - - 6 - - 6 - - 6 - - 6 - - 6 - - 6 - - 6 - - 6 - - 6 - - 6 - - name: non_tiring_then_tiring_blocks + elemType: "int" + - name: generated_large_all_tiring + seed: 44 in: hours: - - 6 - - 6 - - 6 - - 6 - - 6 - - 9 - - 9 - - 9 - - 9 - - 9 - - 9 - - 9 - - 9 - - 9 - - 9 - - name: mixed_low_high + gen: "array" + len: 10000 + of: + gen: "int" + min: 9 + max: 16 + distinct: false + sorted: false + elemType: "int" + - name: generated_large_threshold_mix + seed: 55 in: hours: - - 6 - - 7 - - 8 - - 9 - - 10 - - 8 - - 7 - - 9 - - 9 - - 6 - - name: positive_prefix_then_noise + gen: "array" + len: 10000 + of: + gen: "int" + min: 7 + max: 9 + distinct: false + sorted: false + elemType: "int" + - name: generated_large_full_range + seed: 66 in: hours: - - 9 - - 9 - - 6 - - 6 - - 6 - - 6 - - 9 - - 6 - - 6 - - 6 + gen: "array" + len: 10000 + of: + gen: "int" + min: 0 + max: 16 + distinct: false + sorted: false + elemType: "int" diff --git a/tests/1001-1500/1124. longest-well-performing-interval/sol.cpp b/tests/1001-1500/1124. longest-well-performing-interval/sol.cpp index 714adad3..5ac97128 100644 --- a/tests/1001-1500/1124. longest-well-performing-interval/sol.cpp +++ b/tests/1001-1500/1124. longest-well-performing-interval/sol.cpp @@ -2,24 +2,24 @@ class Solution { public: int longestWPI(vector& hours) { int score = 0; - int longest_interval = 0; - unordered_map seen_at; - seen_at[0] = -1; + int longestInterval = 0; + unordered_map seenAt; + seenAt[0] = -1; for (int i = 0; i < hours.size(); i++) { score += hours[i] > 8 ? 1 : -1; if (score > 0) { - longest_interval = i + 1; - } else if (seen_at.count(score - 1)) { - longest_interval = max(longest_interval, i - seen_at[score - 1]); + longestInterval = i + 1; + } else if (seenAt.count(score - 1)) { + longestInterval = max(longestInterval, i - seenAt[score - 1]); } - if (!seen_at.count(score)) { - seen_at[score] = i; + if (!seenAt.count(score)) { + seenAt[score] = i; } } - return longest_interval; + return longestInterval; } }; diff --git a/tests/1001-1500/1124. longest-well-performing-interval/sol.cs b/tests/1001-1500/1124. longest-well-performing-interval/sol.cs index 24800813..393f7da6 100644 --- a/tests/1001-1500/1124. longest-well-performing-interval/sol.cs +++ b/tests/1001-1500/1124. longest-well-performing-interval/sol.cs @@ -2,7 +2,7 @@ public class Solution { public int LongestWPI(int[] hours) { int score = 0; int longestInterval = 0; - var seenAt = new Dictionary(); + Dictionary seenAt = new Dictionary(); seenAt[0] = -1; for (int i = 0; i < hours.Length; i++) { diff --git a/tests/1001-1500/1124. longest-well-performing-interval/sol.dart b/tests/1001-1500/1124. longest-well-performing-interval/sol.dart index 03c3c691..399799d9 100644 --- a/tests/1001-1500/1124. longest-well-performing-interval/sol.dart +++ b/tests/1001-1500/1124. longest-well-performing-interval/sol.dart @@ -10,7 +10,10 @@ class Solution { if (score > 0) { longestInterval = i + 1; } else if (seenAt.containsKey(score - 1)) { - longestInterval = max(longestInterval, i - seenAt[score - 1]!); + int candidate = i - seenAt[score - 1]!; + if (candidate > longestInterval) { + longestInterval = candidate; + } } if (!seenAt.containsKey(score)) { @@ -20,6 +23,4 @@ class Solution { return longestInterval; } - - int max(int a, int b) => a > b ? a : b; } diff --git a/tests/1001-1500/1124. longest-well-performing-interval/sol.go b/tests/1001-1500/1124. longest-well-performing-interval/sol.go index 5cdd578f..80a7ac56 100644 --- a/tests/1001-1500/1124. longest-well-performing-interval/sol.go +++ b/tests/1001-1500/1124. longest-well-performing-interval/sol.go @@ -12,9 +12,9 @@ func longestWPI(hours []int) int { if score > 0 { longestInterval = i + 1 - } else if val, ok := seenAt[score-1]; ok { - if i - val > longestInterval { - longestInterval = i - val + } else if idx, ok := seenAt[score-1]; ok { + if i - idx > longestInterval { + longestInterval = i - idx } } diff --git a/tests/1001-1500/1124. longest-well-performing-interval/sol.rb b/tests/1001-1500/1124. longest-well-performing-interval/sol.rb index 8e6e2842..496a3f96 100644 --- a/tests/1001-1500/1124. longest-well-performing-interval/sol.rb +++ b/tests/1001-1500/1124. longest-well-performing-interval/sol.rb @@ -14,9 +14,7 @@ def longest_wpi(hours) longest_interval = [longest_interval, i - seen_at[score - 1]].max end - unless seen_at.key?(score) - seen_at[score] = i - end + seen_at[score] = i unless seen_at.key?(score) end longest_interval diff --git a/tests/1001-1500/1124. longest-well-performing-interval/sol.rs b/tests/1001-1500/1124. longest-well-performing-interval/sol.rs index d71ed5d0..3493cab5 100644 --- a/tests/1001-1500/1124. longest-well-performing-interval/sol.rs +++ b/tests/1001-1500/1124. longest-well-performing-interval/sol.rs @@ -1,12 +1,12 @@ impl Solution { pub fn longest_wpi(hours: Vec) -> i32 { - let mut score: i32 = 0; - let mut longest_interval: i32 = 0; - let mut seen_at: std::collections::HashMap = std::collections::HashMap::new(); + let mut score = 0; + let mut longest_interval = 0; + let mut seen_at = std::collections::HashMap::new(); seen_at.insert(0, -1); - for (i, &h) in hours.iter().enumerate() { - score += if h > 8 { 1 } else { -1 }; + for i in 0..hours.len() { + score += if hours[i] > 8 { 1 } else { -1 }; if score > 0 { longest_interval = i as i32 + 1; diff --git a/tests/1001-1500/1124. longest-well-performing-interval/sol.swift b/tests/1001-1500/1124. longest-well-performing-interval/sol.swift index 2139697e..c4a27619 100644 --- a/tests/1001-1500/1124. longest-well-performing-interval/sol.swift +++ b/tests/1001-1500/1124. longest-well-performing-interval/sol.swift @@ -4,8 +4,8 @@ class Solution { var longestInterval = 0 var seenAt = [0: -1] - for (i, h) in hours.enumerated() { - score += h > 8 ? 1 : -1 + for i in 0.. 8 ? 1 : -1 if score > 0 { longestInterval = i + 1 diff --git a/tests/1001-1500/1125. smallest-sufficient-team/manifest.yaml b/tests/1001-1500/1125. smallest-sufficient-team/manifest.yaml index 81f48643..576242af 100644 --- a/tests/1001-1500/1125. smallest-sufficient-team/manifest.yaml +++ b/tests/1001-1500/1125. smallest-sufficient-team/manifest.yaml @@ -597,3 +597,254 @@ tests: - ["b"] - ["rare"] - ["a", "b", "rare"] + - name: max-people-late-four-block-team + in: + req_skills: + [ + "s0", + "s1", + "s2", + "s3", + "s4", + "s5", + "s6", + "s7", + "s8", + "s9", + "s10", + "s11", + "s12", + "s13", + "s14", + "s15", + ] + people: + elemType: "string" + value: + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - ["s0", "s1", "s2", "s3"] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - ["s4", "s5", "s6", "s7"] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - ["s8", "s9", "s10", "s11"] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - ["s12", "s13", "s14", "s15"] + - name: max-people-generalists-at-front + in: + req_skills: + [ + "s0", + "s1", + "s2", + "s3", + "s4", + "s5", + "s6", + "s7", + "s8", + "s9", + "s10", + "s11", + "s12", + "s13", + "s14", + "s15", + ] + people: + elemType: "string" + value: + - ["s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7"] + - ["s8", "s9", "s10", "s11", "s12", "s13", "s14", "s15"] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - name: max-people-singletons-and-noise + in: + req_skills: + [ + "s0", + "s1", + "s2", + "s3", + "s4", + "s5", + "s6", + "s7", + "s8", + "s9", + "s10", + "s11", + "s12", + "s13", + "s14", + "s15", + ] + people: + elemType: "string" + value: + - ["s0"] + - ["s1"] + - ["s2"] + - ["s3"] + - ["s4"] + - ["s5"] + - ["s6"] + - ["s7"] + - ["s8"] + - ["s9"] + - ["s10"] + - ["s11"] + - ["s12"] + - ["s13"] + - ["s14"] + - ["s15"] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] diff --git a/tests/1001-1500/1125. smallest-sufficient-team/sol.cpp b/tests/1001-1500/1125. smallest-sufficient-team/sol.cpp index ec632589..ef42ed26 100644 --- a/tests/1001-1500/1125. smallest-sufficient-team/sol.cpp +++ b/tests/1001-1500/1125. smallest-sufficient-team/sol.cpp @@ -1,45 +1,91 @@ -#include -using namespace std; - class Solution { +private: + unordered_set unmet_skills; + int smallest_length = INT_MAX; + vector current_team; + vector best_team; + vector req_skills; + vector> people_sets; + unordered_map> skills_to_people; + + void meet_skill(int skill) { + if (unmet_skills.empty()) { + if (smallest_length > current_team.size()) { + smallest_length = current_team.size(); + best_team = current_team; + } + return; + } + + if (skill >= req_skills.size() || unmet_skills.find(req_skills[skill]) == unmet_skills.end()) { + meet_skill(skill + 1); + return; + } + + auto& candidates = skills_to_people[req_skills[skill]]; + for (int i : candidates) { + unordered_set skills_added; + for (const auto& s : people_sets[i]) { + if (unmet_skills.count(s)) { + skills_added.insert(s); + } + } + + for (const auto& s : skills_added) { + unmet_skills.erase(s); + } + current_team.push_back(i); + + meet_skill(skill + 1); + + current_team.pop_back(); + for (const auto& s : skills_added) { + unmet_skills.insert(s); + } + } + } + public: vector smallestSufficientTeam(vector& req_skills, vector>& people) { - int n = (int)req_skills.size(); - int full = (1 << n) - 1; - unordered_map idx; - for (int i = 0; i < n; ++i) idx[req_skills[i]] = i; - - vector masks; - masks.reserve(people.size()); - for (auto& person : people) { - int mask = 0; - for (auto& skill : person) mask |= 1 << idx[skill]; - masks.push_back(mask); + this->req_skills = req_skills; + int n = people.size(); + people_sets.resize(n); + for (int i = 0; i < n; i++) { + for (const auto& s : people[i]) { + people_sets[i].insert(s); + } } - vector> dp(1 << n); - vector seen(1 << n, 0); - seen[0] = 1; - - for (int i = 0; i < (int)masks.size(); ++i) { - int pmask = masks[i]; - if (!pmask) continue; - auto cur = dp; - auto curSeen = seen; - for (int mask = 0; mask <= full; ++mask) { - if (!seen[mask]) continue; - int nmask = mask | pmask; - vector cand = dp[mask]; - cand.push_back(i); - if (!curSeen[nmask] || cand.size() < cur[nmask].size()) { - curSeen[nmask] = 1; - cur[nmask] = move(cand); + // Remove all skill sets that are subset of another skillset + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (i != j) { + bool is_subset = true; + for (const auto& s : people_sets[i]) { + if (people_sets[j].find(s) == people_sets[j].end()) { + is_subset = false; + break; + } + } + if (is_subset) { + people_sets[i].clear(); + } } } - dp.swap(cur); - seen.swap(curSeen); } - return dp[full]; + // Build dictionary of skills to the people who can perform them + for (int i = 0; i < n; i++) { + for (const auto& skill : people_sets[i]) { + skills_to_people[skill].insert(i); + } + } + + for (const auto& s : req_skills) { + unmet_skills.insert(s); + } + + meet_skill(0); + return best_team; } }; diff --git a/tests/1001-1500/1125. smallest-sufficient-team/sol.cs b/tests/1001-1500/1125. smallest-sufficient-team/sol.cs index cc620b53..4203677f 100644 --- a/tests/1001-1500/1125. smallest-sufficient-team/sol.cs +++ b/tests/1001-1500/1125. smallest-sufficient-team/sol.cs @@ -1,86 +1,74 @@ public class Solution { + private HashSet unmetSkills; + private int smallestLength = int.MaxValue; + private List currentTeam = new List(); + private List bestTeam = new List(); + private string[] reqSkills; + private List> peopleSets; + private Dictionary> skillsToPeople; + public int[] SmallestSufficientTeam(string[] req_skills, IList> people) { - int n = req_skills.Length; - int m = people.Count; - - Dictionary skillIdx = new Dictionary(); + reqSkills = req_skills; + int n = people.Count; + peopleSets = new List>(); for (int i = 0; i < n; i++) { - skillIdx[req_skills[i]] = i; + peopleSets.Add(new HashSet(people[i])); } - - int[] peopleMask = new int[m]; - for (int i = 0; i < m; i++) { - int mask = 0; - foreach (string skill in people[i]) { - mask |= 1 << skillIdx[skill]; - } - peopleMask[i] = mask; - } - - for (int i = 0; i < m; i++) { - for (int j = 0; j < m; j++) { - if (i != j && peopleMask[i] != 0 && (peopleMask[i] & peopleMask[j]) == peopleMask[i]) { - peopleMask[i] = 0; - break; + + // Remove all skill sets that are subset of another skillset + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (i != j && peopleSets[i].IsSubsetOf(peopleSets[j])) { + peopleSets[i] = new HashSet(); } } } - - List[] skillToPeople = new List[n]; + + // Build dictionary of skills to the people who can perform them + skillsToPeople = new Dictionary>(); for (int i = 0; i < n; i++) { - skillToPeople[i] = new List(); - } - for (int i = 0; i < m; i++) { - if (peopleMask[i] == 0) continue; - for (int bit = 0; bit < n; bit++) { - if ((peopleMask[i] & (1 << bit)) != 0) { - skillToPeople[bit].Add(i); + foreach (string skill in peopleSets[i]) { + if (!skillsToPeople.ContainsKey(skill)) { + skillsToPeople[skill] = new HashSet(); } + skillsToPeople[skill].Add(i); } } - - HashSet unmetSkills = new HashSet(req_skills); - int smallestLength = int.MaxValue; - List currentTeam = new List(); - List bestTeam = new List(); - - void Backtrack(int skill) { - if (unmetSkills.Count == 0) { - if (smallestLength > currentTeam.Count) { - smallestLength = currentTeam.Count; - bestTeam = new List(currentTeam); - } - return; - } - - if (skill >= n) return; - - if (!unmetSkills.Contains(req_skills[skill])) { - Backtrack(skill + 1); - return; - } - - foreach (int i in skillToPeople[skill]) { - int mask = peopleMask[i]; - List skillsAdded = new List(); - foreach (string s in unmetSkills) { - if ((mask & (1 << skillIdx[s])) != 0) { - skillsAdded.Add(s); - } - } - if (skillsAdded.Count == 0) continue; - - foreach (string s in skillsAdded) unmetSkills.Remove(s); - currentTeam.Add(i); - - Backtrack(skill + 1); - - currentTeam.RemoveAt(currentTeam.Count - 1); - foreach (string s in skillsAdded) unmetSkills.Add(s); + + unmetSkills = new HashSet(req_skills); + + MeetSkill(0); + + return bestTeam.ToArray(); + } + + private void MeetSkill(int skill) { + if (unmetSkills.Count == 0) { + if (smallestLength > currentTeam.Count) { + smallestLength = currentTeam.Count; + bestTeam = new List(currentTeam); } + return; + } + + if (skill >= reqSkills.Length || !unmetSkills.Contains(reqSkills[skill])) { + MeetSkill(skill + 1); + return; + } + + if (!skillsToPeople.ContainsKey(reqSkills[skill])) return; + + foreach (int i in skillsToPeople[reqSkills[skill]]) { + HashSet skillsAdded = new HashSet(peopleSets[i]); + skillsAdded.IntersectWith(unmetSkills); + + unmetSkills.ExceptWith(skillsAdded); + currentTeam.Add(i); + + MeetSkill(skill + 1); + + currentTeam.RemoveAt(currentTeam.Count - 1); + unmetSkills.UnionWith(skillsAdded); } - - Backtrack(0); - return bestTeam.ToArray(); } } diff --git a/tests/1001-1500/1125. smallest-sufficient-team/sol.dart b/tests/1001-1500/1125. smallest-sufficient-team/sol.dart index 140210eb..c85c9c2c 100644 --- a/tests/1001-1500/1125. smallest-sufficient-team/sol.dart +++ b/tests/1001-1500/1125. smallest-sufficient-team/sol.dart @@ -1,83 +1,36 @@ class Solution { - List smallestSufficientTeam(List req_skills, List> people) { - int n = req_skills.length; - int m = people.length; - - Map skillIdx = {}; - for (int i = 0; i < n; i++) { - skillIdx[req_skills[i]] = i; + List smallestSufficientTeam( + List req_skills, + List> people, + ) { + final skillIndex = {}; + for (var i = 0; i < req_skills.length; i++) { + skillIndex[req_skills[i]] = i; } - - List peopleMask = List.filled(m, 0); - for (int i = 0; i < m; i++) { - int mask = 0; - for (String skill in people[i]) { - mask |= (1 << skillIdx[skill]!); + + final personMasks = []; + for (final skills in people) { + var mask = 0; + for (final skill in skills) { + final index = skillIndex[skill]; + if (index != null) mask |= 1 << index; } - peopleMask[i] = mask; + personMasks.add(mask); } - - for (int i = 0; i < m; i++) { - for (int j = 0; j < m; j++) { - if (i != j && peopleMask[i] != 0 && (peopleMask[i] & peopleMask[j]) == peopleMask[i]) { - peopleMask[i] = 0; - break; + + final best = >{0: []}; + for (var person = 0; person < personMasks.length; person++) { + final current = Map>.from(best); + for (final entry in current.entries) { + final combined = entry.key | personMasks[person]; + if (combined == entry.key) continue; + final candidate = [...entry.value, person]; + final existing = best[combined]; + if (existing == null || candidate.length < existing.length) { + best[combined] = candidate; } } } - - List> skillToPeople = List.generate(n, (_) => []); - for (int i = 0; i < m; i++) { - if (peopleMask[i] == 0) continue; - for (int bit = 0; bit < n; bit++) { - if ((peopleMask[i] & (1 << bit)) != 0) { - skillToPeople[bit].add(i); - } - } - } - - Set unmetSkills = req_skills.toSet(); - int smallestLength = 1 << 60; - List currentTeam = []; - List bestTeam = []; - - void backtrack(int skill) { - if (unmetSkills.isEmpty) { - if (smallestLength > currentTeam.length) { - smallestLength = currentTeam.length; - bestTeam = List.from(currentTeam); - } - return; - } - - if (skill >= n) return; - - if (!unmetSkills.contains(req_skills[skill])) { - backtrack(skill + 1); - return; - } - - for (int i in skillToPeople[skill]) { - int mask = peopleMask[i]; - Set skillsAdded = {}; - for (String s in unmetSkills) { - if ((mask & (1 << skillIdx[s]!)) != 0) { - skillsAdded.add(s); - } - } - if (skillsAdded.isEmpty) continue; - - unmetSkills.removeAll(skillsAdded); - currentTeam.add(i); - - backtrack(skill + 1); - - currentTeam.removeLast(); - unmetSkills.addAll(skillsAdded); - } - } - - backtrack(0); - return bestTeam; + return best[(1 << req_skills.length) - 1]!; } } diff --git a/tests/1001-1500/1125. smallest-sufficient-team/sol.go b/tests/1001-1500/1125. smallest-sufficient-team/sol.go index 05ae44e6..20201d75 100644 --- a/tests/1001-1500/1125. smallest-sufficient-team/sol.go +++ b/tests/1001-1500/1125. smallest-sufficient-team/sol.go @@ -1,99 +1,90 @@ func smallestSufficientTeam(req_skills []string, people [][]string) []int { - n := len(req_skills) - m := len(people) - - skillIdx := make(map[string]int) - for i, skill := range req_skills { - skillIdx[skill] = i - } - - peopleMask := make([]int, m) + n := len(people) + peopleSets := make([]map[string]bool, n) for i, skills := range people { - mask := 0 - for _, skill := range skills { - mask |= 1 << skillIdx[skill] + peopleSets[i] = make(map[string]bool) + for _, s := range skills { + peopleSets[i][s] = true } - peopleMask[i] = mask } - - for i := 0; i < m; i++ { - for j := 0; j < m; j++ { - if i != j && peopleMask[i] != 0 && (peopleMask[i] & peopleMask[j]) == peopleMask[i] { - peopleMask[i] = 0 - break + + // Remove all skill sets that are subset of another skillset + for i := 0; i < n; i++ { + for j := 0; j < n; j++ { + if i != j { + subset := true + for s := range peopleSets[i] { + if !peopleSets[j][s] { + subset = false + break + } + } + if subset { + peopleSets[i] = make(map[string]bool) + } } } } - - skillToPeople := make([][]int, n) - for i := 0; i < n; i++ { - skillToPeople[i] = []int{} - } - for i := 0; i < m; i++ { - if peopleMask[i] == 0 { - continue - } - for bit := 0; bit < n; bit++ { - if (peopleMask[i] & (1 << bit)) != 0 { - skillToPeople[bit] = append(skillToPeople[bit], i) + + // Build dictionary of skills to the people who can perform them + skillsToPeople := make(map[string]map[int]bool) + for i, skills := range peopleSets { + for s := range skills { + if skillsToPeople[s] == nil { + skillsToPeople[s] = make(map[int]bool) } + skillsToPeople[s][i] = true } } - + unmetSkills := make(map[string]bool) - for _, skill := range req_skills { - unmetSkills[skill] = true + for _, s := range req_skills { + unmetSkills[s] = true } - - smallestLength := int(^uint(0) >> 1) - var currentTeam []int - var bestTeam []int - - var backtrack func(skill int) - backtrack = func(skill int) { + + smallestLength := int(^uint(0) >> 1) // max int + currentTeam := []int{} + bestTeam := []int{} + + var meetSkill func(int) + meetSkill = func(skill int) { if len(unmetSkills) == 0 { if smallestLength > len(currentTeam) { smallestLength = len(currentTeam) - bestTeam = append([]int{}, currentTeam...) + bestTeam = make([]int, len(currentTeam)) + copy(bestTeam, currentTeam) } return } - - if skill >= n { + + if skill >= len(req_skills) || !unmetSkills[req_skills[skill]] { + meetSkill(skill + 1) return } - - if !unmetSkills[req_skills[skill]] { - backtrack(skill + 1) - return - } - - for _, i := range skillToPeople[skill] { - mask := peopleMask[i] - skillsAdded := []string{} - for s := range unmetSkills { - if (mask & (1 << skillIdx[s])) != 0 { - skillsAdded = append(skillsAdded, s) + + candidates := skillsToPeople[req_skills[skill]] + for i := range candidates { + skillsAdded := make(map[string]bool) + for s := range peopleSets[i] { + if unmetSkills[s] { + skillsAdded[s] = true } } - if len(skillsAdded) == 0 { - continue - } - - for _, s := range skillsAdded { + + for s := range skillsAdded { delete(unmetSkills, s) } currentTeam = append(currentTeam, i) - - backtrack(skill + 1) - + + meetSkill(skill + 1) + currentTeam = currentTeam[:len(currentTeam)-1] - for _, s := range skillsAdded { + for s := range skillsAdded { unmetSkills[s] = true } } } - - backtrack(0) + + meetSkill(0) return bestTeam } diff --git a/tests/1001-1500/1125. smallest-sufficient-team/sol.java b/tests/1001-1500/1125. smallest-sufficient-team/sol.java index 6ec4a07b..74b5ecb5 100644 --- a/tests/1001-1500/1125. smallest-sufficient-team/sol.java +++ b/tests/1001-1500/1125. smallest-sufficient-team/sol.java @@ -1,42 +1,80 @@ -import java.util.*; - class Solution { + private Set unmet_skills; + private int smallest_length = Integer.MAX_VALUE; + private List current_team = new ArrayList<>(); + private List best_team = new ArrayList<>(); + private String[] req_skills; + private List> people_sets; + private Map> skills_to_people; + public int[] smallestSufficientTeam(String[] req_skills, List> people) { - int n = req_skills.length; - int full = (1 << n) - 1; - Map idx = new HashMap<>(); - for (int i = 0; i < n; i++) idx.put(req_skills[i], i); - - int[] masks = new int[people.size()]; - for (int i = 0; i < people.size(); i++) { - int mask = 0; - for (String skill : people.get(i)) mask |= 1 << idx.get(skill); - masks[i] = mask; - } - - @SuppressWarnings("unchecked") - ArrayList[] dp = new ArrayList[1 << n]; - dp[0] = new ArrayList<>(); - - for (int i = 0; i < masks.length; i++) { - int pmask = masks[i]; - if (pmask == 0) continue; - ArrayList[] next = Arrays.copyOf(dp, dp.length); - for (int mask = 0; mask <= full; mask++) { - if (dp[mask] == null) continue; - int nmask = mask | pmask; - ArrayList cand = new ArrayList<>(dp[mask]); - cand.add(i); - if (next[nmask] == null || cand.size() < next[nmask].size()) { - next[nmask] = cand; + this.req_skills = req_skills; + int n = people.size(); + people_sets = new ArrayList<>(); + for (int i = 0; i < n; i++) { + people_sets.add(new HashSet<>(people.get(i))); + } + + // Remove all skill sets that are subset of another skillset + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (i != j && people_sets.get(j).containsAll(people_sets.get(i))) { + people_sets.set(i, new HashSet<>()); } } - dp = next; } - ArrayList ans = dp[full]; - int[] res = new int[ans.size()]; - for (int i = 0; i < ans.size(); i++) res[i] = ans.get(i); - return res; + // Build dictionary of skills to the people who can perform them + skills_to_people = new HashMap<>(); + for (int i = 0; i < n; i++) { + for (String skill : people_sets.get(i)) { + skills_to_people.computeIfAbsent(skill, k -> new HashSet<>()).add(i); + } + } + + unmet_skills = new HashSet<>(); + for (String skill : req_skills) { + unmet_skills.add(skill); + } + + meet_skill(0); + + int[] result = new int[best_team.size()]; + for (int i = 0; i < best_team.size(); i++) { + result[i] = best_team.get(i); + } + return result; + } + + private void meet_skill(int skill) { + if (unmet_skills.isEmpty()) { + if (smallest_length > current_team.size()) { + smallest_length = current_team.size(); + best_team = new ArrayList<>(current_team); + } + return; + } + + if (skill >= req_skills.length || !unmet_skills.contains(req_skills[skill])) { + meet_skill(skill + 1); + return; + } + + Set candidates = skills_to_people.get(req_skills[skill]); + if (candidates == null) return; + + for (int i : candidates) { + Set person_skills = people_sets.get(i); + Set skills_added = new HashSet<>(person_skills); + skills_added.retainAll(unmet_skills); + + unmet_skills.removeAll(skills_added); + current_team.add(i); + + meet_skill(skill + 1); + + current_team.remove(current_team.size() - 1); + unmet_skills.addAll(skills_added); + } } } diff --git a/tests/1001-1500/1125. smallest-sufficient-team/sol.kt b/tests/1001-1500/1125. smallest-sufficient-team/sol.kt index d8a38560..5b1868e0 100644 --- a/tests/1001-1500/1125. smallest-sufficient-team/sol.kt +++ b/tests/1001-1500/1125. smallest-sufficient-team/sol.kt @@ -1,34 +1,19 @@ class Solution { fun smallestSufficientTeam(req_skills: Array, people: List>): IntArray { - val n = req_skills.size - val full = (1 shl n) - 1 - val idx = HashMap() - for (i in req_skills.indices) idx[req_skills[i]] = i - - val masks = IntArray(people.size) - for (i in people.indices) { + val index = req_skills.withIndex().associate { it.value to it.index } + val best = mutableMapOf(0 to IntArray(0)) + for ((person, skills) in people.withIndex()) { var mask = 0 - for (skill in people[i]) mask = mask or (1 shl idx[skill]!!) - masks[i] = mask - } - - var dp = arrayOfNulls(1 shl n) - dp[0] = IntArray(0) - - for (i in masks.indices) { - val pmask = masks[i] - if (pmask == 0) continue - val next = dp.copyOf() - for (mask in 0..full) { - val team = dp[mask] ?: continue - val nmask = mask or pmask - val cand = team + i - val old = next[nmask] - if (old == null || cand.size < old.size) next[nmask] = cand + for (skill in skills) index[skill]?.let { mask = mask or (1 shl it) } + for ((oldMask, team) in best.toMap()) { + val newMask = oldMask or mask + if (newMask == oldMask) continue + val candidate = team + person + if (best[newMask] == null || candidate.size < best[newMask]!!.size) { + best[newMask] = candidate + } } - dp = next } - - return dp[full]!! + return best[(1 shl req_skills.size) - 1]!! } } diff --git a/tests/1001-1500/1125. smallest-sufficient-team/sol.py b/tests/1001-1500/1125. smallest-sufficient-team/sol.py index 6bd515fb..dfd389ee 100644 --- a/tests/1001-1500/1125. smallest-sufficient-team/sol.py +++ b/tests/1001-1500/1125. smallest-sufficient-team/sol.py @@ -1,6 +1,6 @@ -from typing import List import collections import math +from typing import List class Solution: diff --git a/tests/1001-1500/1125. smallest-sufficient-team/sol.py2 b/tests/1001-1500/1125. smallest-sufficient-team/sol.py2 index c9e72ccc..92359400 100644 --- a/tests/1001-1500/1125. smallest-sufficient-team/sol.py2 +++ b/tests/1001-1500/1125. smallest-sufficient-team/sol.py2 @@ -5,43 +5,30 @@ class Solution(object): :type people: List[List[str]] :rtype: List[int] """ - n = len(req_skills) - m = len(people) - # map skill to index - skill_idx = {skill: i for i, skill in enumerate(req_skills)} + import collections + import math - # convert each person's skills to a bitmask - people_mask = [] - for p in people: - mask = 0 - for skill in p: - mask |= (1 << skill_idx[skill]) - people_mask.append(mask) + # Convert all sublists into sets + for i, skills in enumerate(people): + people[i] = set(skills) - # remove people whose skills are subset of another (still track original index) - for i in range(m): - for j in range(m): - if i != j and people_mask[i] and (people_mask[i] & people_mask[j]) == people_mask[i]: - people_mask[i] = 0 - break + # Remove all skill sets that are subset of another skillset + for i, i_skills in enumerate(people): + for j, j_skills in enumerate(people): + if i != j and i_skills.issubset(j_skills): + people[i] = set() - # map skill bit to people who have it (only if person not removed) - skill_to_people = {i: [] for i in range(n)} - for i, mask in enumerate(people_mask): - if mask == 0: - continue - for skill_idx_val, bit in enumerate(range(n)): - if mask & (1 << bit): - skill_to_people[skill_idx_val].append(i) + # Build dictionary of skills to the people who can perform them + skills_to_people = collections.defaultdict(set) + for i, skills in enumerate(people): + for skill in skills: + skills_to_people[skill].add(i) + people[i] = set(skills) self.unmet_skills = set(req_skills) self.smallest_length = float('inf') self.current_team = [] self.best_team = [] - self.req_skills = req_skills - self.skills_to_people = skill_to_people - self.people_mask = people_mask - self.skill_idx = skill_idx def meet_skill(skill=0): if not self.unmet_skills: @@ -50,29 +37,19 @@ class Solution(object): self.best_team = self.current_team[:] return - if skill >= len(self.req_skills): - return - - if self.req_skills[skill] not in self.unmet_skills: + if req_skills[skill] not in self.unmet_skills: meet_skill(skill + 1) return - for i in self.skills_to_people[skill]: - mask = self.people_mask[i] - skills_added = set() - for s in list(self.unmet_skills): - if mask & (1 << self.skill_idx[s]): - skills_added.add(s) - if not skills_added: - continue - - self.unmet_skills -= skills_added + for i in skills_to_people[req_skills[skill]]: + skills_added_by_person = people[i].intersection(self.unmet_skills) + self.unmet_skills = self.unmet_skills - skills_added_by_person self.current_team.append(i) meet_skill(skill + 1) self.current_team.pop() - self.unmet_skills |= skills_added + self.unmet_skills = self.unmet_skills.union(skills_added_by_person) meet_skill() return self.best_team diff --git a/tests/1001-1500/1125. smallest-sufficient-team/sol.rb b/tests/1001-1500/1125. smallest-sufficient-team/sol.rb index d7982d2a..2519e7be 100644 --- a/tests/1001-1500/1125. smallest-sufficient-team/sol.rb +++ b/tests/1001-1500/1125. smallest-sufficient-team/sol.rb @@ -2,34 +2,59 @@ # @param {String[][]} people # @return {Integer[]} def smallest_sufficient_team(req_skills, people) - n = req_skills.size - full = (1 << n) - 1 - idx = {} - req_skills.each_with_index { |skill, i| idx[skill] = i } - - masks = people.map do |skills| - mask = 0 - skills.each { |skill| mask |= (1 << idx[skill]) } - mask - end - - dp = Array.new(1 << n) - dp[0] = [] - - masks.each_with_index do |pmask, i| - next if pmask == 0 - nxt = dp.dup - (0..full).each do |mask| - team = dp[mask] - next if team.nil? - nmask = mask | pmask - cand = team + [i] - if nxt[nmask].nil? || cand.length < nxt[nmask].length - nxt[nmask] = cand - end + # Convert all sublists into sets + people.each_with_index do |skills, i| + people[i] = skills.to_set end - dp = nxt - end - dp[full] || [] + # Remove all skill sets that are subset of another skillset + people.each_with_index do |i_skills, i| + people.each_with_index do |j_skills, j| + if i != j && i_skills.subset?(j_skills) + people[i] = Set.new + end + end + end + + # Build dictionary of skills to the people who can perform them + skills_to_people = Hash.new { |h, k| h[k] = Set.new } + people.each_with_index do |skills, i| + skills.each do |skill| + skills_to_people[skill].add(i) + end + end + + @unmet_skills = req_skills.to_set + @smallest_length = Float::INFINITY + @current_team = [] + @best_team = [] + + define_method(:meet_skill) do |skill = 0| + if @unmet_skills.empty? + if @smallest_length > @current_team.length + @smallest_length = @current_team.length + @best_team = @current_team.dup + end + return + end + + if !@unmet_skills.include?(req_skills[skill]) + meet_skill(skill + 1) + return + end + + skills_to_people[req_skills[skill]].each do |i| + skills_added_by_person = people[i].intersection(@unmet_skills) + @unmet_skills = @unmet_skills - skills_added_by_person + @current_team.push(i) + + meet_skill(skill + 1) + + @current_team.pop + @unmet_skills = @unmet_skills.union(skills_added_by_person) + end + end + + meet_skill() + @best_team.to_a end diff --git a/tests/1001-1500/1125. smallest-sufficient-team/sol.rs b/tests/1001-1500/1125. smallest-sufficient-team/sol.rs index 53a07539..beb065af 100644 --- a/tests/1001-1500/1125. smallest-sufficient-team/sol.rs +++ b/tests/1001-1500/1125. smallest-sufficient-team/sol.rs @@ -1,103 +1,29 @@ +use std::collections::HashMap; + impl Solution { pub fn smallest_sufficient_team(req_skills: Vec, people: Vec>) -> Vec { - let n = req_skills.len(); - let m = people.len(); - - let mut skill_idx = std::collections::HashMap::new(); + let mut index = HashMap::new(); for (i, skill) in req_skills.iter().enumerate() { - skill_idx.insert(skill.clone(), i); + index.insert(skill.as_str(), i); } - - let mut people_mask = vec![0i32; m]; - for (i, skills) in people.iter().enumerate() { - let mut mask = 0; + let mut best: HashMap> = HashMap::new(); + best.insert(0, Vec::new()); + for (person, skills) in people.iter().enumerate() { + let mut mask = 0u32; for skill in skills { - mask |= 1 << skill_idx[skill]; - } - people_mask[i] = mask; - } - - for i in 0..m { - for j in 0..m { - if i != j && people_mask[i] != 0 && (people_mask[i] & people_mask[j]) == people_mask[i] { - people_mask[i] = 0; - break; - } - } - } - - let mut skill_to_people = vec![vec![]; n]; - for i in 0..m { - if people_mask[i] == 0 { - continue; - } - for bit in 0..n { - if (people_mask[i] & (1 << bit)) != 0 { - skill_to_people[bit].push(i); - } - } - } - - let mut unmet_skills: std::collections::HashSet = req_skills.iter().cloned().collect(); - let mut smallest_length = i32::MAX; - let mut current_team = vec![]; - let mut best_team = vec![]; - - fn backtrack( - skill: usize, - req_skills: &Vec, - people_mask: &Vec, - skill_to_people: &Vec>, - skill_idx: &std::collections::HashMap, - unmet_skills: &mut std::collections::HashSet, - smallest_length: &mut i32, - current_team: &mut Vec, - best_team: &mut Vec, - ) { - if unmet_skills.is_empty() { - if *smallest_length > current_team.len() as i32 { - *smallest_length = current_team.len() as i32; - *best_team = current_team.clone(); - } - return; - } - - if skill >= req_skills.len() { - return; - } - - if !unmet_skills.contains(&req_skills[skill]) { - backtrack(skill + 1, req_skills, people_mask, skill_to_people, skill_idx, unmet_skills, smallest_length, current_team, best_team); - return; - } - - for &i in &skill_to_people[skill] { - let mask = people_mask[i]; - let mut skills_added = vec![]; - for s in unmet_skills.iter() { - if (mask & (1 << skill_idx[s])) != 0 { - skills_added.push(s.clone()); - } - } - if skills_added.is_empty() { - continue; - } - - for s in &skills_added { - unmet_skills.remove(s); - } - current_team.push(i as i32); - - backtrack(skill + 1, req_skills, people_mask, skill_to_people, skill_idx, unmet_skills, smallest_length, current_team, best_team); - - current_team.pop(); - for s in skills_added { - unmet_skills.insert(s); + if let Some(&i) = index.get(skill.as_str()) { mask |= 1 << i; } + } + let snapshot: Vec<(u32, Vec)> = best.iter().map(|(&m, team)| (m, team.clone())).collect(); + for (old_mask, team) in snapshot { + let new_mask = old_mask | mask; + if new_mask == old_mask { continue; } + let mut candidate = team; + candidate.push(person as i32); + if best.get(&new_mask).map_or(true, |old| candidate.len() < old.len()) { + best.insert(new_mask, candidate); } } } - - backtrack(0, &req_skills, &people_mask, &skill_to_people, &skill_idx, &mut unmet_skills, &mut smallest_length, &mut current_team, &mut best_team); - best_team + best.remove(&((1u32 << req_skills.len()) - 1)).unwrap() } } diff --git a/tests/1001-1500/1125. smallest-sufficient-team/sol.swift b/tests/1001-1500/1125. smallest-sufficient-team/sol.swift index 4adc1045..f14338c6 100644 --- a/tests/1001-1500/1125. smallest-sufficient-team/sol.swift +++ b/tests/1001-1500/1125. smallest-sufficient-team/sol.swift @@ -1,34 +1,64 @@ class Solution { + private var unmetSkills: Set = [] + private var smallestLength = Int.max + private var currentTeam: [Int] = [] + private var bestTeam: [Int] = [] + private var reqSkills: [String] = [] + private var peopleSets: [Set] = [] + private var skillsToPeople: [String: Set] = [:] + func smallestSufficientTeam(_ req_skills: [String], _ people: [[String]]) -> [Int] { - let n = req_skills.count - let full = (1 << n) - 1 - var idx: [String: Int] = [:] - for (i, skill) in req_skills.enumerated() { idx[skill] = i } - - let masks = people.map { skills -> Int in - var mask = 0 - for skill in skills { mask |= 1 << idx[skill]! } - return mask + self.reqSkills = req_skills + let n = people.count + peopleSets = people.map { Set($0) } + + // Remove all skill sets that are subset of another skillset + for i in 0..(repeating: nil, count: 1 << n) - dp[0] = [] - - for (i, pmask) in masks.enumerated() { - if pmask == 0 { continue } - var next = dp - for mask in 0...full { - guard let team = dp[mask] else { continue } - let nmask = mask | pmask - var cand = team - cand.append(i) - if next[nmask] == nil || cand.count < next[nmask]!.count { - next[nmask] = cand + // Build dictionary of skills to the people who can perform them + for i in 0.. currentTeam.count { + smallestLength = currentTeam.count + bestTeam = currentTeam } + return + } + + if skill >= reqSkills.count || !unmetSkills.contains(reqSkills[skill]) { + meetSkill(skill + 1) + return + } + + guard let candidates = skillsToPeople[reqSkills[skill]] else { return } + + for i in candidates { + let skillsAdded = peopleSets[i].intersection(unmetSkills) + unmetSkills.subtract(skillsAdded) + currentTeam.append(i) + + meetSkill(skill + 1) + + currentTeam.removeLast() + unmetSkills.formUnion(skillsAdded) } - dp = next } - return dp[full] ?? [] + meetSkill() + return bestTeam } } diff --git a/tests/1001-1500/1125. smallest-sufficient-team/sol.ts b/tests/1001-1500/1125. smallest-sufficient-team/sol.ts index 145b56db..96e9c1ee 100644 --- a/tests/1001-1500/1125. smallest-sufficient-team/sol.ts +++ b/tests/1001-1500/1125. smallest-sufficient-team/sol.ts @@ -2,50 +2,44 @@ function smallestSufficientTeam( req_skills: string[], people: string[][], ): number[] { - const n = req_skills.length; - const m = people.length; + const n = people.length; + let peopleSets: Set[] = people.map((p) => new Set(p)); - const skillIdx: Map = new Map(); - req_skills.forEach((skill, i) => skillIdx.set(skill, i)); - - const peopleMask: number[] = new Array(m).fill(0); - for (let i = 0; i < m; i++) { - let mask = 0; - for (const skill of people[i]) { - mask |= 1 << skillIdx.get(skill)!; - } - peopleMask[i] = mask; - } - - for (let i = 0; i < m; i++) { - for (let j = 0; j < m; j++) { - if ( - i !== j && - peopleMask[i] !== 0 && - (peopleMask[i] & peopleMask[j]) === peopleMask[i] - ) { - peopleMask[i] = 0; - break; + // Remove all skill sets that are subset of another skillset + for (let i = 0; i < n; i++) { + for (let j = 0; j < n; j++) { + if (i !== j) { + let isSubset = true; + for (const s of peopleSets[i]) { + if (!peopleSets[j].has(s)) { + isSubset = false; + break; + } + } + if (isSubset) { + peopleSets[i] = new Set(); + } } } } - const skillToPeople: number[][] = Array.from({ length: n }, () => []); - for (let i = 0; i < m; i++) { - if (peopleMask[i] === 0) continue; - for (let bit = 0; bit < n; bit++) { - if ((peopleMask[i] & (1 << bit)) !== 0) { - skillToPeople[bit].push(i); + // Build dictionary of skills to the people who can perform them + const skillsToPeople: Map> = new Map(); + for (let i = 0; i < n; i++) { + for (const skill of peopleSets[i]) { + if (!skillsToPeople.has(skill)) { + skillsToPeople.set(skill, new Set()); } + skillsToPeople.get(skill)!.add(i); } } - const unmetSkills: Set = new Set(req_skills); - let smallestLength = Infinity; + let unmetSkills: Set = new Set(req_skills); + let smallestLength: number = Infinity; let currentTeam: number[] = []; let bestTeam: number[] = []; - function backtrack(skill: number): void { + function meetSkill(skill: number = 0): void { if (unmetSkills.size === 0) { if (smallestLength > currentTeam.length) { smallestLength = currentTeam.length; @@ -54,33 +48,36 @@ function smallestSufficientTeam( return; } - if (skill >= n) return; - - if (!unmetSkills.has(req_skills[skill])) { - backtrack(skill + 1); + if (skill >= req_skills.length || !unmetSkills.has(req_skills[skill])) { + meetSkill(skill + 1); return; } - for (const i of skillToPeople[skill]) { - const mask = peopleMask[i]; - const skillsAdded: string[] = []; - for (const s of unmetSkills) { - if ((mask & (1 << skillIdx.get(s)!)) !== 0) { - skillsAdded.push(s); + const candidates = skillsToPeople.get(req_skills[skill]); + if (!candidates) return; + + for (const i of candidates) { + const skillsAdded = new Set(); + for (const s of peopleSets[i]) { + if (unmetSkills.has(s)) { + skillsAdded.add(s); } } - if (skillsAdded.length === 0) continue; - skillsAdded.forEach((s) => unmetSkills.delete(s)); + for (const s of skillsAdded) { + unmetSkills.delete(s); + } currentTeam.push(i); - backtrack(skill + 1); + meetSkill(skill + 1); currentTeam.pop(); - skillsAdded.forEach((s) => unmetSkills.add(s)); + for (const s of skillsAdded) { + unmetSkills.add(s); + } } } - backtrack(0); + meetSkill(); return bestTeam; } diff --git a/tests/1001-1500/1128. number-of-equivalent-domino-pairs/manifest.yaml b/tests/1001-1500/1128. number-of-equivalent-domino-pairs/manifest.yaml index 1217b1bf..ddd26021 100644 --- a/tests/1001-1500/1128. number-of-equivalent-domino-pairs/manifest.yaml +++ b/tests/1001-1500/1128. number-of-equivalent-domino-pairs/manifest.yaml @@ -1,6 +1,6 @@ entry: id: 1128 - title: number-of-equivalent-domino-pairs + title: "number-of-equivalent-domino-pairs" params: dominoes: type: array @@ -21,36 +21,35 @@ entry: dart: "Solution().numEquivDominoPairs({dominoes})" swift: "Solution().numEquivDominoPairs({dominoes})" typescript: "numEquivDominoPairs({dominoes})" + judge: - type: exact + type: "exact" + limits: - time_ms: 1000 - memory_mb: 256 + time_ms: 500 + memory_mb: 300 + oracle: python3: call: "Checker().numEquivDominoPairs(dominoes, {result})" checker: | class Checker: def numEquivDominoPairs(self, dominoes, result): - if not isinstance(result, int): + if not isinstance(result, int) or isinstance(result, bool) or result < 0: return False - count = 0 - seen = [0] * 100 + counts = {} + expected = 0 for pair in dominoes: - if not isinstance(pair, list) or len(pair) != 2: - return False - a, b = pair - if not isinstance(a, int) or not isinstance(b, int): - return False - if a < 1 or a > 9 or b < 1 or b > 9: - return False - key = a * 10 + b if a <= b else b * 10 + a - count += seen[key] - seen[key] += 1 - return result == count + key = tuple(sorted(pair)) + previous = counts.get(key, 0) + expected += previous + counts[key] = previous + 1 + return result == expected + seed: 1128 + tests: - - name: ex1 + - name: "example_one" in: dominoes: - [1, 2] @@ -58,7 +57,7 @@ tests: - [3, 4] - [5, 6] out: 1 - - name: ex2 + - name: "example_two" in: dominoes: - [1, 2] @@ -67,203 +66,262 @@ tests: - [1, 2] - [2, 2] out: 3 - - name: single_domino + - name: "single_domino" + in: + dominoes: [[1, 9]] + out: 0 + - name: "all_distinct" in: dominoes: - - [1, 1] + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [1, 6] out: 0 - - name: two_identical + - name: "reversed_pairs" in: dominoes: - - [1, 1] - - [1, 1] - out: 1 - - name: two_reversed + - [9, 1] + - [1, 9] + - [9, 1] + - [2, 8] + - [8, 2] + out: 4 + - name: "double_one_one" in: dominoes: - - [2, 3] - - [3, 2] + - [1, 1] + - [1, 1] out: 1 - - name: three_same + - name: "double_nine_nine" in: dominoes: - - [4, 5] - - [5, 4] - - [4, 5] + - [9, 9] + - [9, 9] + - [9, 9] out: 3 - - name: no_pairs + - name: "three_same_orientation" in: dominoes: - - [1, 2] - - [3, 4] - - [5, 6] - out: 0 - - name: all_same_four + - [4, 7] + - [4, 7] + - [4, 7] + out: 3 + - name: "three_mixed_orientation" in: dominoes: - - [7, 8] - - [8, 7] - - [7, 8] - - [8, 7] - out: 6 - - name: mixed_multiples + - [7, 4] + - [4, 7] + - [7, 4] + out: 3 + - name: "two_groups" in: dominoes: - [1, 2] - [2, 1] - - [1, 2] - [3, 3] - [3, 3] - - [3, 3] - out: 6 - - name: pair_and_single - in: - dominoes: - - [9, 1] - - [1, 9] - - [1, 1] - out: 1 - - name: cross_two_groups - in: - dominoes: - - [1, 3] - - [3, 1] - - [2, 4] - - [4, 2] out: 2 - - name: boundary_nine + - name: "interleaved_groups" in: dominoes: - - [9, 9] - - [9, 1] - - [1, 9] - - [9, 9] - out: 2 - - name: alternating_two_groups + - [1, 2] + - [3, 4] + - [2, 1] + - [4, 3] + - [1, 2] + out: 4 + - name: "one_each_small" in: dominoes: - - [1, 4] - - [4, 1] - - [1, 4] - - [4, 1] - - [2, 2] + - [1, 1] + - [1, 2] - [2, 2] - out: 7 - - name: mixed_triples + - [2, 3] + - [3, 3] + - [3, 4] + out: 0 + - name: "four_same" + in: + dominoes: + - [5, 6] + - [6, 5] + - [5, 6] + - [6, 5] + out: 6 + - name: "five_same" in: dominoes: - [2, 5] - [5, 2] + - [2, 5] - [5, 2] - - [6, 6] - - [6, 6] - - [1, 7] - out: 4 - - name: all_unique_ordered + - [2, 5] + out: 10 + - name: "three_groups_of_two" + in: + dominoes: + - [1, 8] + - [8, 1] + - [2, 7] + - [7, 2] + - [3, 6] + - [6, 3] + out: 3 + - name: "same_endpoint_different_other" in: dominoes: + - [1, 1] - [1, 2] - [1, 3] - [1, 4] - [1, 5] - [1, 6] - [1, 7] + - [1, 8] + - [1, 9] out: 0 - - name: all_unique_reversed + - name: "all_nine_types" in: dominoes: - - [2, 1] - - [3, 1] - - [4, 1] - - [5, 1] - - [6, 1] - - [7, 1] + - [9, 1] + - [9, 2] + - [9, 3] + - [9, 4] + - [9, 5] + - [9, 6] + - [9, 7] + - [9, 8] + - [9, 9] out: 0 - - name: cluster_one + - name: "two_each_three_types" in: dominoes: - - [3, 8] - - [8, 3] - - [3, 8] - - [3, 8] - - [2, 9] - - [9, 2] - out: 7 - - name: cluster_two + - [1, 9] + - [9, 1] + - [2, 8] + - [8, 2] + - [3, 7] + - [7, 3] + out: 3 + - name: "late_match" in: dominoes: + - [1, 2] + - [3, 4] + - [5, 6] + - [7, 8] + - [9, 9] + - [2, 1] + out: 1 + - name: "four_doubles" + in: + dominoes: + - [1, 1] + - [2, 2] + - [3, 3] - [4, 4] + - [1, 1] + - [2, 2] + - [3, 3] - [4, 4] - - [4, 4] - - [4, 4] - - [5, 6] - - [6, 5] - out: 7 - - name: symmetric_mix + out: 4 + - name: "six_same" in: dominoes: - - [1, 8] - - [8, 1] - - [2, 7] - - [7, 2] - - [3, 6] - - [6, 3] - out: 3 - - name: repeated_fives + - [9, 4] + - [4, 9] + - [9, 4] + - [4, 9] + - [9, 4] + - [4, 9] + out: 15 + - name: "ten_same" in: dominoes: + - [6, 8] + - [8, 6] + - [6, 8] + - [8, 6] + - [6, 8] + - [8, 6] + - [6, 8] + - [8, 6] + - [6, 8] + - [8, 6] + out: 45 + - name: "mixed_counts" + in: + dominoes: + - [1, 2] + - [2, 1] + - [2, 1] + - [3, 4] + - [4, 3] - [5, 5] - [5, 5] - [5, 5] - - [5, 5] - - [5, 5] - out: 10 - - name: repeated_nines + - [6, 7] + out: 7 + - name: "max_values_mixed" in: dominoes: - [9, 9] + - [9, 8] + - [8, 9] - [9, 9] - - [9, 9] - - [9, 9] - out: 6 - - name: ascending_chain + - [1, 9] + - [9, 1] + out: 3 + - name: "ten_distinct_types" in: dominoes: + - [1, 1] - [1, 2] - - [2, 3] - - [3, 4] - - [4, 5] - - [5, 6] - - [6, 7] + - [1, 3] + - [1, 4] + - [1, 5] + - [1, 6] + - [1, 7] + - [1, 8] + - [1, 9] + - [2, 2] out: 0 - - name: descending_chain + - name: "two_large_groups" in: dominoes: - - [2, 1] - - [3, 2] - - [4, 3] - - [5, 4] - - [6, 5] - - [7, 6] - out: 0 - - name: one_pair_one_noise + - [1, 9] + - [9, 1] + - [1, 9] + - [2, 8] + - [8, 2] + - [2, 8] + - [2, 8] + out: 9 + - name: "pair_after_many_nonmatches" in: dominoes: - - [2, 9] - - [9, 2] - - [2, 3] - - [4, 5] + - [1, 3] + - [2, 4] + - [3, 5] + - [4, 6] + - [5, 7] + - [6, 8] + - [7, 9] + - [3, 1] out: 1 - - name: two_pairs_separate + - name: "three_double_types" in: dominoes: - - [1, 6] - - [6, 1] - - [2, 7] - - [7, 2] - - [8, 9] - out: 2 - - name: three_pairs_separate + - [2, 2] + - [2, 2] + - [4, 4] + - [4, 4] + - [8, 8] + - [8, 8] + out: 3 + - name: "four_reversed_pairs" in: dominoes: - [1, 9] @@ -272,116 +330,244 @@ tests: - [8, 2] - [3, 7] - [7, 3] - out: 3 - - name: four_pair_groups + - [4, 6] + - [6, 4] + out: 4 + - name: "nine_identical" + in: + dominoes: + - [5, 5] + - [5, 5] + - [5, 5] + - [5, 5] + - [5, 5] + - [5, 5] + - [5, 5] + - [5, 5] + - [5, 5] + out: 36 + - name: "all_canonical_domino_types_once" in: dominoes: + - [1, 1] + - [1, 2] + - [1, 3] - [1, 4] - - [4, 1] + - [1, 5] + - [1, 6] + - [1, 7] + - [1, 8] + - [1, 9] + - [2, 2] + - [2, 3] + - [2, 4] - [2, 5] - - [5, 2] + - [2, 6] + - [2, 7] + - [2, 8] + - [2, 9] + - [3, 3] + - [3, 4] + - [3, 5] - [3, 6] - - [6, 3] - - [7, 7] + - [3, 7] + - [3, 8] + - [3, 9] + - [4, 4] + - [4, 5] + - [4, 6] + - [4, 7] + - [4, 8] + - [4, 9] + - [5, 5] + - [5, 6] + - [5, 7] + - [5, 8] + - [5, 9] + - [6, 6] + - [6, 7] + - [6, 8] + - [6, 9] - [7, 7] - out: 4 - - name: all_same_pair_value + - [7, 8] + - [7, 9] + - [8, 8] + - [8, 9] + - [9, 9] + out: 0 + - name: "all_canonical_types_once_reversed" in: dominoes: + - [1, 1] + - [2, 1] + - [3, 1] + - [4, 1] + - [5, 1] + - [6, 1] + - [7, 1] + - [8, 1] + - [9, 1] + - [2, 2] + - [3, 2] + - [4, 2] + - [5, 2] + - [6, 2] + - [7, 2] - [8, 2] - - [2, 8] - - [8, 2] - - [2, 8] - - [8, 2] - out: 10 - - name: mixed_with_double + - [9, 2] + - [3, 3] + - [4, 3] + - [5, 3] + - [6, 3] + - [7, 3] + - [8, 3] + - [9, 3] + - [4, 4] + - [5, 4] + - [6, 4] + - [7, 4] + - [8, 4] + - [9, 4] + - [5, 5] + - [6, 5] + - [7, 5] + - [8, 5] + - [9, 5] + - [6, 6] + - [7, 6] + - [8, 6] + - [9, 6] + - [7, 7] + - [8, 7] + - [9, 7] + - [8, 8] + - [9, 8] + - [9, 9] + out: 0 + - name: "uneven_group_frequencies" in: dominoes: - - [1, 1] - - [1, 1] - [1, 2] - [2, 1] - - [3, 3] - - [3, 3] - out: 3 - - name: many_twos_and_threes + - [1, 2] + - [2, 1] + - [3, 4] + - [4, 3] + - [3, 4] + - [5, 5] + - [5, 5] + - [6, 9] + - [9, 6] + - [8, 8] + out: 11 + - name: "reversed_pairs_separated_by_doubles" in: dominoes: - - [2, 3] - - [3, 2] - - [2, 3] - - [3, 2] - - [2, 3] + - [1, 9] + - [2, 2] + - [3, 3] + - [9, 1] - [4, 4] + - [2, 2] + - [1, 9] + - [3, 3] + - [9, 1] - [4, 4] - out: 11 - - name: generated_small_a + out: 9 + - name: "fifteen_identical_mixed_orientation" in: dominoes: - gen: array - len: 24 + - [2, 7] + - [7, 2] + - [2, 7] + - [7, 2] + - [2, 7] + - [7, 2] + - [2, 7] + - [7, 2] + - [2, 7] + - [7, 2] + - [2, 7] + - [7, 2] + - [2, 7] + - [7, 2] + - [2, 7] + out: 105 + - name: "generator_large_5000" + seed: 11 + in: + dominoes: + gen: "array" + len: 5000 + elemType: "int" of: - gen: array + gen: "array" len: 2 + elemType: "int" of: - gen: int + gen: "int" min: 1 max: 9 - elemType: int - elemType: int - - name: generated_small_b + - name: "generator_large_10000" + seed: 22 in: dominoes: - gen: array - len: 37 + gen: "array" + len: 10000 + elemType: "int" of: - gen: array + gen: "array" len: 2 + elemType: "int" of: - gen: int + gen: "int" min: 1 max: 9 - elemType: int - elemType: int - - name: generated_large_a + - name: "generator_large_20000" + seed: 33 in: dominoes: - gen: array - len: 40000 + gen: "array" + len: 20000 + elemType: "int" of: - gen: array + gen: "array" len: 2 + elemType: "int" of: - gen: int + gen: "int" min: 1 max: 9 - elemType: int - elemType: int - - name: generated_large_b + - name: "generator_large_30000" + seed: 44 in: dominoes: - gen: array - len: 39999 + gen: "array" + len: 30000 + elemType: "int" of: - gen: array + gen: "array" len: 2 + elemType: "int" of: - gen: int + gen: "int" min: 1 max: 9 - elemType: int - elemType: int - - name: generated_large_c + - name: "generator_maximum_40000" + seed: 55 in: dominoes: - gen: array - len: 20000 + gen: "array" + len: + gen: "int" + min: 40000 + max: 40000 + elemType: "int" of: - gen: array + gen: "array" len: 2 + elemType: "int" of: - gen: int + gen: "int" min: 1 max: 9 - elemType: int - elemType: int diff --git a/tests/1001-1500/1128. number-of-equivalent-domino-pairs/sol.dart b/tests/1001-1500/1128. number-of-equivalent-domino-pairs/sol.dart index bf70f20f..72453eca 100644 --- a/tests/1001-1500/1128. number-of-equivalent-domino-pairs/sol.dart +++ b/tests/1001-1500/1128. number-of-equivalent-domino-pairs/sol.dart @@ -1,6 +1,6 @@ class Solution { int numEquivDominoPairs(List> dominoes) { - var mpp = List.filled(100, 0); + List mpp = List.filled(100, 0); int count = 0; for (var d in dominoes) { int a = d[0], b = d[1]; diff --git a/tests/1001-1500/1128. number-of-equivalent-domino-pairs/sol.py2 b/tests/1001-1500/1128. number-of-equivalent-domino-pairs/sol.py2 index 7f4930a6..04d5b067 100644 --- a/tests/1001-1500/1128. number-of-equivalent-domino-pairs/sol.py2 +++ b/tests/1001-1500/1128. number-of-equivalent-domino-pairs/sol.py2 @@ -1,9 +1,5 @@ class Solution(object): def numEquivDominoPairs(self, dominoes): - """ - :type dominoes: List[List[int]] - :rtype: int - """ mpp = [0] * 100 count = 0 for a, b in dominoes: diff --git a/tests/1001-1500/1128. number-of-equivalent-domino-pairs/sol.swift b/tests/1001-1500/1128. number-of-equivalent-domino-pairs/sol.swift index c1755fad..344946df 100644 --- a/tests/1001-1500/1128. number-of-equivalent-domino-pairs/sol.swift +++ b/tests/1001-1500/1128. number-of-equivalent-domino-pairs/sol.swift @@ -1,6 +1,6 @@ class Solution { func numEquivDominoPairs(_ dominoes: [[Int]]) -> Int { - var mpp = Array(repeating: 0, count: 100) + var mpp = [Int](repeating: 0, count: 100) var count = 0 for d in dominoes { let a = d[0], b = d[1] diff --git a/tests/1001-1500/1128. number-of-equivalent-domino-pairs/sol.ts b/tests/1001-1500/1128. number-of-equivalent-domino-pairs/sol.ts index 841a4dc5..9f0b157c 100644 --- a/tests/1001-1500/1128. number-of-equivalent-domino-pairs/sol.ts +++ b/tests/1001-1500/1128. number-of-equivalent-domino-pairs/sol.ts @@ -1,5 +1,5 @@ function numEquivDominoPairs(dominoes: number[][]): number { - const mpp = new Array(100).fill(0); + const mpp: number[] = new Array(100).fill(0); let count = 0; for (const [a, b] of dominoes) { const key = a <= b ? a * 10 + b : b * 10 + a; diff --git a/tests/1001-1500/1129. shortest-path-with-alternating-colors/manifest.yaml b/tests/1001-1500/1129. shortest-path-with-alternating-colors/manifest.yaml index 1345e90c..1a5331f2 100644 --- a/tests/1001-1500/1129. shortest-path-with-alternating-colors/manifest.yaml +++ b/tests/1001-1500/1129. shortest-path-with-alternating-colors/manifest.yaml @@ -1,6 +1,6 @@ entry: id: 1129 - title: shortest-path-with-alternating-colors + title: "shortest-path-with-alternating-colors" params: n: type: int @@ -17,657 +17,486 @@ entry: items: type: int call: - cpp: Solution().shortestAlternatingPaths({n}, {redEdges}, {blueEdges}) - rust: Solution::shortest_alternating_paths({n}, {redEdges}, {blueEdges}) - python3: Solution().shortestAlternatingPaths({n}, {redEdges}, {blueEdges}) - python2: Solution().shortestAlternatingPaths({n}, {redEdges}, {blueEdges}) - ruby: shortest_alternating_paths({n}, {redEdges}, {blueEdges}) - java: new Solution().shortestAlternatingPaths({n}, {redEdges}, {blueEdges}) - csharp: new Solution().ShortestAlternatingPaths({n}, {redEdges}, {blueEdges}) - kotlin: Solution().shortestAlternatingPaths({n}, {redEdges}, {blueEdges}) - go: shortestAlternatingPaths({n}, {redEdges}, {blueEdges}) - dart: Solution().shortestAlternatingPaths({n}, {redEdges}, {blueEdges}) - swift: Solution().shortestAlternatingPaths({n}, {redEdges}, {blueEdges}) - typescript: shortestAlternatingPaths({n}, {redEdges}, {blueEdges}) + cpp: "Solution().shortestAlternatingPaths({n}, {redEdges}, {blueEdges})" + rust: "Solution::shortest_alternating_paths({n}, {redEdges}, {blueEdges})" + python3: "Solution().shortestAlternatingPaths({n}, {redEdges}, {blueEdges})" + python2: "Solution().shortestAlternatingPaths({n}, {redEdges}, {blueEdges})" + ruby: "shortest_alternating_paths({n}, {redEdges}, {blueEdges})" + java: "new Solution().shortestAlternatingPaths({n}, {redEdges}, {blueEdges})" + csharp: "new Solution().ShortestAlternatingPaths({n}, {redEdges}, {blueEdges})" + kotlin: "Solution().shortestAlternatingPaths({n}, {redEdges}, {blueEdges})" + go: "shortestAlternatingPaths({n}, {redEdges}, {blueEdges})" + dart: "Solution().shortestAlternatingPaths({n}, {redEdges}, {blueEdges})" + swift: "Solution().shortestAlternatingPaths({n}, {redEdges}, {blueEdges})" + typescript: "shortestAlternatingPaths({n}, {redEdges}, {blueEdges})" judge: type: exact limits: - time_ms: 1500 - memory_mb: 256 + time_ms: 500 + memory_mb: 300 oracle: python3: - call: Checker().shortestAlternatingPaths(n, redEdges, blueEdges, {result}) - checker: - "import collections\nclass Checker:\n def shortestAlternatingPaths(self,\ - \ n, redEdges, blueEdges, result):\n if not isinstance(result, list)\ - \ or len(result) != n:\n return False\n RED, BLUE = 0, 1\n\ - \ graph = [[[] for _ in range(n)] for _ in range(2)]\n for u,\ - \ v in redEdges:\n graph[RED][u].append(v)\n for u, v in blueEdges:\n\ - \ graph[BLUE][u].append(v)\n dist = [[-1] * n for _ in range(2)]\n\ - \ q = collections.deque([(0, RED), (0, BLUE)])\n dist[RED][0]\ - \ = 0\n dist[BLUE][0] = 0\n while q:\n node, last =\ - \ q.popleft()\n nxt = 1 - last\n for nei in graph[nxt][node]:\n\ - \ if dist[nxt][nei] == -1:\n dist[nxt][nei]\ - \ = dist[last][node] + 1\n q.append((nei, nxt))\n \ - \ expected = []\n for i in range(n):\n a, b = dist[RED][i],\ - \ dist[BLUE][i]\n if a == -1 or (b != -1 and b < a):\n \ - \ expected.append(b)\n else:\n expected.append(a)\n\ - \ return result == expected\n" + call: "Checker().shortestAlternatingPaths(n, redEdges, blueEdges, {result})" + checker: | + from collections import deque + class Checker: + def shortestAlternatingPaths(self, n, redEdges, blueEdges, result): + if not isinstance(result, list) or len(result) != n: + return False + graph = [[] for _ in range(n)] + for u, v in redEdges: + graph[u].append((v, 0)) + for u, v in blueEdges: + graph[u].append((v, 1)) + dist = [[-1, -1] for _ in range(n)] + q = deque([(0, 0), (0, 1)]) + dist[0] = [0, 0] + while q: + u, previous = q.popleft() + for v, color in graph[u]: + if color != previous and dist[v][color] == -1: + dist[v][color] = dist[u][previous] + 1 + q.append((v, color)) + expected = [0 if i == 0 else (min(x for x in dist[i] if x >= 0) if any(x >= 0 for x in dist[i]) else -1) for i in range(n)] + return result == expected seed: 1129 tests: - - name: ex1 + - name: official_one in: n: 3 redEdges: - elemType: int - value: - - - 0 - - 1 - - - 1 - - 2 - blueEdges: - elemType: int - value: [] - - name: ex2 + - [0, 1] + - [1, 2] + blueEdges: [] + out: [0, 1, -1] + - name: official_two in: n: 3 redEdges: - elemType: int - value: - - - 0 - - 1 + - [0, 1] blueEdges: - elemType: int - value: - - - 2 - - 1 - - name: ex3 + - [2, 1] + out: [0, 1, -1] + - name: one_node_empty in: - n: 3 + n: 1 + redEdges: [] + blueEdges: [] + out: [0] + - name: one_node_loops + in: + n: 1 redEdges: - elemType: int - value: - - - 1 - - 0 + - [0, 0] blueEdges: - elemType: int - value: - - - 2 - - 1 - - name: ex4 + - [0, 0] + out: [0] + - name: red_then_blue in: n: 3 redEdges: - elemType: int - value: - - - 0 - - 1 + - [0, 1] blueEdges: - elemType: int - value: - - - 1 - - 2 - - name: single + - [1, 2] + out: [0, 1, 2] + - name: blue_then_red in: - n: 1 + n: 3 redEdges: - elemType: int - value: [] + - [1, 2] blueEdges: - elemType: int - value: [] - - name: two_red + - [0, 1] + out: [0, 1, 2] + - name: same_color_blocked in: - n: 2 + n: 4 redEdges: - elemType: int - value: - - - 0 - - 1 - blueEdges: - elemType: int - value: [] - - name: two_blue + - [0, 1] + - [1, 2] + - [2, 3] + blueEdges: [] + out: [0, 1, -1, -1] + - name: unreachable_islands in: - n: 2 + n: 5 redEdges: - elemType: int - value: [] + - [2, 3] blueEdges: - elemType: int - value: - - - 0 - - 1 - - name: parallel_both + - [3, 4] + out: [0, -1, -1, -1, -1] + - name: direct_both_colors in: n: 2 redEdges: - elemType: int - value: - - - 0 - - 1 + - [0, 1] blueEdges: - elemType: int - value: - - - 0 - - 1 - - name: cycle_small + - [0, 1] + out: [0, 1] + - name: parallel_edges in: n: 3 redEdges: - elemType: int - value: - - - 0 - - 1 - - - 1 - - 2 + - [0, 1] + - [0, 1] blueEdges: - elemType: int - value: - - - 2 - - 0 - - name: alt_cycle - in: - n: 4 - redEdges: - elemType: int - value: - - - 0 - - 1 - - - 2 - - 3 - blueEdges: - elemType: int - value: - - - 1 - - 2 - - - 3 - - 0 - - name: unreachable + - [1, 2] + - [1, 2] + out: [0, 1, 2] + - name: self_loop_then_edge in: - n: 4 + n: 3 redEdges: - elemType: int - value: - - - 1 - - 2 + - [0, 0] + - [0, 1] blueEdges: - elemType: int - value: - - - 2 - - 3 - - name: red_chain + - [1, 2] + out: [0, 1, 2] + - name: self_loop_wrong_color in: - n: 5 + n: 3 redEdges: - elemType: int - value: - - - 0 - - 1 - - - 1 - - 2 - - - 2 - - 3 - - - 3 - - 4 - blueEdges: - elemType: int - value: [] - - name: blue_chain + - [0, 0] + - [0, 1] + - [1, 2] + blueEdges: [] + out: [0, 1, -1] + - name: longer_alternating_route in: - n: 5 + n: 6 redEdges: - elemType: int - value: [] - blueEdges: - elemType: int - value: - - - 0 - - 1 - - - 1 - - 2 - - - 2 - - 3 - - - 3 - - 4 - - name: perfect_alt + - [0, 1] + - [2, 3] + - [4, 5] + blueEdges: + - [1, 2] + - [3, 4] + out: [0, 1, 2, 3, 4, 5] + - name: shortcut_beats_route in: n: 5 redEdges: - elemType: int - value: - - - 0 - - 1 - - - 2 - - 3 - blueEdges: - elemType: int - value: - - - 1 - - 2 - - - 3 - - 4 - - name: branch_red + - [0, 1] + - [1, 4] + - [0, 3] + blueEdges: + - [1, 2] + - [3, 4] + out: [0, 1, 2, 1, 2] + - name: alternating_cycle in: - n: 5 + n: 4 redEdges: - elemType: int - value: - - - 0 - - 1 - - - 0 - - 2 - - - 2 - - 3 - blueEdges: - elemType: int - value: - - - 1 - - 3 - - - 3 - - 4 - - name: branch_blue + - [0, 1] + - [2, 3] + blueEdges: + - [1, 2] + - [3, 0] + out: [0, 1, 2, 3] + - name: reverse_edges_irrelevant in: - n: 5 + n: 4 redEdges: - elemType: int - value: - - - 1 - - 3 - - - 3 - - 4 - blueEdges: - elemType: int - value: - - - 0 - - 1 - - - 0 - - 2 - - - 2 - - 3 - - name: self_loops + - [1, 0] + - [2, 1] + blueEdges: + - [3, 2] + out: [0, -1, -1, -1] + - name: dense_small in: - n: 3 + n: 5 redEdges: - elemType: int - value: - - - 0 - - 0 - - - 0 - - 1 - blueEdges: - elemType: int - value: - - - 1 - - 1 - - - 1 - - 2 - - name: double_edges + - [0, 1] + - [0, 2] + - [1, 3] + - [2, 3] + - [3, 4] + - [4, 0] + blueEdges: + - [0, 3] + - [1, 2] + - [2, 4] + - [3, 0] + - [4, 1] + out: [0, 1, 1, 1, 2] + - name: empty_edges_many_nodes + in: + n: 10 + redEdges: [] + blueEdges: [] + out: [0, -1, -1, -1, -1, -1, -1, -1, -1, -1] + - name: red_chain_with_blue_links in: - n: 4 + n: 8 redEdges: - elemType: int - value: - - - 0 - - 1 - - - 0 - - 1 - - - 2 - - 3 - blueEdges: - elemType: int - value: - - - 1 - - 2 - - - 1 - - 2 - - name: cross_edges + - [0, 1] + - [2, 3] + - [4, 5] + - [6, 7] + blueEdges: + - [1, 2] + - [3, 4] + - [5, 6] + out: [0, 1, 2, 3, 4, 5, 6, 7] + - name: alternate_to_dead_end in: n: 4 redEdges: - elemType: int - value: - - - 0 - - 2 - - - 1 - - 3 - blueEdges: - elemType: int - value: - - - 0 - - 1 - - - 2 - - 3 - - name: back_edges + - [0, 1] + - [2, 3] + blueEdges: + - [1, 0] + - [1, 2] + out: [0, 1, 2, 3] + - name: duplicate_opposite_routes in: n: 4 redEdges: - elemType: int - value: - - - 0 - - 1 - - - 2 - - 1 - blueEdges: - elemType: int - value: - - - 1 - - 2 - - - 1 - - 3 - - name: dense_4 + - [0, 1] + - [0, 2] + - [1, 3] + blueEdges: + - [0, 2] + - [2, 3] + out: [0, 1, 1, 2] + - name: competing_first_colors in: - n: 4 + n: 5 redEdges: - elemType: int - value: - - - 0 - - 1 - - - 0 - - 2 - - - 1 - - 2 - - - 2 - - 3 - blueEdges: - elemType: int - value: - - - 0 - - 3 - - - 1 - - 3 - - - 2 - - 1 - - name: sparse_6 + - [0, 1] + - [2, 4] + blueEdges: + - [0, 2] + - [1, 3] + - [3, 4] + out: [0, 1, 1, 2, 2] + - name: revisiting_node_in_other_color_state in: - n: 6 + n: 5 redEdges: - elemType: int - value: - - - 0 - - 1 - - - 4 - - 5 - blueEdges: - elemType: int - value: - - - 1 - - 2 - - - 2 - - 3 - - name: reach_last_only + - [0, 1] + - [2, 3] + - [1, 4] + blueEdges: + - [1, 2] + - [3, 1] + out: [0, 1, 2, 3, 5] + - name: color_choice_changes_reachability in: n: 6 redEdges: - elemType: int - value: - - - 0 - - 2 - - - 2 - - 4 + - [0, 1] + - [1, 3] + - [2, 3] + - [4, 5] blueEdges: - elemType: int - value: - - - 4 - - 5 - - name: all_colors_needed + - [0, 2] + - [3, 4] + out: [0, 1, 1, 2, 3, 4] + - name: mixed_loops_and_parallel_cycle in: - n: 6 + n: 4 redEdges: - elemType: int - value: - - - 0 - - 1 - - - 2 - - 3 - - - 4 - - 5 - blueEdges: - elemType: int - value: - - - 1 - - 2 - - - 3 - - 4 - - name: many_options + - [0, 1] + - [0, 1] + - [1, 1] + - [2, 3] + blueEdges: + - [1, 2] + - [2, 2] + - [3, 0] + out: [0, 1, 2, 3] + - name: generated_sparse + seed: 1201 + in: + n: 100 + redEdges: + gen: array + len: 80 + of: + gen: array + len: 2 + of: + gen: int + min: 0 + max: 99 + blueEdges: + gen: array + len: 80 + of: + gen: array + len: 2 + of: + gen: int + min: 0 + max: 99 + - name: two_nodes_no_edges in: - n: 6 - redEdges: - elemType: int - value: - - - 0 - - 1 - - - 0 - - 3 - - - 2 - - 5 - - - 4 - - 5 - blueEdges: - elemType: int - value: - - - 1 - - 2 - - - 3 - - 4 - - - 1 - - 4 - - name: diamond + n: 2 + redEdges: [] + blueEdges: [] + out: [0, -1] + - name: red_blue_red in: - n: 5 + n: 4 redEdges: - elemType: int - value: - - - 0 - - 1 - - - 0 - - 2 - - - 3 - - 4 - blueEdges: - elemType: int - value: - - - 1 - - 3 - - - 2 - - 3 - - name: zigzag - in: - n: 7 - redEdges: - elemType: int - value: - - - 0 - - 1 - - - 2 - - 3 - - - 4 - - 5 - blueEdges: - elemType: int - value: - - - 1 - - 2 - - - 3 - - 4 - - - 5 - - 6 - - name: mixed_shortcuts - in: - n: 7 - redEdges: - elemType: int - value: - - - 0 - - 2 - - - 2 - - 4 - - - 1 - - 3 - blueEdges: - elemType: int - value: - - - 0 - - 1 - - - 1 - - 5 - - - 5 - - 6 - - - 4 - - 6 - - name: isolated_zero_only + - [0, 1] + - [2, 3] + blueEdges: + - [1, 2] + out: [0, 1, 2, 3] + - name: blue_red_blue in: - n: 5 + n: 4 redEdges: - elemType: int - value: - - - 1 - - 2 - - - 2 - - 3 + - [1, 2] blueEdges: - elemType: int - value: - - - 3 - - 4 - - name: return_edge + - [0, 1] + - [2, 3] + out: [0, 1, 2, 3] + - name: revisit_with_other_state in: - n: 5 + n: 3 redEdges: - elemType: int - value: - - - 0 - - 1 - - - 2 - - 1 - blueEdges: - elemType: int - value: - - - 1 - - 2 - - - 1 - - 0 - - name: two_components + - [0, 1] + - [1, 0] + blueEdges: + - [1, 0] + - [0, 2] + out: [0, 1, 1] + - name: unreachable_after_same_color in: - n: 8 + n: 5 redEdges: - elemType: int - value: - - - 0 - - 1 - - - 1 - - 2 - - - 5 - - 6 - blueEdges: - elemType: int - value: - - - 2 - - 3 - - - 6 - - 7 - - name: alt_needed_long + - [0, 1] + - [1, 2] + blueEdges: + - [0, 3] + - [3, 4] + out: [0, 1, -1, 1, -1] + - name: endpoint_n_minus_one in: - n: 8 + n: 6 redEdges: - elemType: int - value: - - - 0 - - 1 - - - 2 - - 3 - - - 4 - - 5 - - - 6 - - 7 - blueEdges: - elemType: int - value: - - - 1 - - 2 - - - 3 - - 4 - - - 5 - - 6 - - name: blue_start_better + - [0, 5] + blueEdges: [] + out: [0, -1, -1, -1, -1, 1] + - name: parallel_mixed_colors in: - n: 5 + n: 3 redEdges: - elemType: int - value: - - - 1 - - 2 - - - 2 - - 4 - blueEdges: - elemType: int - value: - - - 0 - - 1 - - - 1 - - 3 - - - 3 - - 4 - - name: red_start_better + - [0, 1] + - [1, 2] + blueEdges: + - [0, 1] + - [1, 2] + out: [0, 1, 2] + - name: loop_can_switch_color in: - n: 5 + n: 2 redEdges: - elemType: int - value: - - - 0 - - 1 - - - 1 - - 3 - - - 3 - - 4 - blueEdges: - elemType: int - value: - - - 1 - - 2 - - - 2 - - 4 - - name: duplicate_mix + - [0, 0] + - [0, 1] + blueEdges: + - [0, 0] + out: [0, 1] + - name: alternate_shortcut in: n: 5 redEdges: - elemType: int - value: - - - 0 - - 1 - - - 0 - - 1 - - - 2 - - 3 - - - 2 - - 3 - blueEdges: - elemType: int - value: - - - 1 - - 2 - - - 1 - - 2 - - - 3 - - 4 - - name: self_and_path + - [0, 1] + - [1, 4] + - [2, 3] + blueEdges: + - [0, 2] + - [2, 4] + out: [0, 1, 1, 2, -1] + - name: all_edges_to_source in: n: 5 redEdges: - elemType: int - value: - - - 0 - - 0 - - - 0 - - 1 - - - 2 - - 2 - blueEdges: - elemType: int - value: - - - 1 - - 2 - - - 2 - - 3 - - - 3 - - 4 + - [1, 0] + - [2, 0] + - [3, 0] + - [4, 0] + blueEdges: + - [1, 0] + - [2, 0] + out: [0, -1, -1, -1, -1] + - name: generated_medium + seed: 1202 + in: + n: 100 + redEdges: + gen: array + len: 250 + of: + gen: array + len: 2 + of: + gen: int + min: 0 + max: 99 + blueEdges: + gen: array + len: 250 + of: + gen: array + len: 2 + of: + gen: int + min: 0 + max: 99 + - name: generated_dense + seed: 1203 + in: + n: 100 + redEdges: + gen: array + len: 400 + of: + gen: array + len: 2 + of: + gen: int + min: 0 + max: 99 + blueEdges: + gen: array + len: 400 + of: + gen: array + len: 2 + of: + gen: int + min: 0 + max: 99 + - name: generated_red_only + seed: 1204 + in: + n: 100 + redEdges: + gen: array + len: 400 + of: + gen: array + len: 2 + of: + gen: int + min: 0 + max: 99 + blueEdges: [] + - name: blue_only_chain + in: + n: 10 + redEdges: [] + blueEdges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + out: [0, 1, -1, -1, -1, -1, -1, -1, -1, -1] diff --git a/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.cpp b/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.cpp index 900b0010..945c0529 100644 --- a/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.cpp +++ b/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.cpp @@ -2,17 +2,18 @@ class Solution { public: vector shortestAlternatingPaths(int n, vector>& redEdges, vector>& blueEdges) { vector ans(n, -1); - vector>> graph(n); // (v, color): 1-red, 2-blue - queue> q; // (node, prevColor): 0-init, 1-red, 2-blue - q.push({0, 0}); + vector>> graph(n); // (to, color): 1=red, 2=blue - for (auto& edge : redEdges) { - graph[edge[0]].push_back({edge[1], 1}); + for (auto& e : redEdges) { + graph[e[0]].push_back({e[1], 1}); } - for (auto& edge : blueEdges) { - graph[edge[0]].push_back({edge[1], 2}); + for (auto& e : blueEdges) { + graph[e[0]].push_back({e[1], 2}); } + queue> q; // (node, prevColor): 0=init + q.push({0, 0}); + int step = 0; while (!q.empty()) { int size = q.size(); @@ -22,7 +23,8 @@ class Solution { if (ans[u] == -1) { ans[u] = step; } - for (auto& [v, edgeColor] : graph[u]) { + for (int j = 0; j < graph[u].size(); j++) { + auto& [v, edgeColor] = graph[u][j]; if (v == -1 || edgeColor == prevColor) continue; q.push({v, edgeColor}); v = -1; diff --git a/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.cs b/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.cs index b26be082..f527987e 100644 --- a/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.cs +++ b/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.cs @@ -8,15 +8,15 @@ public int[] ShortestAlternatingPaths(int n, int[][] redEdges, int[][] blueEdges graph[i] = new List<(int, int)>(); } - foreach (var edge in redEdges) { - graph[edge[0]].Add((edge[1], 1)); // 1-red + foreach (var e in redEdges) { + graph[e[0]].Add((e[1], 1)); // 1 = red } - foreach (var edge in blueEdges) { - graph[edge[0]].Add((edge[1], 2)); // 2-blue + foreach (var e in blueEdges) { + graph[e[0]].Add((e[1], 2)); // 2 = blue } - Queue<(int, int)> q = new Queue<(int, int)>(); - q.Enqueue((0, 0)); // (node, prevColor): 0-init, 1-red, 2-blue + Queue<(int, int)> q = new Queue<(int, int)>(); // (node, prevColor): 0=init + q.Enqueue((0, 0)); int step = 0; while (q.Count > 0) { @@ -26,12 +26,11 @@ public int[] ShortestAlternatingPaths(int n, int[][] redEdges, int[][] blueEdges if (ans[u] == -1) { ans[u] = step; } - var neighbors = graph[u]; - for (int j = 0; j < neighbors.Count; j++) { - var (v, edgeColor) = neighbors[j]; + for (int j = 0; j < graph[u].Count; j++) { + var (v, edgeColor) = graph[u][j]; if (v == -1 || edgeColor == prevColor) continue; q.Enqueue((v, edgeColor)); - neighbors[j] = (-1, edgeColor); + graph[u][j] = (-1, edgeColor); } } step++; diff --git a/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.dart b/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.dart index 49040167..560fc552 100644 --- a/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.dart +++ b/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.dart @@ -3,20 +3,21 @@ class Solution { List ans = List.filled(n, -1); List>> graph = List.generate(n, (_) => []); - for (var edge in redEdges) { - graph[edge[0]].add([edge[1], 1]); // 1-red + for (var e in redEdges) { + graph[e[0]].add([e[1], 1]); // 1 = red } - for (var edge in blueEdges) { - graph[edge[0]].add([edge[1], 2]); // 2-blue + for (var e in blueEdges) { + graph[e[0]].add([e[1], 2]); // 2 = blue } - List> q = [[0, 0]]; // [node, prevColor] - int step = 0; + var q = Queue>(); + q.add([0, 0]); // [node, prevColor]: 0=init + int step = 0; while (q.isNotEmpty) { int size = q.length; for (int i = 0; i < size; i++) { - var cur = q.removeAt(0); + var cur = q.removeFirst(); int u = cur[0], prevColor = cur[1]; if (ans[u] == -1) { ans[u] = step; @@ -26,7 +27,7 @@ class Solution { int v = neighbors[j][0], edgeColor = neighbors[j][1]; if (v == -1 || edgeColor == prevColor) continue; q.add([v, edgeColor]); - neighbors[j][0] = -1; + neighbors[j] = [-1, edgeColor]; } } step++; diff --git a/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.go b/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.go index 1f59563e..7566337d 100644 --- a/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.go +++ b/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.go @@ -5,9 +5,10 @@ func shortestAlternatingPaths(n int, redEdges [][]int, blueEdges [][]int) []int } type edge struct { - v int - color int // 1-red, 2-blue + to int + color int // 1=red, 2=blue } + graph := make([][]edge, n) for _, e := range redEdges { graph[e[0]] = append(graph[e[0]], edge{e[1], 1}) @@ -16,28 +17,28 @@ func shortestAlternatingPaths(n int, redEdges [][]int, blueEdges [][]int) []int graph[e[0]] = append(graph[e[0]], edge{e[1], 2}) } - type node struct { - u int - prevColor int + type pair struct { + node int + prevColor int // 0=init } - q := []node{{0, 0}} + + q := []pair{{0, 0}} step := 0 for len(q) > 0 { size := len(q) for i := 0; i < size; i++ { - cur := q[0] + u, prevColor := q[0].node, q[0].prevColor q = q[1:] - if ans[cur.u] == -1 { - ans[cur.u] = step + if ans[u] == -1 { + ans[u] = step } - for j := range graph[cur.u] { - e := graph[cur.u][j] - if e.v == -1 || e.color == cur.prevColor { + for j, e := range graph[u] { + if e.to == -1 || e.color == prevColor { continue } - q = append(q, node{e.v, e.color}) - graph[cur.u][j].v = -1 + q = append(q, pair{e.to, e.color}) + graph[u][j].to = -1 } } step++ diff --git a/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.java b/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.java index 677979d9..8b8d50db 100644 --- a/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.java +++ b/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.java @@ -1,43 +1,42 @@ +import java.util.*; + class Solution { public int[] shortestAlternatingPaths(int n, int[][] redEdges, int[][] blueEdges) { - int[] ans = new int[n]; - Arrays.fill(ans, -1); - - List> graph = new ArrayList<>(); + List> red = new ArrayList<>(); + List> blue = new ArrayList<>(); for (int i = 0; i < n; i++) { - graph.add(new ArrayList<>()); + red.add(new ArrayList<>()); + blue.add(new ArrayList<>()); } - - for (int[] edge : redEdges) { - graph.get(edge[0]).add(new int[]{edge[1], 1}); // 1-red - } - for (int[] edge : blueEdges) { - graph.get(edge[0]).add(new int[]{edge[1], 2}); // 2-blue - } - - Queue q = new LinkedList<>(); - q.offer(new int[]{0, 0}); // {node, prevColor} - - int step = 0; - while (!q.isEmpty()) { - int size = q.size(); - for (int i = 0; i < size; i++) { - int[] cur = q.poll(); - int u = cur[0], prevColor = cur[1]; - if (ans[u] == -1) { - ans[u] = step; - } - List neighbors = graph.get(u); - for (int j = 0; j < neighbors.size(); j++) { - int[] pair = neighbors.get(j); - int v = pair[0], edgeColor = pair[1]; - if (v == -1 || edgeColor == prevColor) continue; - q.offer(new int[]{v, edgeColor}); - neighbors.set(j, new int[]{-1, edgeColor}); + for (int[] edge : redEdges) red.get(edge[0]).add(edge[1]); + for (int[] edge : blueEdges) blue.get(edge[0]).add(edge[1]); + + int[] answer = new int[n]; + Arrays.fill(answer, -1); + boolean[][] seen = new boolean[n][2]; + ArrayDeque queue = new ArrayDeque<>(); + queue.offer(new int[] {0, 0}); + queue.offer(new int[] {0, 1}); + seen[0][0] = seen[0][1] = true; + int distance = 0; + + while (!queue.isEmpty()) { + for (int count = queue.size(); count > 0; count--) { + int[] state = queue.poll(); + int node = state[0]; + int lastColor = state[1]; + if (answer[node] == -1) answer[node] = distance; + List> nextGraph = lastColor == 0 ? blue : red; + int nextColor = 1 - lastColor; + for (int next : nextGraph.get(node)) { + if (!seen[next][nextColor]) { + seen[next][nextColor] = true; + queue.offer(new int[] {next, nextColor}); + } } } - step++; + distance++; } - return ans; + return answer; } } diff --git a/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.kt b/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.kt index 3e36a32c..a0fdac8d 100644 --- a/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.kt +++ b/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.kt @@ -1,21 +1,25 @@ class Solution { fun shortestAlternatingPaths(n: Int, redEdges: Array, blueEdges: Array): IntArray { val ans = IntArray(n) { -1 } - val graph = Array(n) { mutableListOf>() } - val q: java.util.Queue> = java.util.LinkedList() - q.offer(Pair(0, 0)) // (node, prevColor): 0-init, 1-red, 2-blue + val graph = Array(n) { mutableListOf() } - for ((u, v) in redEdges) { - graph[u].add(Pair(v, 1)) + for (e in redEdges) { + graph[e[0]].add(intArrayOf(e[1], 1)) // 1 = red } - for ((u, v) in blueEdges) { - graph[u].add(Pair(v, 2)) + for (e in blueEdges) { + graph[e[0]].add(intArrayOf(e[1], 2)) // 2 = blue } + val q: java.util.Queue = java.util.LinkedList() + q.offer(intArrayOf(0, 0)) // [node, prevColor]: 0=init + var step = 0 while (q.isNotEmpty()) { - repeat(q.size) { - val (u, prevColor) = q.poll() + val size = q.size + repeat(size) { + val cur = q.poll() + val u = cur[0] + val prevColor = cur[1] if (ans[u] == -1) { ans[u] = step } @@ -23,8 +27,8 @@ class Solution { for (i in neighbors.indices) { val (v, edgeColor) = neighbors[i] if (v == -1 || edgeColor == prevColor) continue - q.offer(Pair(v, edgeColor)) - neighbors[i] = Pair(-1, edgeColor) + q.offer(intArrayOf(v, edgeColor)) + neighbors[i] = intArrayOf(-1, edgeColor) } } step++ diff --git a/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.py b/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.py index 67ad8402..f00d923b 100644 --- a/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.py +++ b/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.py @@ -1,5 +1,4 @@ import collections -from typing import List from enum import Enum diff --git a/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.py2 b/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.py2 index dceb257d..743ad2b2 100644 --- a/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.py2 +++ b/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.py2 @@ -8,7 +8,7 @@ class Solution(object): """ ans = [-1] * n graph = [[] for _ in range(n)] - q = collections.deque([(0, 0)]) # (node, prevColor): 0-init, 1-red, 2-blue + q = collections.deque([(0, 0)]) # (node, prevColor): 0=init, 1=red, 2=blue for u, v in redEdges: graph[u].append((v, 1)) diff --git a/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.rb b/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.rb index 209736da..4189d17e 100644 --- a/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.rb +++ b/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.rb @@ -3,9 +3,9 @@ # @param {Integer[][]} blue_edges # @return {Integer[]} def shortest_alternating_paths(n, red_edges, blue_edges) - ans = Array.new(n, -1) + ans = [-1] * n graph = Array.new(n) { [] } - q = [[0, 0]] # [node, prevColor]: 0-init, 1-red, 2-blue + q = [[0, 0]] # [node, prevColor]: 0=init, 1=red, 2=blue red_edges.each { |u, v| graph[u] << [v, 1] } blue_edges.each { |u, v| graph[u] << [v, 2] } diff --git a/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.rs b/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.rs index 0c394041..5fecf39b 100644 --- a/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.rs +++ b/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.rs @@ -2,33 +2,34 @@ impl Solution { pub fn shortest_alternating_paths(n: i32, red_edges: Vec>, blue_edges: Vec>) -> Vec { let n = n as usize; let mut ans = vec![-1; n]; - let mut graph: Vec> = vec![Vec::new(); n]; - let mut q = std::collections::VecDeque::new(); - q.push_back((0i32, 0i32)); // (node, prevColor): 0-init, 1-red, 2-blue + let mut graph: Vec> = vec![vec![]; n]; // (to, color): 1=red, 2=blue - for edge in &red_edges { - graph[edge[0] as usize].push((edge[1], 1)); + for e in &red_edges { + graph[e[0] as usize].push((e[1], 1)); } - for edge in &blue_edges { - graph[edge[0] as usize].push((edge[1], 2)); + for e in &blue_edges { + graph[e[0] as usize].push((e[1], 2)); } + let mut q = std::collections::VecDeque::new(); + q.push_back((0, 0)); // (node, prevColor): 0=init + let mut step = 0; while !q.is_empty() { let size = q.len(); for _ in 0..size { let (u, prev_color) = q.pop_front().unwrap(); - let uu = u as usize; - if ans[uu] == -1 { - ans[uu] = step; + let u = u as usize; + if ans[u] == -1 { + ans[u] = step; } - for i in 0..graph[uu].len() { - let (v, edge_color) = graph[uu][i]; - if v == -1 || edge_color == prev_color { + let neighbors = graph[u].clone(); + for (j, (v, edge_color)) in neighbors.iter().enumerate() { + if *v == -1 || *edge_color == prev_color { continue; } - q.push_back((v, edge_color)); - graph[uu][i] = (-1, edge_color); + q.push_back((*v as usize, *edge_color)); + graph[u][j] = (-1, *edge_color); } } step += 1; diff --git a/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.swift b/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.swift index 632ee8c8..5294905a 100644 --- a/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.swift +++ b/tests/1001-1500/1129. shortest-path-with-alternating-colors/sol.swift @@ -1,17 +1,18 @@ class Solution { func shortestAlternatingPaths(_ n: Int, _ redEdges: [[Int]], _ blueEdges: [[Int]]) -> [Int] { - var ans = Array(repeating: -1, count: n) - var graph = Array(repeating: [(Int, Int)](), count: n) - var q: [(Int, Int)] = [(0, 0)] // (node, prevColor): 0-init, 1-red, 2-blue + var ans = [Int](repeating: -1, count: n) + var graph = [[(Int, Int)]](repeating: [], count: n) // (to, color): 1=red, 2=blue - for edge in redEdges { - graph[edge[0]].append((edge[1], 1)) + for e in redEdges { + graph[e[0]].append((e[1], 1)) } - for edge in blueEdges { - graph[edge[0]].append((edge[1], 2)) + for e in blueEdges { + graph[e[0]].append((e[1], 2)) } + var q = [(0, 0)] // (node, prevColor): 0=init var step = 0 + while !q.isEmpty { let size = q.count for _ in 0.. []); - const q: [number, number][] = [[0, 0]]; // [node, prevColor]: 0-init, 1-red, 2-blue for (const [u, v] of redEdges) { - graph[u].push([v, 1]); + graph[u].push([v, 1]); // 1 = red } for (const [u, v] of blueEdges) { - graph[u].push([v, 2]); + graph[u].push([v, 2]); // 2 = blue } + const q: [number, number][] = [[0, 0]]; // [node, prevColor]: 0=init let step = 0; + while (q.length > 0) { const size = q.length; for (let i = 0; i < size; i++) { diff --git a/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/manifest.yaml b/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/manifest.yaml new file mode 100644 index 00000000..a3282f26 --- /dev/null +++ b/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/manifest.yaml @@ -0,0 +1,272 @@ +entry: + id: 1130 + title: "minimum-cost-tree-from-leaf-values" + params: + arr: + type: array + items: + type: int + call: + cpp: "Solution().mctFromLeafValues({arr})" + rust: "Solution::mct_from_leaf_values({arr})" + python3: "Solution().mctFromLeafValues({arr})" + python2: "Solution().mctFromLeafValues({arr})" + ruby: "mct_from_leaf_values({arr})" + java: "new Solution().mctFromLeafValues({arr})" + csharp: "new Solution().MctFromLeafValues({arr})" + kotlin: "Solution().mctFromLeafValues({arr})" + go: "mctFromLeafValues({arr})" + dart: "Solution().mctFromLeafValues({arr})" + swift: "Solution().mctFromLeafValues({arr})" + typescript: "mctFromLeafValues({arr})" + +judge: + type: "exact" + +limits: + time_ms: 500 + memory_mb: 300 + +oracle: + python3: + call: "Checker().mctFromLeafValues(arr, {result})" + checker: | + class Checker: + def mctFromLeafValues(self, arr, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + n = len(arr) + if n < 2 or n > 40 or any(not isinstance(x, int) or isinstance(x, bool) or x < 1 or x > 15 for x in arr): + return False + mx = [[0] * n for _ in range(n)] + for i in range(n): + mx[i][i] = arr[i] + for j in range(i + 1, n): + mx[i][j] = max(mx[i][j - 1], arr[j]) + dp = [[0] * n for _ in range(n)] + for width in range(2, n + 1): + for left in range(n - width + 1): + right = left + width - 1 + best = 2 ** 63 - 1 + for split in range(left, right): + best = min(best, dp[left][split] + dp[split + 1][right] + mx[left][split] * mx[split + 1][right]) + dp[left][right] = best + return result == dp[0][n - 1] + +seed: 113000 + +tests: + - name: "example_three_leaves" + in: + arr: [6, 2, 4] + out: 32 + - name: "example_two_leaves" + in: + arr: [4, 11] + out: 44 + - name: "minimum_pair" + in: + arr: [1, 1] + out: 1 + - name: "increasing_four" + in: + arr: [1, 2, 3, 4] + out: 20 + - name: "decreasing_four" + in: + arr: [4, 3, 2, 1] + out: 20 + - name: "symmetric_peak" + in: + arr: [1, 2, 1] + out: 4 + - name: "valley" + in: + arr: [2, 1, 2] + out: 6 + - name: "equal_four" + in: + arr: [5, 5, 5, 5] + out: 75 + - name: "maximum_equal_three" + in: + arr: [15, 15, 15] + out: 450 + - name: "alternating_low_high" + in: + arr: [1, 15, 1, 15] + out: 255 + - name: "alternating_high_low" + in: + arr: [15, 1, 15, 1] + out: 255 + - name: "mixed_a" + in: + arr: [2, 7, 6, 3] + out: 74 + - name: "mixed_b" + in: + arr: [7, 2, 5, 10] + out: 115 + - name: "repeated_small" + in: + arr: [3, 1, 2, 1, 3] + out: 19 + - name: "decreasing_five" + in: + arr: [10, 9, 8, 7, 6] + out: 260 + - name: "mixed_c" + in: + arr: [1, 3, 2, 4, 1] + out: 25 + - name: "mixed_d" + in: + arr: [8, 1, 4, 2, 7] + out: 96 + - name: "example_prefix_plus_leaf" + in: + arr: [6, 2, 4, 5] + out: 58 + - name: "increasing_five" + in: + arr: [2, 4, 6, 8, 10] + out: 160 + - name: "decreasing_six" + in: + arr: [15, 14, 13, 12, 11, 10] + out: 790 + - name: "equal_six" + in: + arr: [1, 1, 1, 1, 1, 1] + out: 5 + - name: "equal_middle_pair" + in: + arr: [1, 5, 5, 1] + out: 35 + - name: "paired_duplicates" + in: + arr: [2, 2, 3, 3] + out: 19 + - name: "alternating_medium" + in: + arr: [9, 1, 8, 2, 7] + out: 150 + - name: "equal_edges" + in: + arr: [4, 1, 1, 4] + out: 21 + - name: "two_value_repeat" + in: + arr: [12, 3, 12, 3] + out: 216 + - name: "palindrome_five" + in: + arr: [1, 4, 2, 4, 1] + out: 32 + - name: "mixed_six" + in: + arr: [5, 1, 2, 3, 4, 5] + out: 65 + - name: "descending_peaks" + in: + arr: [14, 2, 13, 3, 12, 4] + out: 448 + - name: "duplicate_pairs_six" + in: + arr: [3, 3, 1, 2, 2, 1] + out: 23 + - name: "large_prefix_peak" + in: + arr: [11, 10, 1, 2, 3, 4] + out: 170 + - name: "palindrome_five_two" + in: + arr: [1, 2, 3, 2, 1] + out: 16 + - name: "alternating_peaks_six" + in: + arr: [2, 15, 3, 14, 4, 13] + out: 516 + - name: "interleaved_six" + in: + arr: [1, 6, 2, 5, 3, 4] + out: 78 + - name: "generated_maximum_a" + seed: 113001 + in: + arr: + gen: "array" + len: 40 + of: + gen: "int" + min: 1 + max: 15 + distinct: false + sorted: false + elemType: "int" + - name: "generated_maximum_b" + seed: 113002 + in: + arr: + gen: "array" + len: 40 + of: + gen: "int" + min: 1 + max: 15 + distinct: false + sorted: false + elemType: "int" + - name: "generated_maximum_c" + seed: 113003 + in: + arr: + gen: "array" + len: 40 + of: + gen: "int" + min: 1 + max: 15 + distinct: false + sorted: false + elemType: "int" + - name: "generated_maximum_d" + seed: 113004 + in: + arr: + gen: "array" + len: 40 + of: + gen: "int" + min: 1 + max: 15 + distinct: false + sorted: false + elemType: "int" + - name: "generated_maximum_e" + seed: 113005 + in: + arr: + gen: "array" + len: 40 + of: + gen: "int" + min: 1 + max: 15 + distinct: false + sorted: false + elemType: "int" + - name: "generated_maximum_f" + seed: 113006 + in: + arr: + gen: "array" + len: 40 + of: + gen: "int" + min: 1 + max: 15 + distinct: false + sorted: false + elemType: "int" diff --git a/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.cpp b/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.cpp new file mode 100644 index 00000000..e7156673 --- /dev/null +++ b/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int mctFromLeafValues(vector& arr) { + int result = 0; + vector st = {INT_MAX}; + + for (int a : arr) { + while (st.back() <= a) { + int mid = st.back(); + st.pop_back(); + result += mid * min(st.back(), a); + } + st.push_back(a); + } + + int first = st.back(); + st.pop_back(); + while (st.size() > 1) { + result += first * st.back(); + first = st.back(); + st.pop_back(); + } + + return result; + } +}; diff --git a/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.cs b/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.cs new file mode 100644 index 00000000..e0dbb6ba --- /dev/null +++ b/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.cs @@ -0,0 +1,23 @@ +public class Solution { + public int MctFromLeafValues(int[] arr) { + int result = 0; + var st = new Stack(); + st.Push(int.MaxValue); + + foreach (int a in arr) { + while (st.Peek() <= a) { + int mid = st.Pop(); + result += mid * Math.Min(st.Peek(), a); + } + st.Push(a); + } + + int first = st.Pop(); + while (st.Count > 1) { + result += first * st.Peek(); + first = st.Pop(); + } + + return result; + } +} diff --git a/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.dart b/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.dart new file mode 100644 index 00000000..1ae3c619 --- /dev/null +++ b/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.dart @@ -0,0 +1,22 @@ +class Solution { + int mctFromLeafValues(List arr) { + int result = 0; + List st = [double.maxFinite.toInt()]; + + for (int a in arr) { + while (st.last <= a) { + int mid = st.removeLast(); + result += mid * (st.last < a ? st.last : a); + } + st.add(a); + } + + int first = st.removeLast(); + while (st.length > 1) { + result += first * st.last; + first = st.removeLast(); + } + + return result; + } +} diff --git a/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.go b/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.go new file mode 100644 index 00000000..fec0e741 --- /dev/null +++ b/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.go @@ -0,0 +1,23 @@ +func mctFromLeafValues(arr []int) int { + result := 0 + st := []int{int(^uint(0) >> 1)} + + for _, a := range arr { + for st[len(st)-1] <= a { + mid := st[len(st)-1] + st = st[:len(st)-1] + result += mid * min(st[len(st)-1], a) + } + st = append(st, a) + } + + first := st[len(st)-1] + st = st[:len(st)-1] + for len(st) > 1 { + result += first * st[len(st)-1] + first = st[len(st)-1] + st = st[:len(st)-1] + } + + return result +} diff --git a/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.java b/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.java new file mode 100644 index 00000000..3cc118a4 --- /dev/null +++ b/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.java @@ -0,0 +1,23 @@ +class Solution { + public int mctFromLeafValues(int[] arr) { + int result = 0; + java.util.Stack st = new java.util.Stack<>(); + st.push(Integer.MAX_VALUE); + + for (int a : arr) { + while (st.peek() <= a) { + int mid = st.pop(); + result += mid * Math.min(st.peek(), a); + } + st.push(a); + } + + int first = st.pop(); + while (st.size() > 1) { + result += first * st.peek(); + first = st.pop(); + } + + return result; + } +} diff --git a/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.kt b/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.kt new file mode 100644 index 00000000..4991c6d7 --- /dev/null +++ b/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.kt @@ -0,0 +1,23 @@ +class Solution { + fun mctFromLeafValues(arr: IntArray): Int { + var result = 0 + val st = ArrayDeque() + st.addLast(Int.MAX_VALUE) + + for (a in arr) { + while (st.last() <= a) { + val mid = st.removeLast() + result += mid * minOf(st.last(), a) + } + st.addLast(a) + } + + var first = st.removeLast() + while (st.size > 1) { + result += first * st.last() + first = st.removeLast() + } + + return result + } +} diff --git a/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.py b/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.py new file mode 100644 index 00000000..4f1febb2 --- /dev/null +++ b/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.py @@ -0,0 +1,18 @@ +class Solution: + def mctFromLeafValues(self, arr): + result = 0 + st = [float("inf")] # sentinel so stack is never empty + + for a in arr: + while st[-1] <= a: + mid = st.pop() + result += mid * min(st[-1], a) + st.append(a) + + # Merge remaining elements in stack + first = st.pop() + while len(st) > 1: # leave sentinel + result += first * st[-1] + first = st.pop() + + return result diff --git a/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.py2 b/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.py2 new file mode 100644 index 00000000..23e88ac6 --- /dev/null +++ b/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.py2 @@ -0,0 +1,21 @@ +class Solution(object): + def mctFromLeafValues(self, arr): + """ + :type arr: List[int] + :rtype: int + """ + result = 0 + st = [float('inf')] + + for a in arr: + while st[-1] <= a: + mid = st.pop() + result += mid * min(st[-1], a) + st.append(a) + + first = st.pop() + while len(st) > 1: + result += first * st[-1] + first = st.pop() + + return result diff --git a/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.rb b/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.rb new file mode 100644 index 00000000..d05ae1c5 --- /dev/null +++ b/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.rb @@ -0,0 +1,22 @@ +# @param {Integer[]} arr +# @return {Integer} +def mct_from_leaf_values(arr) + result = 0 + st = [Float::INFINITY] + + arr.each do |a| + while st[-1] <= a + mid = st.pop + result += mid * [st[-1], a].min + end + st.push(a) + end + + first = st.pop + while st.length > 1 + result += first * st[-1] + first = st.pop + end + + result +end diff --git a/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.rs b/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.rs new file mode 100644 index 00000000..479b3b0b --- /dev/null +++ b/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.rs @@ -0,0 +1,22 @@ +impl Solution { + pub fn mct_from_leaf_values(arr: Vec) -> i32 { + let mut result = 0; + let mut st: Vec = vec![i32::MAX]; + + for &a in &arr { + while st[st.len() - 1] <= a { + let mid = st.pop().unwrap(); + result += mid * st[st.len() - 1].min(a); + } + st.push(a); + } + + let mut first = st.pop().unwrap(); + while st.len() > 1 { + result += first * st[st.len() - 1]; + first = st.pop().unwrap(); + } + + result + } +} diff --git a/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.swift b/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.swift new file mode 100644 index 00000000..54ff215d --- /dev/null +++ b/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.swift @@ -0,0 +1,22 @@ +class Solution { + func mctFromLeafValues(_ arr: [Int]) -> Int { + var result = 0 + var st = [Int.max] + + for a in arr { + while st.last! <= a { + let mid = st.removeLast() + result += mid * min(st.last!, a) + } + st.append(a) + } + + var first = st.removeLast() + while st.count > 1 { + result += first * st.last! + first = st.removeLast() + } + + return result + } +} diff --git a/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.ts b/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.ts new file mode 100644 index 00000000..f3911b4b --- /dev/null +++ b/tests/1001-1500/1130. minimum-cost-tree-from-leaf-values/sol.ts @@ -0,0 +1,20 @@ +function mctFromLeafValues(arr: number[]): number { + let result = 0; + const st: number[] = [Infinity]; + + for (const a of arr) { + while (st[st.length - 1] <= a) { + const mid = st.pop()!; + result += mid * Math.min(st[st.length - 1], a); + } + st.push(a); + } + + let first = st.pop()!; + while (st.length > 1) { + result += first * st[st.length - 1]; + first = st.pop()!; + } + + return result; +} diff --git a/tests/1001-1500/1131. maximum-of-absolute-value-expression/manifest.yaml b/tests/1001-1500/1131. maximum-of-absolute-value-expression/manifest.yaml new file mode 100644 index 00000000..e62666a7 --- /dev/null +++ b/tests/1001-1500/1131. maximum-of-absolute-value-expression/manifest.yaml @@ -0,0 +1,335 @@ +entry: + id: 1131 + title: "maximum-of-absolute-value-expression" + params: + arr1: + type: array + items: + type: int + arr2: + type: array + items: + type: int + call: + cpp: "Solution().maxAbsValExpr({arr1}, {arr2})" + rust: "Solution::max_abs_val_expr({arr1}, {arr2})" + python3: "Solution().maxAbsValExpr({arr1}, {arr2})" + python2: "Solution().maxAbsValExpr({arr1}, {arr2})" + ruby: "max_abs_val_expr({arr1}, {arr2})" + java: "new Solution().maxAbsValExpr({arr1}, {arr2})" + csharp: "new Solution().MaxAbsValExpr({arr1}, {arr2})" + kotlin: "Solution().maxAbsValExpr({arr1}, {arr2})" + go: "maxAbsValExpr({arr1}, {arr2})" + dart: "Solution().maxAbsValExpr({arr1}, {arr2})" + swift: "Solution().maxAbsValExpr({arr1}, {arr2})" + typescript: "maxAbsValExpr({arr1}, {arr2})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().maxAbsValExpr(arr1, arr2, {result})" + checker: | + class Checker: + def maxAbsValExpr(self, arr1, arr2, result): + if len(arr1) != len(arr2) or len(arr1) < 2: + return False + best = 0 + for sign1 in (1, -1): + for sign2 in (1, -1): + values = [sign1 * arr1[i] + sign2 * arr2[i] + i for i in range(len(arr1))] + best = max(best, max(values) - min(values)) + return result == best + +seed: 1131 + +tests: + - name: "example-one" + in: + arr1: [1, 2, 3, 4] + arr2: [-1, 4, 5, 6] + out: 13 + - name: "example-two" + in: + arr1: [1, -2, -5, 0, 10] + arr2: [0, -2, -1, -7, -4] + out: 20 + - name: "minimum-length-equal" + in: + arr1: [0, 0] + arr2: [0, 0] + out: 1 + - name: "index-dominates" + in: + arr1: [5, 5, 5, 5, 5] + arr2: [7, 7, 7, 7, 7] + out: 4 + - name: "constant-opposite" + in: + arr1: [10, 10, 10] + arr2: [-10, -10, -10] + out: 2 + - name: "two-positive-extremes" + in: + arr1: [1000000, -1000000] + arr2: [1000000, -1000000] + out: 4000001 + - name: "two-crossed-extremes" + in: + arr1: [1000000, -1000000] + arr2: [-1000000, 1000000] + out: 4000001 + - name: "two-element-one-axis-maximum" + in: + arr1: [1000000, -1000000] + arr2: [0, 0] + out: 2000001 + - name: "single-coordinate-change" + in: + arr1: [0, 100, 0] + arr2: [0, 0, 0] + out: 101 + - name: "negative-coordinate-change" + in: + arr1: [0, -100, 0] + arr2: [0, 0, 0] + out: 101 + - name: "alternating-signs" + in: + arr1: [1, -1, 1, -1] + arr2: [-1, 1, -1, 1] + out: 7 + - name: "opposing-trends" + in: + arr1: [-5, -2, 1, 4] + arr2: [8, 5, 2, -1] + out: 21 + - name: "same-trends" + in: + arr1: [-5, -2, 1, 4] + arr2: [-8, -5, -2, 1] + out: 21 + - name: "zeros-and-one" + in: + arr1: [0, 1] + arr2: [0, 1] + out: 3 + - name: "large-negative" + in: + arr1: [-1000000, -999999, -1000000] + arr2: [1000000, 999999, 1000000] + out: 3 + - name: "large-positive" + in: + arr1: [1000000, 999999, 1000000] + arr2: [1000000, 999999, 1000000] + out: 3 + - name: "repeated-extreme" + in: + arr1: [1000000, 0, -1000000, 0] + arr2: [0, 1000000, 0, -1000000] + out: 2000003 + - name: "mixed-small" + in: + arr1: [3, -4, 2, -1, 0, 7] + arr2: [-2, 5, -6, 4, 1, -3] + out: 23 + - name: "mixed-duplicates" + in: + arr1: [2, 2, -2, -2, 2] + arr2: [1, -1, 1, -1, 1] + out: 9 + - name: "monotone-arr1" + in: + arr1: [0, 1, 2, 3, 4, 5] + arr2: [5, 4, 3, 2, 1, 0] + out: 15 + - name: "monotone-arr2" + in: + arr1: [5, 4, 3, 2, 1, 0] + arr2: [0, 1, 2, 3, 4, 5] + out: 15 + - name: "uneven-small" + in: + arr1: [-3, 9, -8, 2, 6] + arr2: [4, -7, 5, 0, -2] + out: 30 + - name: "cancellation" + in: + arr1: [100, -100, 50, -50] + arr2: [-100, 100, -50, 50] + out: 401 + - name: "center-peak" + in: + arr1: [0, 0, 100, 0, 0] + arr2: [0, 0, -100, 0, 0] + out: 202 + - name: "all-minimum" + in: + arr1: [-1000000, -1000000] + arr2: [-1000000, -1000000] + out: 1 + - name: "alternating-large" + in: + arr1: [1000000, -1000000, 1000000, -1000000, 1000000] + arr2: [-1000000, 1000000, -1000000, 1000000, -1000000] + out: 4000003 + - name: "short-three" + in: + arr1: [9, 0, -9] + arr2: [2, -4, 6] + out: 24 + - name: "short-four" + in: + arr1: [-1, 8, 3, -6] + arr2: [7, -2, 5, 0] + out: 19 + - name: "balanced-six" + in: + arr1: [-2, 4, -6, 8, -10, 12] + arr2: [3, -5, 7, -9, 11, -13] + out: 47 + - name: "zeros-with-spike" + in: + arr1: [0, 0, 0, 0, 50, 0, 0] + arr2: [0, 0, 0, 0, 50, 0, 0] + out: 104 + - name: "interior-opposite-extremes" + in: + arr1: [0, 1000000, 0, 0, -1000000, 0] + arr2: [0, -1000000, 0, 0, 1000000, 0] + out: 4000003 + - name: "far-endpoints-mixed-signs" + in: + arr1: [-1000000, 4, -3, 2, 1000000] + arr2: [1000000, -5, 6, -7, -1000000] + out: 4000004 + - name: "middle-pair-beats-endpoints" + in: + arr1: [0, -900000, 900000, 0, 0] + arr2: [0, 900000, -900000, 0, 0] + out: 3600001 + - name: "plateaus-with-late-reversal" + in: + arr1: [12, 12, 12, -8, -8, -8, 12] + arr2: [-3, -3, -3, 9, 9, 9, -3] + out: 37 + - name: "generated-wide-12k" + seed: 113101 + in: + arr1: + gen: "array" + len: 12000 + of: + gen: "int" + min: -1000000 + max: 1000000 + elemType: "int" + arr2: + gen: "array" + len: 12000 + of: + gen: "int" + min: -1000000 + max: 1000000 + elemType: "int" + - name: "generated-wide-25k" + seed: 113102 + in: + arr1: + gen: "array" + len: 25000 + of: + gen: "int" + min: -1000000 + max: 1000000 + elemType: "int" + arr2: + gen: "array" + len: 25000 + of: + gen: "int" + min: -1000000 + max: 1000000 + elemType: "int" + - name: "generated-large-max" + seed: 113103 + in: + arr1: + gen: "array" + len: 40000 + of: + gen: "int" + min: -1000000 + max: 1000000 + elemType: "int" + arr2: + gen: "array" + len: 40000 + of: + gen: "int" + min: -1000000 + max: 1000000 + elemType: "int" + - name: "generated-large-narrow" + seed: 113104 + in: + arr1: + gen: "array" + len: 39999 + of: + gen: "int" + min: -3 + max: 3 + elemType: "int" + arr2: + gen: "array" + len: 39999 + of: + gen: "int" + min: -3 + max: 3 + elemType: "int" + - name: "generated-large-wide-32k" + seed: 113105 + in: + arr1: + gen: "array" + len: 32000 + of: + gen: "int" + min: -1000000 + max: 1000000 + elemType: "int" + arr2: + gen: "array" + len: 32000 + of: + gen: "int" + min: -1000000 + max: 1000000 + elemType: "int" + - name: "generated-large-midrange-36k" + seed: 113106 + in: + arr1: + gen: "array" + len: 36000 + of: + gen: "int" + min: -250000 + max: 250000 + elemType: "int" + arr2: + gen: "array" + len: 36000 + of: + gen: "int" + min: -250000 + max: 250000 + elemType: "int" diff --git a/tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.cpp b/tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.cpp new file mode 100644 index 00000000..25e0bff8 --- /dev/null +++ b/tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int maxAbsValExpr(vector& arr1, vector& arr2) { + int res = 0; + int n = arr1.size(); + vector> signs = {{1, 1}, {1, -1}, {-1, 1}, {-1, -1}}; + + for (auto [p, q] : signs) { + int maxVal = INT_MIN; + int minVal = INT_MAX; + for (int i = 0; i < n; i++) { + int value = p * arr1[i] + q * arr2[i] + i; + maxVal = max(maxVal, value); + minVal = min(minVal, value); + } + res = max(res, maxVal - minVal); + } + + return res; + } +}; diff --git a/tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.cs b/tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.cs new file mode 100644 index 00000000..7537610c --- /dev/null +++ b/tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.cs @@ -0,0 +1,22 @@ +public class Solution { + public int MaxAbsValExpr(int[] arr1, int[] arr2) { + int res = 0; + int n = arr1.Length; + int[,] signs = {{1, 1}, {1, -1}, {-1, 1}, {-1, -1}}; + + for (int k = 0; k < 4; k++) { + int p = signs[k, 0]; + int q = signs[k, 1]; + int maxVal = int.MinValue; + int minVal = int.MaxValue; + for (int i = 0; i < n; i++) { + int value = p * arr1[i] + q * arr2[i] + i; + maxVal = Math.Max(maxVal, value); + minVal = Math.Min(minVal, value); + } + res = Math.Max(res, maxVal - minVal); + } + + return res; + } +} diff --git a/tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.dart b/tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.dart new file mode 100644 index 00000000..a853fec1 --- /dev/null +++ b/tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.dart @@ -0,0 +1,21 @@ +class Solution { + int maxAbsValExpr(List arr1, List arr2) { + int res = 0; + int n = arr1.length; + List> signs = [[1, 1], [1, -1], [-1, 1], [-1, -1]]; + + for (var sign in signs) { + int p = sign[0], q = sign[1]; + int maxVal = -1000000000; + int minVal = 1000000000; + for (int i = 0; i < n; i++) { + int value = p * arr1[i] + q * arr2[i] + i; + if (value > maxVal) maxVal = value; + if (value < minVal) minVal = value; + } + if (maxVal - minVal > res) res = maxVal - minVal; + } + + return res; + } +} diff --git a/tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.go b/tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.go new file mode 100644 index 00000000..f32b3881 --- /dev/null +++ b/tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.go @@ -0,0 +1,25 @@ +func maxAbsValExpr(arr1 []int, arr2 []int) int { + res := 0 + n := len(arr1) + signs := [][]int{{1, 1}, {1, -1}, {-1, 1}, {-1, -1}} + + for _, sign := range signs { + p, q := sign[0], sign[1] + maxVal := int(-1e9) + minVal := int(1e9) + for i := 0; i < n; i++ { + value := p*arr1[i] + q*arr2[i] + i + if value > maxVal { + maxVal = value + } + if value < minVal { + minVal = value + } + } + if maxVal - minVal > res { + res = maxVal - minVal + } + } + + return res +} diff --git a/tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.java b/tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.java new file mode 100644 index 00000000..dd662a05 --- /dev/null +++ b/tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.java @@ -0,0 +1,21 @@ +class Solution { + public int maxAbsValExpr(int[] arr1, int[] arr2) { + int res = 0; + int n = arr1.length; + int[][] signs = {{1, 1}, {1, -1}, {-1, 1}, {-1, -1}}; + + for (int[] sign : signs) { + int p = sign[0], q = sign[1]; + int maxVal = Integer.MIN_VALUE; + int minVal = Integer.MAX_VALUE; + for (int i = 0; i < n; i++) { + int value = p * arr1[i] + q * arr2[i] + i; + maxVal = Math.max(maxVal, value); + minVal = Math.min(minVal, value); + } + res = Math.max(res, maxVal - minVal); + } + + return res; + } +} diff --git a/tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.kt b/tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.kt new file mode 100644 index 00000000..20f265bd --- /dev/null +++ b/tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.kt @@ -0,0 +1,22 @@ +class Solution { + fun maxAbsValExpr(arr1: IntArray, arr2: IntArray): Int { + var res = 0 + val n = arr1.size + val signs = arrayOf(intArrayOf(1, 1), intArrayOf(1, -1), intArrayOf(-1, 1), intArrayOf(-1, -1)) + + for (sign in signs) { + val p = sign[0] + val q = sign[1] + var maxVal = Int.MIN_VALUE + var minVal = Int.MAX_VALUE + for (i in 0 until n) { + val value = p * arr1[i] + q * arr2[i] + i + maxVal = maxOf(maxVal, value) + minVal = minOf(minVal, value) + } + res = maxOf(res, maxVal - minVal) + } + + return res + } +} diff --git a/tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.py b/tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.py new file mode 100644 index 00000000..9f1dbd5d --- /dev/null +++ b/tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.py @@ -0,0 +1,20 @@ +class Solution(object): + def maxAbsValExpr(self, arr1, arr2): + """ + :type arr1: List[int] + :type arr2: List[int] + :rtype: int + """ + res = 0 + n = len(arr1) + + for p, q in [(1, 1), (1, -1), (-1, 1), (-1, -1)]: + max_val = float("-inf") + min_val = float("inf") + for i in range(n): + value = p * arr1[i] + q * arr2[i] + i + max_val = max(max_val, value) + min_val = min(min_val, value) + res = max(res, max_val - min_val) + + return res diff --git a/tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.py2 b/tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.py2 new file mode 100644 index 00000000..625310cb --- /dev/null +++ b/tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.py2 @@ -0,0 +1,20 @@ +class Solution(object): + def maxAbsValExpr(self, arr1, arr2): + """ + :type arr1: List[int] + :type arr2: List[int] + :rtype: int + """ + res = 0 + n = len(arr1) + + for p, q in [(1, 1), (1, -1), (-1, 1), (-1, -1)]: + max_val = float('-inf') + min_val = float('inf') + for i in range(n): + value = p * arr1[i] + q * arr2[i] + i + max_val = max(max_val, value) + min_val = min(min_val, value) + res = max(res, max_val - min_val) + + return res diff --git a/tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.rb b/tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.rb new file mode 100644 index 00000000..4b47a83e --- /dev/null +++ b/tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.rb @@ -0,0 +1,20 @@ +# @param {Integer[]} arr1 +# @param {Integer[]} arr2 +# @return {Integer} +def max_abs_val_expr(arr1, arr2) + res = 0 + n = arr1.length + + [[1, 1], [1, -1], [-1, 1], [-1, -1]].each do |p, q| + max_val = -Float::INFINITY + min_val = Float::INFINITY + (0...n).each do |i| + value = p * arr1[i] + q * arr2[i] + i + max_val = value if value > max_val + min_val = value if value < min_val + end + res = [res, max_val - min_val].max + end + + res +end diff --git a/tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.rs b/tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.rs new file mode 100644 index 00000000..cd4b631d --- /dev/null +++ b/tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.rs @@ -0,0 +1,20 @@ +impl Solution { + pub fn max_abs_val_expr(arr1: Vec, arr2: Vec) -> i32 { + let mut res = 0; + let n = arr1.len(); + let signs = [(1, 1), (1, -1), (-1, 1), (-1, -1)]; + + for (p, q) in signs.iter() { + let mut max_val = i32::MIN; + let mut min_val = i32::MAX; + for i in 0..n { + let value = p * arr1[i] + q * arr2[i] + i as i32; + max_val = max_val.max(value); + min_val = min_val.min(value); + } + res = res.max(max_val - min_val); + } + + res + } +} diff --git a/tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.swift b/tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.swift new file mode 100644 index 00000000..4c4b3cfe --- /dev/null +++ b/tests/1001-1500/1131. maximum-of-absolute-value-expression/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func maxAbsValExpr(_ arr1: [Int], _ arr2: [Int]) -> Int { + var res = 0 + let n = arr1.count + let signs = [(1, 1), (1, -1), (-1, 1), (-1, -1)] + + for (p, q) in signs { + var maxVal = Int.min + var minVal = Int.max + for i in 0.. 37: + return False + if not isinstance(result, int) or isinstance(result, bool): + return False + first, second, third = 0, 1, 1 + for _ in range(n): + first, second, third = second, third, first + second + third + return result == first +seed: 1137 +tests: + - name: minimum_n0 + in: + n: 0 + out: 0 + - name: base_n1 + in: + n: 1 + out: 1 + - name: base_n2 + in: + n: 2 + out: 1 + - name: first_recurrence_n3 + in: + n: 3 + out: 2 + - name: recurrence_n4 + in: + n: 4 + out: 4 + - name: recurrence_n5 + in: + n: 5 + out: 7 + - name: recurrence_n6 + in: + n: 6 + out: 13 + - name: recurrence_n7 + in: + n: 7 + out: 24 + - name: recurrence_n8 + in: + n: 8 + out: 44 + - name: recurrence_n9 + in: + n: 9 + out: 81 + - name: recurrence_n10 + in: + n: 10 + out: 149 + - name: recurrence_n11 + in: + n: 11 + out: 274 + - name: recurrence_n12 + in: + n: 12 + out: 504 + - name: recurrence_n13 + in: + n: 13 + out: 927 + - name: recurrence_n14 + in: + n: 14 + out: 1705 + - name: recurrence_n15 + in: + n: 15 + out: 3136 + - name: recurrence_n16 + in: + n: 16 + out: 5768 + - name: recurrence_n17 + in: + n: 17 + out: 10609 + - name: recurrence_n18 + in: + n: 18 + out: 19513 + - name: recurrence_n19 + in: + n: 19 + out: 35890 + - name: recurrence_n20 + in: + n: 20 + out: 66012 + - name: recurrence_n21 + in: + n: 21 + out: 121415 + - name: recurrence_n22 + in: + n: 22 + out: 223317 + - name: recurrence_n23 + in: + n: 23 + out: 410744 + - name: recurrence_n24 + in: + n: 24 + out: 755476 + - name: recurrence_n25 + in: + n: 25 + out: 1389537 + - name: recurrence_n26 + in: + n: 26 + out: 2555757 + - name: recurrence_n27 + in: + n: 27 + out: 4700770 + - name: recurrence_n28 + in: + n: 28 + out: 8646064 + - name: recurrence_n29 + in: + n: 29 + out: 15902591 + - name: recurrence_n30 + in: + n: 30 + out: 29249425 + - name: recurrence_n31 + in: + n: 31 + out: 53798080 + - name: recurrence_n32 + in: + n: 32 + out: 98950096 + - name: recurrence_n33 + in: + n: 33 + out: 181997601 + - name: recurrence_n34 + in: + n: 34 + out: 334745777 + - name: recurrence_n35 + in: + n: 35 + out: 615693474 + - name: recurrence_n36 + in: + n: 36 + out: 1132436852 + - name: maximum_n37 + in: + n: 37 + out: 2082876103 + - name: official_example_n4 + in: + n: 4 + out: 4 + - name: official_example_n25 + in: + n: 25 + out: 1389537 diff --git a/tests/1001-1500/1137. n-th-tribonacci-number/sol.cpp b/tests/1001-1500/1137. n-th-tribonacci-number/sol.cpp new file mode 100644 index 00000000..b46da5de --- /dev/null +++ b/tests/1001-1500/1137. n-th-tribonacci-number/sol.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + int tribonacci(int n) { + int ft = 0, st = 1, tt = 1; + for (int i = 1; i <= n; i++) { + int frt = ft + st + tt; + ft = st; + st = tt; + tt = frt; + } + return ft; + } +}; diff --git a/tests/1001-1500/1137. n-th-tribonacci-number/sol.cs b/tests/1001-1500/1137. n-th-tribonacci-number/sol.cs new file mode 100644 index 00000000..5f88901f --- /dev/null +++ b/tests/1001-1500/1137. n-th-tribonacci-number/sol.cs @@ -0,0 +1,12 @@ +public class Solution { + public int Tribonacci(int n) { + int ft = 0, st = 1, tt = 1; + for (int i = 1; i <= n; i++) { + int frt = ft + st + tt; + ft = st; + st = tt; + tt = frt; + } + return ft; + } +} diff --git a/tests/1001-1500/1137. n-th-tribonacci-number/sol.dart b/tests/1001-1500/1137. n-th-tribonacci-number/sol.dart new file mode 100644 index 00000000..70b702c3 --- /dev/null +++ b/tests/1001-1500/1137. n-th-tribonacci-number/sol.dart @@ -0,0 +1,12 @@ +class Solution { + int tribonacci(int n) { + int ft = 0, st = 1, tt = 1; + for (int i = 1; i <= n; i++) { + int frt = ft + st + tt; + ft = st; + st = tt; + tt = frt; + } + return ft; + } +} diff --git a/tests/1001-1500/1137. n-th-tribonacci-number/sol.go b/tests/1001-1500/1137. n-th-tribonacci-number/sol.go new file mode 100644 index 00000000..d37cdb32 --- /dev/null +++ b/tests/1001-1500/1137. n-th-tribonacci-number/sol.go @@ -0,0 +1,10 @@ +func tribonacci(n int) int { + ft, st, tt := 0, 1, 1 + for i := 1; i <= n; i++ { + frt := ft + st + tt + ft = st + st = tt + tt = frt + } + return ft +} diff --git a/tests/1001-1500/1137. n-th-tribonacci-number/sol.java b/tests/1001-1500/1137. n-th-tribonacci-number/sol.java new file mode 100644 index 00000000..4dd4631c --- /dev/null +++ b/tests/1001-1500/1137. n-th-tribonacci-number/sol.java @@ -0,0 +1,12 @@ +class Solution { + public int tribonacci(int n) { + int ft = 0, st = 1, tt = 1; + for (int i = 1; i <= n; i++) { + int frt = ft + st + tt; + ft = st; + st = tt; + tt = frt; + } + return ft; + } +} diff --git a/tests/1001-1500/1137. n-th-tribonacci-number/sol.kt b/tests/1001-1500/1137. n-th-tribonacci-number/sol.kt new file mode 100644 index 00000000..2b1b6d08 --- /dev/null +++ b/tests/1001-1500/1137. n-th-tribonacci-number/sol.kt @@ -0,0 +1,14 @@ +class Solution { + fun tribonacci(n: Int): Int { + var ft = 0 + var st = 1 + var tt = 1 + for (i in 1..n) { + val frt = ft + st + tt + ft = st + st = tt + tt = frt + } + return ft + } +} diff --git a/tests/1001-1500/1137. n-th-tribonacci-number/sol.py b/tests/1001-1500/1137. n-th-tribonacci-number/sol.py new file mode 100644 index 00000000..d7b5ad9b --- /dev/null +++ b/tests/1001-1500/1137. n-th-tribonacci-number/sol.py @@ -0,0 +1,12 @@ +class Solution: + def tribonacci(self, n): + + ft, st, tt = 0, 1, 1 + + for i in range(1, n + 1): + frt = ft + st + tt + ft = st + st = tt + tt = frt + + return ft diff --git a/tests/1001-1500/1137. n-th-tribonacci-number/sol.py2 b/tests/1001-1500/1137. n-th-tribonacci-number/sol.py2 new file mode 100644 index 00000000..ba1a47df --- /dev/null +++ b/tests/1001-1500/1137. n-th-tribonacci-number/sol.py2 @@ -0,0 +1,9 @@ +class Solution(object): + def tribonacci(self, n): + ft, st, tt = 0, 1, 1 + for i in range(1, n + 1): + frt = ft + st + tt + ft = st + st = tt + tt = frt + return ft diff --git a/tests/1001-1500/1137. n-th-tribonacci-number/sol.rb b/tests/1001-1500/1137. n-th-tribonacci-number/sol.rb new file mode 100644 index 00000000..76d8d786 --- /dev/null +++ b/tests/1001-1500/1137. n-th-tribonacci-number/sol.rb @@ -0,0 +1,12 @@ +# @param {Integer} n +# @return {Integer} +def tribonacci(n) + ft, st, tt = 0, 1, 1 + (1..n).each do |i| + frt = ft + st + tt + ft = st + st = tt + tt = frt + end + ft +end diff --git a/tests/1001-1500/1137. n-th-tribonacci-number/sol.rs b/tests/1001-1500/1137. n-th-tribonacci-number/sol.rs new file mode 100644 index 00000000..d6486763 --- /dev/null +++ b/tests/1001-1500/1137. n-th-tribonacci-number/sol.rs @@ -0,0 +1,14 @@ +impl Solution { + pub fn tribonacci(n: i32) -> i32 { + let mut ft = 0; + let mut st = 1; + let mut tt = 1; + for _ in 1..=n { + let frt = ft + st + tt; + ft = st; + st = tt; + tt = frt; + } + ft + } +} diff --git a/tests/1001-1500/1137. n-th-tribonacci-number/sol.swift b/tests/1001-1500/1137. n-th-tribonacci-number/sol.swift new file mode 100644 index 00000000..787dafbc --- /dev/null +++ b/tests/1001-1500/1137. n-th-tribonacci-number/sol.swift @@ -0,0 +1,12 @@ +class Solution { + func tribonacci(_ n: Int) -> Int { + var ft = 0, st = 1, tt = 1 + for _ in 0..> 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}}; + vector word; + for (char c : target) { + word.push_back(c - 'a'); + } + string s = ""; + int j = 0, k = 0; + if (word[0] % 5 != 0) { + s += string(word[0] / 5, 'D'); + } else { + s += string(word[0] / 5, 'D'); + } + if (word[0] % 5 >= 0) { + s += string(word[0] % 5, 'R'); + } + s += '!'; + for (int i = 1; i < word.size(); i++) { + for (int h = 0; h < arr.size(); h++) { + for (int l = 0; l < arr[h].size(); l++) { + if (arr[h][l] == word[i-1]) j = h; + if (arr[h][l] == word[i]) k = h; + } + } + if (word[i-1] == 25) { + if (j > k) { + s += string(j - k, 'U'); + } else { + s += string(k - j, 'D'); + } + if (word[i] % 5 >= word[i-1] % 5) { + s += string(word[i] % 5 - word[i-1] % 5, 'R'); + } else { + s += string(word[i-1] % 5 - word[i] % 5, 'L'); + } + } else { + if (word[i] % 5 >= word[i-1] % 5) { + s += string(word[i] % 5 - word[i-1] % 5, 'R'); + } else { + s += string(word[i-1] % 5 - word[i] % 5, 'L'); + } + if (j > k) { + s += string(j - k, 'U'); + } else { + s += string(k - j, 'D'); + } + } + s += '!'; + } + return s; + } +}; diff --git a/tests/1001-1500/1138. alphabet-board-path/sol.cs b/tests/1001-1500/1138. alphabet-board-path/sol.cs new file mode 100644 index 00000000..a16af88e --- /dev/null +++ b/tests/1001-1500/1138. alphabet-board-path/sol.cs @@ -0,0 +1,53 @@ +public class Solution { + public string AlphabetBoardPath(string target) { + int[][] arr = new int[][] { new int[] {0,1,2,3,4}, new int[] {5,6,7,8,9}, new int[] {10,11,12,13,14}, new int[] {15,16,17,18,19}, new int[] {20,21,22,23,24}, new int[] {25} }; + int[] word = new int[target.Length]; + for (int i = 0; i < target.Length; i++) { + word[i] = target[i] - 'a'; + } + string s = ""; + int j = 0, k = 0; + if (word[0] % 5 != 0) { + s += new string('D', word[0] / 5); + } else { + s += new string('D', word[0] / 5); + } + if (word[0] % 5 >= 0) { + s += new string('R', word[0] % 5); + } + s += "!"; + for (int i = 1; i < word.Length; i++) { + for (int h = 0; h < arr.Length; h++) { + for (int l = 0; l < arr[h].Length; l++) { + if (arr[h][l] == word[i-1]) j = h; + if (arr[h][l] == word[i]) k = h; + } + } + if (word[i-1] == 25) { + if (j > k) { + s += new string('U', j - k); + } else { + s += new string('D', k - j); + } + if (word[i] % 5 >= word[i-1] % 5) { + s += new string('R', word[i] % 5 - word[i-1] % 5); + } else { + s += new string('L', word[i-1] % 5 - word[i] % 5); + } + } else { + if (word[i] % 5 >= word[i-1] % 5) { + s += new string('R', word[i] % 5 - word[i-1] % 5); + } else { + s += new string('L', word[i-1] % 5 - word[i] % 5); + } + if (j > k) { + s += new string('U', j - k); + } else { + s += new string('D', k - j); + } + } + s += "!"; + } + return s; + } +} diff --git a/tests/1001-1500/1138. alphabet-board-path/sol.dart b/tests/1001-1500/1138. alphabet-board-path/sol.dart new file mode 100644 index 00000000..ed9d7d31 --- /dev/null +++ b/tests/1001-1500/1138. alphabet-board-path/sol.dart @@ -0,0 +1,53 @@ +class Solution { + String alphabetBoardPath(String target) { + int r = 0; + int c = 0; + final buffer = StringBuffer(); + + for (int i = 0; i < target.length; i++) { + int code = target.codeUnitAt(i) - 97; + int nr = code ~/ 5; + int nc = code % 5; + + if (nr == 5) { + while (c > nc) { + buffer.write('L'); + c--; + } + while (c < nc) { + buffer.write('R'); + c++; + } + while (r > nr) { + buffer.write('U'); + r--; + } + while (r < nr) { + buffer.write('D'); + r++; + } + } else { + while (r > nr) { + buffer.write('U'); + r--; + } + while (r < nr) { + buffer.write('D'); + r++; + } + while (c > nc) { + buffer.write('L'); + c--; + } + while (c < nc) { + buffer.write('R'); + c++; + } + } + + buffer.write('!'); + } + + return buffer.toString(); + } +} diff --git a/tests/1001-1500/1138. alphabet-board-path/sol.go b/tests/1001-1500/1138. alphabet-board-path/sol.go new file mode 100644 index 00000000..077d5762 --- /dev/null +++ b/tests/1001-1500/1138. alphabet-board-path/sol.go @@ -0,0 +1,77 @@ +func alphabetBoardPath(target string) string { + arr := [][]int{{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}} + word := make([]int, len(target)) + for i, c := range target { + word[i] = int(c - 'a') + } + s := "" + j, k := 0, 0 + if word[0] % 5 != 0 { + for d := 0; d < word[0]/5; d++ { + s += "D" + } + } else { + for d := 0; d < word[0]/5; d++ { + s += "D" + } + } + if word[0] % 5 >= 0 { + for r := 0; r < word[0]%5; r++ { + s += "R" + } + } + s += "!" + for i := 1; i < len(word); i++ { + for h := 0; h < len(arr); h++ { + for l := 0; l < len(arr[h]); l++ { + if arr[h][l] == word[i-1] { + j = h + } + if arr[h][l] == word[i] { + k = h + } + } + } + if word[i-1] == 25 { + if j > k { + for u := 0; u < j - k; u++ { + s += "U" + } + } else { + for d := 0; d < k - j; d++ { + s += "D" + } + } + if word[i] % 5 >= word[i-1] % 5 { + for r := 0; r < word[i]%5 - word[i-1]%5; r++ { + s += "R" + } + } else { + for l := 0; l < word[i-1]%5 - word[i]%5; l++ { + s += "L" + } + } + } else { + if word[i] % 5 >= word[i-1] % 5 { + for r := 0; r < word[i]%5 - word[i-1]%5; r++ { + s += "R" + } + } else { + for l := 0; l < word[i-1]%5 - word[i]%5; l++ { + s += "L" + } + } + if j > k { + for u := 0; u < j - k; u++ { + s += "U" + } + } else { + for d := 0; d < k - j; d++ { + s += "D" + } + } + } + s += "!" + } + return s +} diff --git a/tests/1001-1500/1138. alphabet-board-path/sol.java b/tests/1001-1500/1138. alphabet-board-path/sol.java new file mode 100644 index 00000000..dee695d1 --- /dev/null +++ b/tests/1001-1500/1138. alphabet-board-path/sol.java @@ -0,0 +1,53 @@ +class Solution { + public String alphabetBoardPath(String target) { + int[][] 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}}; + int[] word = new int[target.length()]; + for (int i = 0; i < target.length(); i++) { + word[i] = target.charAt(i) - 'a'; + } + StringBuilder s = new StringBuilder(); + int j = 0, k = 0; + if (word[0] % 5 != 0) { + for (int d = 0; d < word[0] / 5; d++) s.append('D'); + } else { + for (int d = 0; d < word[0] / 5; d++) s.append('D'); + } + if (word[0] % 5 >= 0) { + for (int r = 0; r < word[0] % 5; r++) s.append('R'); + } + s.append('!'); + for (int i = 1; i < word.length; i++) { + for (int h = 0; h < arr.length; h++) { + for (int l = 0; l < arr[h].length; l++) { + if (arr[h][l] == word[i-1]) j = h; + if (arr[h][l] == word[i]) k = h; + } + } + if (word[i-1] == 25) { + if (j > k) { + for (int u = 0; u < j - k; u++) s.append('U'); + } else { + for (int d = 0; d < k - j; d++) s.append('D'); + } + if (word[i] % 5 >= word[i-1] % 5) { + for (int r = 0; r < word[i] % 5 - word[i-1] % 5; r++) s.append('R'); + } else { + for (int l = 0; l < word[i-1] % 5 - word[i] % 5; l++) s.append('L'); + } + } else { + if (word[i] % 5 >= word[i-1] % 5) { + for (int r = 0; r < word[i] % 5 - word[i-1] % 5; r++) s.append('R'); + } else { + for (int l = 0; l < word[i-1] % 5 - word[i] % 5; l++) s.append('L'); + } + if (j > k) { + for (int u = 0; u < j - k; u++) s.append('U'); + } else { + for (int d = 0; d < k - j; d++) s.append('D'); + } + } + s.append('!'); + } + return s.toString(); + } +} diff --git a/tests/1001-1500/1138. alphabet-board-path/sol.kt b/tests/1001-1500/1138. alphabet-board-path/sol.kt new file mode 100644 index 00000000..219b0aff --- /dev/null +++ b/tests/1001-1500/1138. alphabet-board-path/sol.kt @@ -0,0 +1,51 @@ +class Solution { + fun alphabetBoardPath(target: String): String { + val arr = arrayOf(intArrayOf(0,1,2,3,4), intArrayOf(5,6,7,8,9), intArrayOf(10,11,12,13,14), intArrayOf(15,16,17,18,19), intArrayOf(20,21,22,23,24), intArrayOf(25)) + val word = target.map { it.code - 'a'.code } + val s = StringBuilder() + var j = 0 + var k = 0 + if (word[0] % 5 != 0) { + s.append("D".repeat(word[0] / 5)) + } else { + s.append("D".repeat(word[0] / 5)) + } + if (word[0] % 5 >= 0) { + s.append("R".repeat(word[0] % 5)) + } + s.append('!') + for (i in 1 until word.size) { + for (h in arr.indices) { + for (l in arr[h].indices) { + if (arr[h][l] == word[i-1]) j = h + if (arr[h][l] == word[i]) k = h + } + } + if (word[i-1] == 25) { + if (j > k) { + s.append("U".repeat(j - k)) + } else { + s.append("D".repeat(k - j)) + } + if (word[i] % 5 >= word[i-1] % 5) { + s.append("R".repeat(word[i] % 5 - word[i-1] % 5)) + } else { + s.append("L".repeat(word[i-1] % 5 - word[i] % 5)) + } + } else { + if (word[i] % 5 >= word[i-1] % 5) { + s.append("R".repeat(word[i] % 5 - word[i-1] % 5)) + } else { + s.append("L".repeat(word[i-1] % 5 - word[i] % 5)) + } + if (j > k) { + s.append("U".repeat(j - k)) + } else { + s.append("D".repeat(k - j)) + } + } + s.append('!') + } + return s.toString() + } +} diff --git a/tests/1001-1500/1138. alphabet-board-path/sol.py b/tests/1001-1500/1138. alphabet-board-path/sol.py new file mode 100644 index 00000000..1e7d02b3 --- /dev/null +++ b/tests/1001-1500/1138. alphabet-board-path/sol.py @@ -0,0 +1,57 @@ +class Solution: + def alphabetBoardPath(self, target: str) -> str: + 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], + ] + word = [] + for i in target: + word.append(ord(i) - 97) + s = "" + j = k = 0, 0 + if word[0] % 5 != 0: + s += "D" * (word[0] // 5) + + else: + s += "D" * (word[0] // 5) + if word[0] % 5 >= 0: + s += "R" * (word[0] % 5) + + s += "!" + for i in range(1, len(word)): + for h in range(len(arr)): + for l in range(len(arr[h])): + if arr[h][l] == word[i - 1]: + j = h + if arr[h][l] == word[i]: + k = h + + if word[i - 1] == 25: + if j > k: + s += "U" * (j - k) + else: + s += "D" * (k - j) + + if word[i] % 5 >= word[i - 1] % 5: + s += "R" * (word[i] % 5 - word[i - 1] % 5) + else: + s += "L" * (word[i - 1] % 5 - word[i] % 5) + + else: + if word[i] % 5 >= word[i - 1] % 5: + s += "R" * (word[i] % 5 - word[i - 1] % 5) + else: + s += "L" * (word[i - 1] % 5 - word[i] % 5) + + if j > k: + s += "U" * (j - k) + else: + s += "D" * (k - j) + + s += "!" + print(word) + return s diff --git a/tests/1001-1500/1138. alphabet-board-path/sol.py2 b/tests/1001-1500/1138. alphabet-board-path/sol.py2 new file mode 100644 index 00000000..a19818af --- /dev/null +++ b/tests/1001-1500/1138. alphabet-board-path/sol.py2 @@ -0,0 +1,46 @@ +class Solution(object): + def alphabetBoardPath(self, target): + """ + :type target: str + :rtype: str + """ + 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]] + word=[] + for i in target: + word.append(ord(i)-97) + s='' + j=k=0 + if word[0]%5!=0: + s+='D'*(word[0]//5) + else: + s+='D'*(word[0]//5) + if word[0]%5>=0: + s+='R'*(word[0]%5) + s+='!' + for i in range(1,len(word)): + for h in range(len(arr)): + for l in range(len(arr[h])): + if arr[h][l] == word[i-1]: + j = h + if arr[h][l] == word[i]: + k = h + if word[i-1] == 25: + if j > k: + s += 'U' * (j - k) + else: + s += 'D' * (k - j) + if word[i] % 5 >= word[i-1] % 5: + s += 'R' * (word[i] % 5 - word[i-1] % 5) + else: + s += 'L' * (word[i-1] % 5 - word[i] % 5) + else: + if word[i] % 5 >= word[i-1] % 5: + s += 'R' * (word[i] % 5 - word[i-1] % 5) + else: + s += 'L' * (word[i-1] % 5 - word[i] % 5) + if j > k: + s += 'U' * (j - k) + else: + s += 'D' * (k - j) + s+='!' + return s diff --git a/tests/1001-1500/1138. alphabet-board-path/sol.rb b/tests/1001-1500/1138. alphabet-board-path/sol.rb new file mode 100644 index 00000000..f36964c6 --- /dev/null +++ b/tests/1001-1500/1138. alphabet-board-path/sol.rb @@ -0,0 +1,54 @@ +# @param {String} target +# @return {String} +def alphabet_board_path(target) + 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]] + word = target.chars.map { |c| c.ord - 97 } + s = '' + j = k = 0 + if word[0] % 5 != 0 + s += 'D' * (word[0] / 5) + else + s += 'D' * (word[0] / 5) + end + if word[0] % 5 >= 0 + s += 'R' * (word[0] % 5) + end + s += '!' + (1...word.length).each do |i| + arr.each_with_index do |row, h| + row.each_with_index do |val, l| + if val == word[i-1] + j = h + end + if val == word[i] + k = h + end + end + end + if word[i-1] == 25 + if j > k + s += 'U' * (j - k) + else + s += 'D' * (k - j) + end + if word[i] % 5 >= word[i-1] % 5 + s += 'R' * (word[i] % 5 - word[i-1] % 5) + else + s += 'L' * (word[i-1] % 5 - word[i] % 5) + end + else + if word[i] % 5 >= word[i-1] % 5 + s += 'R' * (word[i] % 5 - word[i-1] % 5) + else + s += 'L' * (word[i-1] % 5 - word[i] % 5) + end + if j > k + s += 'U' * (j - k) + else + s += 'D' * (k - j) + end + end + s += '!' + end + return s +end diff --git a/tests/1001-1500/1138. alphabet-board-path/sol.rs b/tests/1001-1500/1138. alphabet-board-path/sol.rs new file mode 100644 index 00000000..bec00fbc --- /dev/null +++ b/tests/1001-1500/1138. alphabet-board-path/sol.rs @@ -0,0 +1,51 @@ +impl Solution { + pub fn alphabet_board_path(target: String) -> String { + let arr: Vec> = vec![vec![0,1,2,3,4],vec![5,6,7,8,9],vec![10,11,12,13,14],vec![15,16,17,18,19],vec![20,21,22,23,24],vec![25]]; + let word: Vec = target.chars().map(|c| c as i32 - 'a' as i32).collect(); + let mut s = String::new(); + let mut j: i32 = 0; + let mut k: i32 = 0; + if word[0] % 5 != 0 { + s.push_str(&"D".repeat((word[0] / 5) as usize)); + } else { + s.push_str(&"D".repeat((word[0] / 5) as usize)); + } + if word[0] % 5 >= 0 { + s.push_str(&"R".repeat((word[0] % 5) as usize)); + } + s.push('!'); + for i in 1..word.len() { + for h in 0..arr.len() { + for l in 0..arr[h].len() { + if arr[h][l] == word[i-1] { j = h as i32; } + if arr[h][l] == word[i] { k = h as i32; } + } + } + if word[i-1] == 25 { + if j > k { + s.push_str(&"U".repeat((j - k) as usize)); + } else { + s.push_str(&"D".repeat((k - j) as usize)); + } + if word[i] % 5 >= word[i-1] % 5 { + s.push_str(&"R".repeat((word[i] % 5 - word[i-1] % 5) as usize)); + } else { + s.push_str(&"L".repeat((word[i-1] % 5 - word[i] % 5) as usize)); + } + } else { + if word[i] % 5 >= word[i-1] % 5 { + s.push_str(&"R".repeat((word[i] % 5 - word[i-1] % 5) as usize)); + } else { + s.push_str(&"L".repeat((word[i-1] % 5 - word[i] % 5) as usize)); + } + if j > k { + s.push_str(&"U".repeat((j - k) as usize)); + } else { + s.push_str(&"D".repeat((k - j) as usize)); + } + } + s.push('!'); + } + s + } +} diff --git a/tests/1001-1500/1138. alphabet-board-path/sol.swift b/tests/1001-1500/1138. alphabet-board-path/sol.swift new file mode 100644 index 00000000..66e3e037 --- /dev/null +++ b/tests/1001-1500/1138. alphabet-board-path/sol.swift @@ -0,0 +1,50 @@ +class Solution { + func alphabetBoardPath(_ target: String) -> String { + let arr: [[Int]] = [[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]] + let word = target.map { Int($0.asciiValue! - 97) } + var s = "" + var j = 0, k = 0 + if word[0] % 5 != 0 { + s += String(repeating: "D", count: word[0] / 5) + } else { + s += String(repeating: "D", count: word[0] / 5) + } + if word[0] % 5 >= 0 { + s += String(repeating: "R", count: word[0] % 5) + } + s += "!" + for i in 1.. k { + s += String(repeating: "U", count: j - k) + } else { + s += String(repeating: "D", count: k - j) + } + if word[i] % 5 >= word[i-1] % 5 { + s += String(repeating: "R", count: word[i] % 5 - word[i-1] % 5) + } else { + s += String(repeating: "L", count: word[i-1] % 5 - word[i] % 5) + } + } else { + if word[i] % 5 >= word[i-1] % 5 { + s += String(repeating: "R", count: word[i] % 5 - word[i-1] % 5) + } else { + s += String(repeating: "L", count: word[i-1] % 5 - word[i] % 5) + } + if j > k { + s += String(repeating: "U", count: j - k) + } else { + s += String(repeating: "D", count: k - j) + } + } + s += "!" + } + return s + } +} diff --git a/tests/1001-1500/1138. alphabet-board-path/sol.ts b/tests/1001-1500/1138. alphabet-board-path/sol.ts new file mode 100644 index 00000000..ca9667ef --- /dev/null +++ b/tests/1001-1500/1138. alphabet-board-path/sol.ts @@ -0,0 +1,56 @@ +function alphabetBoardPath(target: string): string { + const arr: number[][] = [ + [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], + ]; + const word: number[] = target.split("").map((c) => c.charCodeAt(0) - 97); + let s: string = ""; + let j: number = 0, + k: number = 0; + if (word[0] % 5 != 0) { + s += "D".repeat((word[0] / 5) | 0); + } else { + s += "D".repeat((word[0] / 5) | 0); + } + if (word[0] % 5 >= 0) { + s += "R".repeat(word[0] % 5); + } + s += "!"; + for (let i = 1; i < word.length; i++) { + for (let h = 0; h < arr.length; h++) { + for (let l = 0; l < arr[h].length; l++) { + if (arr[h][l] == word[i - 1]) j = h; + if (arr[h][l] == word[i]) k = h; + } + } + if (word[i - 1] == 25) { + if (j > k) { + s += "U".repeat(j - k); + } else { + s += "D".repeat(k - j); + } + if (word[i] % 5 >= word[i - 1] % 5) { + s += "R".repeat((word[i] % 5) - (word[i - 1] % 5)); + } else { + s += "L".repeat((word[i - 1] % 5) - (word[i] % 5)); + } + } else { + if (word[i] % 5 >= word[i - 1] % 5) { + s += "R".repeat((word[i] % 5) - (word[i - 1] % 5)); + } else { + s += "L".repeat((word[i - 1] % 5) - (word[i] % 5)); + } + if (j > k) { + s += "U".repeat(j - k); + } else { + s += "D".repeat(k - j); + } + } + s += "!"; + } + return s; +} diff --git a/tests/1001-1500/1139. largest-1-bordered-square/manifest.yaml b/tests/1001-1500/1139. largest-1-bordered-square/manifest.yaml new file mode 100644 index 00000000..f5ebc453 --- /dev/null +++ b/tests/1001-1500/1139. largest-1-bordered-square/manifest.yaml @@ -0,0 +1,459 @@ +entry: + id: 1139 + title: "largest-1-bordered-square" + params: + grid: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().largest1BorderedSquare({grid})" + rust: "Solution::largest1_bordered_square({grid})" + python3: "Solution().largest1BorderedSquare({grid})" + python2: "Solution().largest1BorderedSquare({grid})" + ruby: "largest1_bordered_square({grid})" + java: "new Solution().largest1BorderedSquare({grid})" + csharp: "new Solution().Largest1BorderedSquare({grid})" + kotlin: "Solution().largest1BorderedSquare({grid})" + go: "largest1BorderedSquare({grid})" + dart: "Solution().largest1BorderedSquare({grid})" + swift: "Solution().largest1BorderedSquare({grid})" + typescript: "largest1BorderedSquare({grid})" + +judge: + type: "exact" + +limits: + time_ms: 700 + memory_mb: 300 + +oracle: + python3: + call: "Checker().largest1BorderedSquare(grid, {result})" + checker: | + class Checker: + def largest1BorderedSquare(self, grid, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if not isinstance(grid, list) or not grid or not isinstance(grid[0], list) or not grid[0]: + return False + rows, cols = len(grid), len(grid[0]) + if rows > 100 or cols > 100 or any(len(row) != cols for row in grid): + return False + if any(cell not in (0, 1) for row in grid for cell in row): + return False + horizontal = [[0] * cols for _ in range(rows)] + vertical = [[0] * cols for _ in range(rows)] + for r in range(rows): + for c in range(cols): + if grid[r][c] == 1: + horizontal[r][c] = 1 + (horizontal[r][c - 1] if c else 0) + vertical[r][c] = 1 + (vertical[r - 1][c] if r else 0) + for size in range(min(rows, cols), 0, -1): + for bottom in range(size - 1, rows): + for right in range(size - 1, cols): + top = bottom - size + 1 + left = right - size + 1 + if (horizontal[bottom][right] >= size and + horizontal[top][right] >= size and + vertical[bottom][right] >= size and + vertical[bottom][left] >= size): + return result == size * size + return result == 0 + +seed: 113900 + +tests: + - name: "single_one" + in: + grid: + elemType: "int" + value: + - [1] + out: 1 + - name: "single_zero" + in: + grid: + elemType: "int" + value: + - [0] + out: 0 + - name: "example_full_border" + in: + grid: + elemType: "int" + value: + - [1, 1, 1] + - [1, 0, 1] + - [1, 1, 1] + out: 9 + - name: "example_single_row" + in: + grid: + elemType: "int" + value: + - [1, 1, 0, 0] + out: 1 + - name: "full_two_by_two" + in: + grid: + elemType: "int" + value: + - [1, 1] + - [1, 1] + out: 4 + - name: "diagonal_only" + in: + grid: + elemType: "int" + value: + - [1, 0] + - [0, 1] + out: 1 + - name: "all_zero_rectangle" + in: + grid: + elemType: "int" + value: + - [0, 0, 0] + - [0, 0, 0] + out: 0 + - name: "checkerboard_three" + in: + grid: + elemType: "int" + value: + - [1, 0, 1] + - [0, 1, 0] + - [1, 0, 1] + out: 1 + - name: "one_row_all_one" + in: + grid: + elemType: "int" + value: + - [1, 1, 1, 1] + out: 1 + - name: "one_column_all_one" + in: + grid: + elemType: "int" + value: + - [1] + - [1] + - [1] + - [1] + out: 1 + - name: "three_by_three_missing_corner" + in: + grid: + elemType: "int" + value: + - [1, 1, 1] + - [0, 0, 1] + - [1, 1, 1] + out: 1 + - name: "two_by_three_full_rows" + in: + grid: + elemType: "int" + value: + - [1, 1, 1] + - [1, 1, 1] + out: 4 + - name: "embedded_two_square" + in: + grid: + elemType: "int" + value: + - [1, 0, 1, 1] + - [1, 0, 1, 1] + - [1, 1, 1, 1] + out: 4 + - name: "partial_corner_square" + in: + grid: + elemType: "int" + value: + - [1, 1, 0] + - [1, 0, 0] + - [1, 1, 1] + out: 1 + - name: "full_four_border" + in: + grid: + elemType: "int" + value: + - [1, 1, 1, 1] + - [1, 0, 0, 1] + - [1, 0, 0, 1] + - [1, 1, 1, 1] + out: 16 + - name: "three_by_four_full" + in: + grid: + elemType: "int" + value: + - [1, 1, 1, 1] + - [1, 1, 1, 1] + - [1, 1, 1, 1] + out: 9 + - name: "vertical_strip_in_rectangle" + in: + grid: + elemType: "int" + value: + - [0, 1, 1] + - [0, 1, 1] + - [0, 1, 1] + out: 4 + - name: "left_l_shape" + in: + grid: + elemType: "int" + value: + - [1, 0, 0] + - [1, 1, 1] + - [1, 0, 1] + out: 1 + - name: "offset_four_square" + in: + grid: + elemType: "int" + value: + - [1, 1, 0, 1] + - [1, 1, 1, 1] + - [0, 1, 1, 1] + out: 4 + - name: "bottom_right_square" + in: + grid: + elemType: "int" + value: + - [0, 0, 1, 1] + - [1, 1, 1, 1] + - [1, 1, 1, 1] + out: 4 + - name: "square_with_zero_bottom_row" + in: + grid: + elemType: "int" + value: + - [1, 1, 1] + - [1, 0, 1] + - [1, 1, 1] + - [0, 0, 0] + out: 9 + - name: "square_at_top" + in: + grid: + elemType: "int" + value: + - [1, 1, 1] + - [1, 1, 1] + - [0, 0, 0] + - [1, 1, 1] + out: 4 + - name: "alternating_columns" + in: + grid: + elemType: "int" + value: + - [1, 0, 1, 0, 1] + - [1, 1, 1, 1, 1] + - [1, 0, 1, 0, 1] + out: 1 + - name: "three_square_left" + in: + grid: + elemType: "int" + value: + - [1, 1, 1, 0, 0] + - [1, 0, 1, 0, 0] + - [1, 1, 1, 0, 0] + out: 9 + - name: "two_by_two_stacked" + in: + grid: + elemType: "int" + value: + - [1, 1] + - [1, 1] + - [1, 1] + out: 4 + - name: "repeated_two_squares" + in: + grid: + elemType: "int" + value: + - [1, 0, 1] + - [1, 1, 1] + - [1, 0, 1] + - [1, 1, 1] + out: 9 + - name: "noisy_four_by_four" + in: + grid: + elemType: "int" + value: + - [0, 1, 1, 1] + - [1, 1, 0, 1] + - [1, 1, 1, 1] + - [1, 0, 1, 1] + out: 9 + - name: "hollow_five_border" + in: + grid: + elemType: "int" + value: + - [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] + out: 25 + - name: "separate_two_blocks" + in: + grid: + elemType: "int" + value: + - [1, 1, 0, 0] + - [1, 1, 0, 0] + - [0, 0, 1, 1] + - [0, 0, 1, 1] + out: 4 + - name: "center_hole_three" + in: + grid: + elemType: "int" + value: + - [1, 1, 1] + - [0, 1, 0] + - [1, 1, 1] + out: 1 + - name: "top_right_four_border" + in: + grid: + elemType: "int" + value: + - [1, 1, 1, 1, 1] + - [0, 0, 0, 0, 1] + - [1, 1, 1, 1, 1] + out: 1 + - name: "noisy_five" + in: + grid: + elemType: "int" + value: + - [1, 0, 1, 1, 1] + - [1, 1, 1, 0, 1] + - [1, 1, 1, 1, 1] + - [1, 0, 0, 0, 1] + out: 9 + - name: "bottom_pattern" + in: + grid: + elemType: "int" + value: + - [0, 0, 0, 1] + - [1, 1, 1, 1] + - [1, 0, 0, 1] + - [1, 1, 1, 1] + out: 1 + - name: "outer_border_gap_leaves_four_square" + in: + grid: + elemType: "int" + value: + - [1, 1, 0, 1, 1] + - [1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1] + out: 16 + - name: "generated_small" + seed: 113901 + in: + grid: + gen: "array" + len: + gen: "int" + min: 1 + max: 8 + of: + gen: "array" + len: 8 + of: + gen: "int" + min: 0 + max: 1 + - name: "generated_medium" + seed: 113902 + in: + grid: + gen: "array" + len: + gen: "int" + min: 10 + max: 25 + of: + gen: "array" + len: 20 + of: + gen: "int" + min: 0 + max: 1 + - name: "generated_wide" + seed: 113903 + in: + grid: + gen: "array" + len: 20 + of: + gen: "array" + len: 30 + of: + gen: "int" + min: 0 + max: 1 + - name: "generated_maximum_square_a" + seed: 113904 + in: + grid: + gen: "array" + len: 100 + of: + gen: "array" + len: 100 + of: + gen: "int" + min: 0 + max: 1 + - name: "generated_maximum_square_b" + seed: 113905 + in: + grid: + gen: "array" + len: 100 + of: + gen: "array" + len: 100 + of: + gen: "int" + min: 0 + max: 1 + - name: "generated_near_maximum_rectangle" + seed: 113906 + in: + grid: + gen: "array" + len: 99 + of: + gen: "array" + len: 100 + of: + gen: "int" + min: 0 + max: 1 diff --git a/tests/1001-1500/1139. largest-1-bordered-square/sol.cpp b/tests/1001-1500/1139. largest-1-bordered-square/sol.cpp new file mode 100644 index 00000000..91a4c4e1 --- /dev/null +++ b/tests/1001-1500/1139. largest-1-bordered-square/sol.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int largest1BorderedSquare(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + vector> h(m, vector(n, 0)); + vector> v(m, vector(n, 0)); + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j]) { + h[i][j] = (j == 0 ? 0 : h[i][j-1]) + 1; + v[i][j] = (i == 0 ? 0 : v[i-1][j]) + 1; + } + } + } + int ans = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + int sz = min(h[i][j], v[i][j]); + for (int k = sz; k >= 1; k--) { + if (h[i-k+1][j] >= k && v[i][j-k+1] >= k) { + ans = max(ans, k); + break; + } + } + } + } + return ans * ans; + } +}; diff --git a/tests/1001-1500/1139. largest-1-bordered-square/sol.cs b/tests/1001-1500/1139. largest-1-bordered-square/sol.cs new file mode 100644 index 00000000..dd2af7f9 --- /dev/null +++ b/tests/1001-1500/1139. largest-1-bordered-square/sol.cs @@ -0,0 +1,32 @@ +public class Solution { + public int Largest1BorderedSquare(int[][] grid) { + int m = grid.Length, n = grid[0].Length; + int[][] h = new int[m][]; + int[][] v = new int[m][]; + for (int i = 0; i < m; i++) { + h[i] = new int[n]; + v[i] = new int[n]; + } + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == 1) { + h[i][j] = (j == 0 ? 0 : h[i][j-1]) + 1; + v[i][j] = (i == 0 ? 0 : v[i-1][j]) + 1; + } + } + } + int ans = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + int sz = Math.Min(h[i][j], v[i][j]); + for (int k = sz; k >= 1; k--) { + if (h[i-k+1][j] >= k && v[i][j-k+1] >= k) { + ans = Math.Max(ans, k); + break; + } + } + } + } + return ans * ans; + } +} diff --git a/tests/1001-1500/1139. largest-1-bordered-square/sol.dart b/tests/1001-1500/1139. largest-1-bordered-square/sol.dart new file mode 100644 index 00000000..64ba7e17 --- /dev/null +++ b/tests/1001-1500/1139. largest-1-bordered-square/sol.dart @@ -0,0 +1,37 @@ +class Solution { + int largest1BorderedSquare(List> grid) { + final rows = grid.length; + final cols = grid[0].length; + + final right = List.generate(rows, (_) => List.filled(cols, 0)); + final down = List.generate(rows, (_) => List.filled(cols, 0)); + + for (var r = rows - 1; r >= 0; r--) { + for (var c = cols - 1; c >= 0; c--) { + if (grid[r][c] == 1) { + right[r][c] = 1 + (c + 1 < cols ? right[r][c + 1] : 0); + down[r][c] = 1 + (r + 1 < rows ? down[r + 1][c] : 0); + } + } + } + + final maxSize = rows < cols ? rows : cols; + for (var size = maxSize; size >= 1; size--) { + final edge = size - 1; + for (var top = 0; top + edge < rows; top++) { + final bottom = top + edge; + for (var left = 0; left + edge < cols; left++) { + final rightCol = left + edge; + if (right[top][left] >= size && + right[bottom][left] >= size && + down[top][left] >= size && + down[top][rightCol] >= size) { + return size * size; + } + } + } + } + + return 0; + } +} diff --git a/tests/1001-1500/1139. largest-1-bordered-square/sol.go b/tests/1001-1500/1139. largest-1-bordered-square/sol.go new file mode 100644 index 00000000..feca3135 --- /dev/null +++ b/tests/1001-1500/1139. largest-1-bordered-square/sol.go @@ -0,0 +1,43 @@ +func largest1BorderedSquare(grid [][]int) int { + m, n := len(grid), len(grid[0]) + h := make([][]int, m) + v := make([][]int, m) + for i := 0; i < m; i++ { + h[i] = make([]int, n) + v[i] = make([]int, n) + } + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if grid[i][j] == 1 { + if j == 0 { + h[i][j] = 1 + } else { + h[i][j] = h[i][j-1] + 1 + } + if i == 0 { + v[i][j] = 1 + } else { + v[i][j] = v[i-1][j] + 1 + } + } + } + } + ans := 0 + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + sz := h[i][j] + if v[i][j] < sz { + sz = v[i][j] + } + for k := sz; k >= 1; k-- { + if h[i-k+1][j] >= k && v[i][j-k+1] >= k { + if k > ans { + ans = k + } + break + } + } + } + } + return ans * ans +} diff --git a/tests/1001-1500/1139. largest-1-bordered-square/sol.java b/tests/1001-1500/1139. largest-1-bordered-square/sol.java new file mode 100644 index 00000000..2e854574 --- /dev/null +++ b/tests/1001-1500/1139. largest-1-bordered-square/sol.java @@ -0,0 +1,28 @@ +class Solution { + public int largest1BorderedSquare(int[][] grid) { + int m = grid.length, n = grid[0].length; + int[][] h = new int[m][n]; + int[][] v = new int[m][n]; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == 1) { + h[i][j] = (j == 0 ? 0 : h[i][j-1]) + 1; + v[i][j] = (i == 0 ? 0 : v[i-1][j]) + 1; + } + } + } + int ans = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + int sz = Math.min(h[i][j], v[i][j]); + for (int k = sz; k >= 1; k--) { + if (h[i-k+1][j] >= k && v[i][j-k+1] >= k) { + ans = Math.max(ans, k); + break; + } + } + } + } + return ans * ans; + } +} diff --git a/tests/1001-1500/1139. largest-1-bordered-square/sol.kt b/tests/1001-1500/1139. largest-1-bordered-square/sol.kt new file mode 100644 index 00000000..eeb13837 --- /dev/null +++ b/tests/1001-1500/1139. largest-1-bordered-square/sol.kt @@ -0,0 +1,29 @@ +class Solution { + fun largest1BorderedSquare(grid: Array): Int { + val m = grid.size + val n = grid[0].size + val h = Array(m) { IntArray(n) } + val v = Array(m) { IntArray(n) } + for (i in 0 until m) { + for (j in 0 until n) { + if (grid[i][j] == 1) { + h[i][j] = (if (j == 0) 0 else h[i][j-1]) + 1 + v[i][j] = (if (i == 0) 0 else v[i-1][j]) + 1 + } + } + } + var ans = 0 + for (i in 0 until m) { + for (j in 0 until n) { + val sz = minOf(h[i][j], v[i][j]) + for (k in sz downTo 1) { + if (h[i-k+1][j] >= k && v[i][j-k+1] >= k) { + ans = maxOf(ans, k) + break + } + } + } + } + return ans * ans + } +} diff --git a/tests/1001-1500/1139. largest-1-bordered-square/sol.py b/tests/1001-1500/1139. largest-1-bordered-square/sol.py new file mode 100644 index 00000000..59cebc20 --- /dev/null +++ b/tests/1001-1500/1139. largest-1-bordered-square/sol.py @@ -0,0 +1,19 @@ +from itertools import accumulate, product + + +class Solution: + def largest1BorderedSquare(self, g: List[List[int]]) -> int: + f = lambda g: [[*accumulate(r, lambda q, v: v * -~q)] for r in g] + h, v = f(g), [*zip(*f(zip(*g)))] + return ( + max( + ( + size + for i, j in product(range(len(g)), range(len(g[0]))) + for size in range(1, min(h[i][j], v[i][j]) + 1) + if h[i - size + 1][j] >= size <= v[i][j - size + 1] + ), + default=0, + ) + ** 2 + ) diff --git a/tests/1001-1500/1139. largest-1-bordered-square/sol.py2 b/tests/1001-1500/1139. largest-1-bordered-square/sol.py2 new file mode 100644 index 00000000..a22b2ec8 --- /dev/null +++ b/tests/1001-1500/1139. largest-1-bordered-square/sol.py2 @@ -0,0 +1,23 @@ +class Solution(object): + def largest1BorderedSquare(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + m, n = len(grid), len(grid[0]) + h = [[0] * n for _ in range(m)] + v = [[0] * n for _ in range(m)] + for i in range(m): + for j in range(n): + if grid[i][j]: + h[i][j] = (h[i][j-1] + 1) if j else 1 + v[i][j] = (v[i-1][j] + 1) if i else 1 + ans = 0 + for i in range(m): + for j in range(n): + sz = min(h[i][j], v[i][j]) + for k in range(sz, 0, -1): + if h[i-k+1][j] >= k and v[i][j-k+1] >= k: + ans = max(ans, k) + break + return ans * ans diff --git a/tests/1001-1500/1139. largest-1-bordered-square/sol.rb b/tests/1001-1500/1139. largest-1-bordered-square/sol.rb new file mode 100644 index 00000000..0766070c --- /dev/null +++ b/tests/1001-1500/1139. largest-1-bordered-square/sol.rb @@ -0,0 +1,29 @@ +# @param {Integer[][]} grid +# @return {Integer} +def largest1_bordered_square(grid) + m = grid.size + n = grid[0].size + h = Array.new(m) { Array.new(n, 0) } + v = Array.new(m) { Array.new(n, 0) } + (0...m).each do |i| + (0...n).each do |j| + if grid[i][j] == 1 + h[i][j] = j == 0 ? 1 : h[i][j-1] + 1 + v[i][j] = i == 0 ? 1 : v[i-1][j] + 1 + end + end + end + ans = 0 + (0...m).each do |i| + (0...n).each do |j| + sz = [h[i][j], v[i][j]].min + (1..sz).reverse_each do |k| + if h[i-k+1][j] >= k && v[i][j-k+1] >= k + ans = [ans, k].max + break + end + end + end + end + ans * ans +end diff --git a/tests/1001-1500/1139. largest-1-bordered-square/sol.rs b/tests/1001-1500/1139. largest-1-bordered-square/sol.rs new file mode 100644 index 00000000..e4560075 --- /dev/null +++ b/tests/1001-1500/1139. largest-1-bordered-square/sol.rs @@ -0,0 +1,29 @@ +impl Solution { + pub fn largest1_bordered_square(grid: Vec>) -> i32 { + let m = grid.len(); + let n = grid[0].len(); + let mut h = vec![vec![0; n]; m]; + let mut v = vec![vec![0; n]; m]; + for i in 0..m { + for j in 0..n { + if grid[i][j] == 1 { + h[i][j] = if j == 0 { 1 } else { h[i][j-1] + 1 }; + v[i][j] = if i == 0 { 1 } else { v[i-1][j] + 1 }; + } + } + } + let mut ans = 0; + for i in 0..m { + for j in 0..n { + let sz = h[i][j].min(v[i][j]); + for k in (1..=sz).rev() { + if h[i-k+1][j] >= k && v[i][j-k+1] >= k { + ans = ans.max(k); + break; + } + } + } + } + (ans * ans) as i32 + } +} diff --git a/tests/1001-1500/1139. largest-1-bordered-square/sol.swift b/tests/1001-1500/1139. largest-1-bordered-square/sol.swift new file mode 100644 index 00000000..30fa7c7e --- /dev/null +++ b/tests/1001-1500/1139. largest-1-bordered-square/sol.swift @@ -0,0 +1,31 @@ +class Solution { + func largest1BorderedSquare(_ grid: [[Int]]) -> Int { + let m = grid.count + let n = grid[0].count + var h = Array(repeating: Array(repeating: 0, count: n), count: m) + var v = Array(repeating: Array(repeating: 0, count: n), count: m) + for i in 0.. 0 { + for k in stride(from: sz, through: 1, by: -1) { + if h[i-k+1][j] >= k && v[i][j-k+1] >= k { + ans = max(ans, k) + break + } + } + } + } + } + return ans * ans + } +} diff --git a/tests/1001-1500/1139. largest-1-bordered-square/sol.ts b/tests/1001-1500/1139. largest-1-bordered-square/sol.ts new file mode 100644 index 00000000..8e9ebbef --- /dev/null +++ b/tests/1001-1500/1139. largest-1-bordered-square/sol.ts @@ -0,0 +1,27 @@ +function largest1BorderedSquare(grid: number[][]): number { + const m = grid.length, + n = grid[0].length; + const h: number[][] = Array.from({ length: m }, () => Array(n).fill(0)); + const v: number[][] = Array.from({ length: m }, () => Array(n).fill(0)); + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + if (grid[i][j] === 1) { + h[i][j] = (j === 0 ? 0 : h[i][j - 1]) + 1; + v[i][j] = (i === 0 ? 0 : v[i - 1][j]) + 1; + } + } + } + let ans = 0; + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + const sz = Math.min(h[i][j], v[i][j]); + for (let k = sz; k >= 1; k--) { + if (h[i - k + 1][j] >= k && v[i][j - k + 1] >= k) { + ans = Math.max(ans, k); + break; + } + } + } + } + return ans * ans; +} diff --git a/tests/1001-1500/1140. stone-game-ii/manifest.yaml b/tests/1001-1500/1140. stone-game-ii/manifest.yaml new file mode 100644 index 00000000..39d9e56a --- /dev/null +++ b/tests/1001-1500/1140. stone-game-ii/manifest.yaml @@ -0,0 +1,261 @@ +entry: + id: 1140 + title: "stone-game-ii" + params: + piles: + type: array + items: + type: int + call: + cpp: "Solution().stoneGameII({piles})" + rust: "Solution::stone_game_ii({piles})" + python3: "Solution().stoneGameII({piles})" + python2: "Solution().stoneGameII({piles})" + ruby: "stone_game_ii({piles})" + java: "new Solution().stoneGameII({piles})" + csharp: "new Solution().StoneGameII({piles})" + kotlin: "Solution().stoneGameII({piles})" + go: "stoneGameII({piles})" + dart: "Solution().stoneGameII({piles})" + swift: "Solution().stoneGameII({piles})" + typescript: "stoneGameII({piles})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().stoneGameII(piles, {result})" + checker: | + class Checker: + def stoneGameII(self, piles, result): + if isinstance(result, bool) or not isinstance(result, int): + return False + total = sum(piles) + memo = {} + + def advantage(index, m): + if index == len(piles): + return 0 + key = (index, m) + if key not in memo: + taken = 0 + best = -total + for x in range(1, min(2 * m, len(piles) - index) + 1): + taken += piles[index + x - 1] + best = max(best, taken - advantage(index + x, max(m, x))) + memo[key] = best + return memo[key] + + expected = (total + advantage(0, 1)) // 2 + return result == expected + +seed: 1140 + +tests: + - name: "example-one" + in: + piles: [2, 7, 9, 4, 4] + out: 10 + - name: "example-two" + in: + piles: [1, 2, 3, 4, 5, 100] + out: 104 + - name: "single-minimum" + in: + piles: [1] + out: 1 + - name: "single-maximum" + in: + piles: [10000] + out: 10000 + - name: "two-equal" + in: + piles: [5, 5] + out: 10 + - name: "two-unequal" + in: + piles: [1, 100] + out: 101 + - name: "three-front-loaded" + in: + piles: [100, 1, 1] + out: 101 + - name: "three-back-loaded" + in: + piles: [1, 1, 100] + out: 2 + - name: "three-balanced" + in: + piles: [2, 2, 2] + out: 4 + - name: "three-middle-spike" + in: + piles: [1, 100, 1] + out: 101 + - name: "four-increasing" + in: + piles: [1, 2, 3, 4] + out: 5 + - name: "four-decreasing" + in: + piles: [4, 3, 2, 1] + out: 7 + - name: "five-ones" + in: + piles: [1, 1, 1, 1, 1] + out: 3 + - name: "five-all-maximum" + in: + piles: [10000, 10000, 10000, 10000, 10000] + out: 30000 + - name: "six-alternating-small" + in: + piles: [1, 10, 1, 10, 1, 10] + out: 12 + - name: "six-alternating-maximum" + in: + piles: [10000, 1, 10000, 1, 10000, 1] + out: 20001 + - name: "six-increasing" + in: + piles: [1, 2, 3, 4, 5, 6] + out: 10 + - name: "six-decreasing" + in: + piles: [6, 5, 4, 3, 2, 1] + out: 12 + - name: "seven-equal" + in: + piles: [7, 7, 7, 7, 7, 7, 7] + out: 28 + - name: "eight-separated-spikes" + in: + piles: [100, 1, 1, 1, 100, 1, 1, 1] + out: 104 + - name: "nine-primes" + in: + piles: [2, 3, 5, 7, 11, 13, 17, 19, 23] + out: 53 + - name: "ten-large-ends" + in: + piles: [1000, 1, 1, 1, 1, 1, 1, 1, 1, 1000] + out: 2002 + - name: "mixed-eight" + in: + piles: [9, 2, 14, 3, 8, 1, 12, 4] + out: 33 + - name: "mixed-ten" + in: + piles: [5, 20, 1, 15, 3, 9, 2, 18, 4, 11] + out: 55 + - name: "late-maximum" + in: + piles: [1, 1, 1, 1, 1, 1, 1, 1, 1, 10000] + out: 10003 + - name: "early-maximum" + in: + piles: [10000, 1, 1, 1, 1, 1, 1, 1, 1, 1] + out: 10005 + - name: "four-all-maximum" + in: + piles: [10000, 10000, 10000, 10000] + out: 20000 + - name: "powers-of-two" + in: + piles: [1, 2, 4, 8, 16, 32, 64, 128] + out: 123 + - name: "fifteen-ones" + in: + piles: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + out: 8 + - name: "pi-digits-pattern" + in: + piles: [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2, 3, 8, 4] + out: 53 + - name: "twelve-alternating-high-first" + in: + piles: [9999, 1, 9999, 1, 9999, 1, 9999, 1, 9999, 1, 9999, 1] + out: 30000 + - name: "twelve-alternating-low-first" + in: + piles: [1, 9999, 1, 9999, 1, 9999, 1, 9999, 1, 9999, 1, 9999] + out: 30000 + - name: "twenty-small-interior" + in: + piles: [8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 8] + out: 21 + - name: "ten-fibonacci" + in: + piles: [13, 21, 34, 55, 89, 144, 233, 377, 610, 987] + out: 1432 + - name: "generated-maximum-uniform-range" + seed: 114001 + in: + piles: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 10000 + elemType: "int" + - name: "generated-maximum-small-values" + seed: 114002 + in: + piles: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 3 + elemType: "int" + - name: "generated-maximum-high-values" + seed: 114003 + in: + piles: + gen: "array" + len: 100 + of: + gen: "int" + min: 9990 + max: 10000 + elemType: "int" + - name: "generated-maximum-midrange" + seed: 114004 + in: + piles: + gen: "array" + len: 100 + of: + gen: "int" + min: 100 + max: 9000 + elemType: "int" + - name: "generated-maximum-low-to-mid" + seed: 114005 + in: + piles: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 1000 + elemType: "int" + - name: "generated-maximum-upper-range" + seed: 114006 + in: + piles: + gen: "array" + len: 100 + of: + gen: "int" + min: 5000 + max: 10000 + elemType: "int" diff --git a/tests/1001-1500/1140. stone-game-ii/sol.cpp b/tests/1001-1500/1140. stone-game-ii/sol.cpp new file mode 100644 index 00000000..2f9eed5b --- /dev/null +++ b/tests/1001-1500/1140. stone-game-ii/sol.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int stoneGameII(vector& piles) { + int n = piles.size(); + vector suffix(n + 1, 0); + for (int i = n - 1; i >= 0; i--) { + suffix[i] = suffix[i + 1] + piles[i]; + } + vector> memo(n, vector(n + 1, -1)); + + function best = [&](int i, int m) -> int { + if (i >= n) return 0; + if (memo[i][m] != -1) return memo[i][m]; + int answer = 0; + for (int x = 1; x <= min(2 * m, n - i); x++) { + answer = max(answer, suffix[i] - best(i + x, max(m, x))); + } + memo[i][m] = answer; + return answer; + }; + + return best(0, 1); + } +}; diff --git a/tests/1001-1500/1140. stone-game-ii/sol.cs b/tests/1001-1500/1140. stone-game-ii/sol.cs new file mode 100644 index 00000000..ff76fafe --- /dev/null +++ b/tests/1001-1500/1140. stone-game-ii/sol.cs @@ -0,0 +1,27 @@ +public class Solution { + public int StoneGameII(int[] piles) { + int n = piles.Length; + int[] suffix = new int[n + 1]; + for (int i = n - 1; i >= 0; i--) { + suffix[i] = suffix[i + 1] + piles[i]; + } + int[][] memo = new int[n][]; + for (int i = 0; i < n; i++) { + memo[i] = new int[n + 1]; + Array.Fill(memo[i], -1); + } + + int Best(int i, int m) { + if (i >= n) return 0; + if (memo[i][m] != -1) return memo[i][m]; + int answer = 0; + for (int x = 1; x <= Math.Min(2 * m, n - i); x++) { + answer = Math.Max(answer, suffix[i] - Best(i + x, Math.Max(m, x))); + } + memo[i][m] = answer; + return answer; + } + + return Best(0, 1); + } +} diff --git a/tests/1001-1500/1140. stone-game-ii/sol.dart b/tests/1001-1500/1140. stone-game-ii/sol.dart new file mode 100644 index 00000000..90278379 --- /dev/null +++ b/tests/1001-1500/1140. stone-game-ii/sol.dart @@ -0,0 +1,25 @@ +class Solution { + int stoneGameII(List piles) { + int n = piles.length; + List suffix = List.filled(n + 1, 0); + for (int i = n - 1; i >= 0; i--) { + suffix[i] = suffix[i + 1] + piles[i]; + } + List> memo = List.generate(n, (_) => List.filled(n + 1, -1)); + + int best(int i, int m) { + if (i >= n) return 0; + if (memo[i][m] != -1) return memo[i][m]; + int answer = 0; + for (int x = 1; x <= (2 * m).clamp(0, n - i); x++) { + answer = answer > suffix[i] - best(i + x, m > x ? m : x) + ? answer + : suffix[i] - best(i + x, m > x ? m : x); + } + memo[i][m] = answer; + return answer; + } + + return best(0, 1); + } +} diff --git a/tests/1001-1500/1140. stone-game-ii/sol.go b/tests/1001-1500/1140. stone-game-ii/sol.go new file mode 100644 index 00000000..840419a8 --- /dev/null +++ b/tests/1001-1500/1140. stone-game-ii/sol.go @@ -0,0 +1,43 @@ +func stoneGameII(piles []int) int { + n := len(piles) + suffix := make([]int, n+1) + for i := n - 1; i >= 0; i-- { + suffix[i] = suffix[i+1] + piles[i] + } + memo := make([][]int, n) + for i := 0; i < n; i++ { + memo[i] = make([]int, n+1) + for j := 0; j <= n; j++ { + memo[i][j] = -1 + } + } + + var best func(int, int) int + best = func(i, m int) int { + if i >= n { + return 0 + } + if memo[i][m] != -1 { + return memo[i][m] + } + answer := 0 + maxX := 2 * m + if maxX > n-i { + maxX = n - i + } + for x := 1; x <= maxX; x++ { + nextM := m + if x > nextM { + nextM = x + } + val := suffix[i] - best(i+x, nextM) + if val > answer { + answer = val + } + } + memo[i][m] = answer + return answer + } + + return best(0, 1) +} diff --git a/tests/1001-1500/1140. stone-game-ii/sol.java b/tests/1001-1500/1140. stone-game-ii/sol.java new file mode 100644 index 00000000..ba8e93e2 --- /dev/null +++ b/tests/1001-1500/1140. stone-game-ii/sol.java @@ -0,0 +1,30 @@ +class Solution { + public int stoneGameII(int[] piles) { + int n = piles.length; + int[] suffix = new int[n + 1]; + for (int i = n - 1; i >= 0; i--) { + suffix[i] = suffix[i + 1] + piles[i]; + } + int[][] memo = new int[n][n + 1]; + for (int i = 0; i < n; i++) { + java.util.Arrays.fill(memo[i], -1); + } + return best(0, 1, piles, suffix, memo); + } + + private int best(int i, int m, int[] piles, int[] suffix, int[][] memo) { + int n = piles.length; + if (i >= n) { + return 0; + } + if (memo[i][m] != -1) { + return memo[i][m]; + } + int answer = 0; + for (int x = 1; x <= Math.min(2 * m, n - i); x++) { + answer = Math.max(answer, suffix[i] - best(i + x, Math.max(m, x), piles, suffix, memo)); + } + memo[i][m] = answer; + return answer; + } +} diff --git a/tests/1001-1500/1140. stone-game-ii/sol.kt b/tests/1001-1500/1140. stone-game-ii/sol.kt new file mode 100644 index 00000000..d28d30c5 --- /dev/null +++ b/tests/1001-1500/1140. stone-game-ii/sol.kt @@ -0,0 +1,23 @@ +class Solution { + fun stoneGameII(piles: IntArray): Int { + val n = piles.size + val suffix = IntArray(n + 1) + for (i in n - 1 downTo 0) { + suffix[i] = suffix[i + 1] + piles[i] + } + val memo = Array(n) { IntArray(n + 1) { -1 } } + + fun best(i: Int, m: Int): Int { + if (i >= n) return 0 + if (memo[i][m] != -1) return memo[i][m] + var answer = 0 + for (x in 1..minOf(2 * m, n - i)) { + answer = maxOf(answer, suffix[i] - best(i + x, maxOf(m, x))) + } + memo[i][m] = answer + return answer + } + + return best(0, 1) + } +} diff --git a/tests/1001-1500/1140. stone-game-ii/sol.py b/tests/1001-1500/1140. stone-game-ii/sol.py new file mode 100644 index 00000000..b1454258 --- /dev/null +++ b/tests/1001-1500/1140. stone-game-ii/sol.py @@ -0,0 +1,21 @@ +class Solution: + def stoneGameII(self, piles): + n = len(piles) + suffix = [0] * (n + 1) + for i in range(n - 1, -1, -1): + suffix[i] = suffix[i + 1] + piles[i] + memo = {} + + def best(i, m): + if i >= n: + return 0 + key = (i, m) + if key in memo: + return memo[key] + answer = 0 + for x in range(1, min(2 * m, n - i) + 1): + answer = max(answer, suffix[i] - best(i + x, max(m, x))) + memo[key] = answer + return answer + + return best(0, 1) diff --git a/tests/1001-1500/1140. stone-game-ii/sol.py2 b/tests/1001-1500/1140. stone-game-ii/sol.py2 new file mode 100644 index 00000000..3a2118ea --- /dev/null +++ b/tests/1001-1500/1140. stone-game-ii/sol.py2 @@ -0,0 +1,21 @@ +class Solution(object): + def stoneGameII(self, piles): + n = len(piles) + suffix = [0] * (n + 1) + for i in range(n - 1, -1, -1): + suffix[i] = suffix[i + 1] + piles[i] + memo = {} + + def best(i, m): + if i >= n: + return 0 + key = (i, m) + if key in memo: + return memo[key] + answer = 0 + for x in range(1, min(2 * m, n - i) + 1): + answer = max(answer, suffix[i] - best(i + x, max(m, x))) + memo[key] = answer + return answer + + return best(0, 1) diff --git a/tests/1001-1500/1140. stone-game-ii/sol.rb b/tests/1001-1500/1140. stone-game-ii/sol.rb new file mode 100644 index 00000000..d06289b2 --- /dev/null +++ b/tests/1001-1500/1140. stone-game-ii/sol.rb @@ -0,0 +1,24 @@ +# @param {Integer[]} piles +# @return {Integer} +def stone_game_ii(piles) + n = piles.length + suffix = Array.new(n + 1, 0) + (n - 1).downto(0) do |i| + suffix[i] = suffix[i + 1] + piles[i] + end + memo = {} + + best = lambda do |i, m| + return 0 if i >= n + key = [i, m] + return memo[key] if memo.key?(key) + answer = 0 + (1..[2 * m, n - i].min).each do |x| + answer = [answer, suffix[i] - best.call(i + x, [m, x].max)].max + end + memo[key] = answer + answer + end + + best.call(0, 1) +end diff --git a/tests/1001-1500/1140. stone-game-ii/sol.rs b/tests/1001-1500/1140. stone-game-ii/sol.rs new file mode 100644 index 00000000..1904356f --- /dev/null +++ b/tests/1001-1500/1140. stone-game-ii/sol.rs @@ -0,0 +1,29 @@ +impl Solution { + pub fn stone_game_ii(piles: Vec) -> i32 { + let n = piles.len(); + let mut suffix = vec![0; n + 1]; + for i in (0..n).rev() { + suffix[i] = suffix[i + 1] + piles[i]; + } + let mut memo = vec![vec![-1; n + 1]; n]; + + fn best(i: usize, m: usize, n: usize, suffix: &[i32], memo: &mut Vec>) -> i32 { + if i >= n { + return 0; + } + if memo[i][m] != -1 { + return memo[i][m]; + } + let mut answer = 0; + let max_x = (2 * m).min(n - i); + for x in 1..=max_x { + let val = suffix[i] - best(i + x, m.max(x), n, suffix, memo); + answer = answer.max(val); + } + memo[i][m] = answer; + answer + } + + best(0, 1, n, &suffix, &mut memo) + } +} diff --git a/tests/1001-1500/1140. stone-game-ii/sol.swift b/tests/1001-1500/1140. stone-game-ii/sol.swift new file mode 100644 index 00000000..654890bd --- /dev/null +++ b/tests/1001-1500/1140. stone-game-ii/sol.swift @@ -0,0 +1,23 @@ +class Solution { + func stoneGameII(_ piles: [Int]) -> Int { + let n = piles.count + var suffix = Array(repeating: 0, count: n + 1) + for i in stride(from: n - 1, through: 0, by: -1) { + suffix[i] = suffix[i + 1] + piles[i] + } + var memo = Array(repeating: Array(repeating: -1, count: n + 1), count: n) + + func best(_ i: Int, _ m: Int) -> Int { + if i >= n { return 0 } + if memo[i][m] != -1 { return memo[i][m] } + var answer = 0 + for x in 1...min(2 * m, n - i) { + answer = max(answer, suffix[i] - best(i + x, max(m, x))) + } + memo[i][m] = answer + return answer + } + + return best(0, 1) + } +} diff --git a/tests/1001-1500/1140. stone-game-ii/sol.ts b/tests/1001-1500/1140. stone-game-ii/sol.ts new file mode 100644 index 00000000..1f5519b0 --- /dev/null +++ b/tests/1001-1500/1140. stone-game-ii/sol.ts @@ -0,0 +1,23 @@ +function stoneGameII(piles: number[]): number { + const n = piles.length; + const suffix: number[] = new Array(n + 1).fill(0); + for (let i = n - 1; i >= 0; i--) { + suffix[i] = suffix[i + 1] + piles[i]; + } + const memo: number[][] = Array.from({ length: n }, () => + new Array(n + 1).fill(-1), + ); + + function best(i: number, m: number): number { + if (i >= n) return 0; + if (memo[i][m] !== -1) return memo[i][m]; + let answer = 0; + for (let x = 1; x <= Math.min(2 * m, n - i); x++) { + answer = Math.max(answer, suffix[i] - best(i + x, Math.max(m, x))); + } + memo[i][m] = answer; + return answer; + } + + return best(0, 1); +} diff --git a/tests/1001-1500/1143. longest-common-subsequence/manifest.yaml b/tests/1001-1500/1143. longest-common-subsequence/manifest.yaml new file mode 100644 index 00000000..2da9371e --- /dev/null +++ b/tests/1001-1500/1143. longest-common-subsequence/manifest.yaml @@ -0,0 +1,288 @@ +entry: + id: 1143 + title: longest-common-subsequence + params: + text1: + type: string + text2: + type: string + call: + cpp: "Solution().longestCommonSubsequence({text1}, {text2})" + rust: "Solution::longest_common_subsequence({text1}, {text2})" + python3: "Solution().longestCommonSubsequence({text1}, {text2})" + python2: "Solution().longestCommonSubsequence({text1}, {text2})" + ruby: "longest_common_subsequence({text1}, {text2})" + java: "new Solution().longestCommonSubsequence({text1}, {text2})" + csharp: "new Solution().LongestCommonSubsequence({text1}, {text2})" + kotlin: "Solution().longestCommonSubsequence({text1}, {text2})" + go: "longestCommonSubsequence({text1}, {text2})" + dart: "Solution().longestCommonSubsequence({text1}, {text2})" + swift: "Solution().longestCommonSubsequence({text1}, {text2})" + typescript: "longestCommonSubsequence({text1}, {text2})" +judge: + type: exact +limits: + time_ms: 1500 + memory_mb: 256 +oracle: + python3: + call: "Checker().longestCommonSubsequence(text1, text2, {result})" + checker: | + class Checker: + def longestCommonSubsequence(self, text1, text2, result): + if not isinstance(text1, str) or not isinstance(text2, str): + return False + if not 1 <= len(text1) <= 1000 or not 1 <= len(text2) <= 1000: + return False + if any(c < 'a' or c > 'z' for c in text1 + text2): + return False + if not isinstance(result, int) or isinstance(result, bool): + return False + previous = [0] * (len(text2) + 1) + for first in text1: + current = [0] + for index, second in enumerate(text2, 1): + if first == second: + current.append(previous[index - 1] + 1) + else: + current.append(max(previous[index], current[-1])) + previous = current + return result == previous[-1] +seed: 1143 +tests: + - name: example_abcde_ace + in: + text1: abcde + text2: ace + out: 3 + - name: example_identical + in: + text1: abc + text2: abc + out: 3 + - name: example_disjoint + in: + text1: abc + text2: def + out: 0 + - name: single_same_character + in: + text1: a + text2: a + out: 1 + - name: single_different_characters + in: + text1: a + text2: z + out: 0 + - name: repeated_character_shorter_second + in: + text1: aaaaa + text2: aaa + out: 3 + - name: reverse_distinct_sequence + in: + text1: abcdef + text2: fedcba + out: 1 + - name: alternating_shift + in: + text1: abababab + text2: babababa + out: 7 + - name: interleaved_letters + in: + text1: axbycz + text2: abcxyz + out: 4 + - name: one_scattered_match + in: + text1: qwerty + text2: zqz + out: 1 + - name: common_prefix_only + in: + text1: abcxyz + text2: abcuvw + out: 3 + - name: common_suffix_only + in: + text1: xyzabc + text2: uvwabc + out: 3 + - name: common_middle_block + in: + text1: xxmnopqyy + text2: zzmnopqww + out: 5 + - name: distinct_shifted_window + in: + text1: abcdefghij + text2: bcdefghijk + out: 9 + - name: entirely_disjoint_repetitions + in: + text1: kkkkkkkk + text2: llllllll + out: 0 + - name: repeated_ordering_choice + in: + text1: aaabbb + text2: ababab + out: 4 + - name: crossing_choices + in: + text1: bdca + text2: abc + out: 2 + - name: duplicate_branching + in: + text1: cacbab + text2: abacba + out: 4 + - name: classic_dynamic_programming_case + in: + text1: aggtab + text2: gxtxayb + out: 4 + - name: repeated_blocks_with_offset + in: + text1: aaabaaaab + text2: abaaabaaa + out: 7 + - name: palindromic_order_conflict + in: + text1: abcba + text2: bacab + out: 3 + - name: alphabet_subset_in_order + in: + text1: qazwsxedc + text2: zsxdc + out: 5 + - name: alphabet_subset_reversed + in: + text1: qazwsxedc + text2: cdxsz + out: 1 + - name: long_identical_phrase + in: + text1: thequickbrownfox + text2: thequickbrownfox + out: 16 + - name: embedded_subsequence + in: + text1: dynamicprogramming + text2: dymcpg + out: 6 + - name: repeated_two_letter_runs + in: + text1: aabbaabbaabb + text2: bbaabbaabbaa + out: 10 + - name: shared_letters_require_skips + in: + text1: xmjyauz + text2: mzjawxu + out: 4 + - name: dense_repetition_with_single_separator + in: + text1: aaaaaabaaaaaa + text2: aaaaacaaaaa + out: 10 + - name: all_alphabet_once + in: + text1: abcdefghijklmnopqrstuvwxyz + text2: abcdefghijklmnopqrstuvwxyz + out: 26 + - name: all_alphabet_reverse + in: + text1: abcdefghijklmnopqrstuvwxyz + text2: zyxwvutsrqponmlkjihgfedcba + out: 1 + - name: long_alternating_blocks + in: + text1: abcabcabcabc + text2: acbacbacbacb + out: 8 + - name: insertion_at_both_ends + in: + text1: zaabcdefghijklmnopqrstuvwxy + text2: abcdefghijklmnopqrstuvwxyz + out: 25 + - name: subsequence_uses_final_character + in: + text1: hijklmnopqrstuvwxyzabcde + text2: ijklmnopqrstuvwxyzabcdez + out: 23 + - name: same_multiset_different_order + in: + text1: aabbccddeeff + text2: ffeeddccbbaa + out: 2 + - name: generated_binary_dense + seed: 101 + in: + text1: + gen: str + len: 400 + alphabet: ab + text2: + gen: str + len: 400 + alphabet: ab + - name: generated_small_alphabet_dense + seed: 202 + in: + text1: + gen: str + len: 400 + alphabet: abcd + text2: + gen: str + len: 400 + alphabet: abcd + - name: generated_medium_alphabet + seed: 303 + in: + text1: + gen: str + len: 400 + alphabet: abcdefgh + text2: + gen: str + len: 400 + alphabet: abcdefgh + - name: generated_full_alphabet + seed: 404 + in: + text1: + gen: str + len: 400 + alphabet: abcdefghijklmnopqrstuvwxyz + text2: + gen: str + len: 400 + alphabet: abcdefghijklmnopqrstuvwxyz + - name: generated_vowel_consonant_mix + seed: 505 + in: + text1: + gen: str + len: 400 + alphabet: aeioubcdfg + text2: + gen: str + len: 400 + alphabet: aeioubcdfg + - name: generated_late_alphabet + seed: 606 + in: + text1: + gen: str + len: 400 + alphabet: qrstuvwxyz + text2: + gen: str + len: 400 + alphabet: qrstuvwxyz diff --git a/tests/1001-1500/1143. longest-common-subsequence/sol.cpp b/tests/1001-1500/1143. longest-common-subsequence/sol.cpp new file mode 100644 index 00000000..2873605a --- /dev/null +++ b/tests/1001-1500/1143. longest-common-subsequence/sol.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int longestCommonSubsequence(string text1, string text2) { + int m = text1.size(); + int n = text2.size(); + vector> memo(m, vector(n, -1)); + + function solve = [&](int i, int j) -> int { + if (i >= m || j >= n) return 0; + if (memo[i][j] != -1) return memo[i][j]; + + if (text1[i] == text2[j]) { + memo[i][j] = 1 + solve(i + 1, j + 1); + } else { + memo[i][j] = max(solve(i + 1, j), solve(i, j + 1)); + } + return memo[i][j]; + }; + + return solve(0, 0); + } +}; diff --git a/tests/1001-1500/1143. longest-common-subsequence/sol.cs b/tests/1001-1500/1143. longest-common-subsequence/sol.cs new file mode 100644 index 00000000..12a9f325 --- /dev/null +++ b/tests/1001-1500/1143. longest-common-subsequence/sol.cs @@ -0,0 +1,25 @@ +public class Solution { + public int LongestCommonSubsequence(string text1, string text2) { + int m = text1.Length; + int n = text2.Length; + int[,] memo = new int[m, n]; + for (int i = 0; i < m; i++) + for (int j = 0; j < n; j++) + memo[i, j] = -1; + + return Solve(0, 0, text1, text2, memo, m, n); + } + + private int Solve(int i, int j, string text1, string text2, int[,] memo, int m, int n) { + if (i >= m || j >= n) return 0; + if (memo[i, j] != -1) return memo[i, j]; + + if (text1[i] == text2[j]) { + memo[i, j] = 1 + Solve(i + 1, j + 1, text1, text2, memo, m, n); + } else { + memo[i, j] = Math.Max(Solve(i + 1, j, text1, text2, memo, m, n), + Solve(i, j + 1, text1, text2, memo, m, n)); + } + return memo[i, j]; + } +} diff --git a/tests/1001-1500/1143. longest-common-subsequence/sol.dart b/tests/1001-1500/1143. longest-common-subsequence/sol.dart new file mode 100644 index 00000000..fc54dee1 --- /dev/null +++ b/tests/1001-1500/1143. longest-common-subsequence/sol.dart @@ -0,0 +1,23 @@ +class Solution { + int longestCommonSubsequence(String text1, String text2) { + int m = text1.length; + int n = text2.length; + List> memo = List.generate(m, (_) => List.filled(n, -1)); + + int solve(int i, int j) { + if (i >= m || j >= n) return 0; + if (memo[i][j] != -1) return memo[i][j]; + + if (text1[i] == text2[j]) { + memo[i][j] = 1 + solve(i + 1, j + 1); + } else { + memo[i][j] = max(solve(i + 1, j), solve(i, j + 1)); + } + return memo[i][j]; + } + + return solve(0, 0); + } + + int max(int a, int b) => a > b ? a : b; +} diff --git a/tests/1001-1500/1143. longest-common-subsequence/sol.go b/tests/1001-1500/1143. longest-common-subsequence/sol.go new file mode 100644 index 00000000..a70419c2 --- /dev/null +++ b/tests/1001-1500/1143. longest-common-subsequence/sol.go @@ -0,0 +1,34 @@ +func longestCommonSubsequence(text1 string, text2 string) int { + m, n := len(text1), len(text2) + memo := make([][]int, m) + for i := range memo { + memo[i] = make([]int, n) + for j := range memo[i] { + memo[i][j] = -1 + } + } + + var solve func(int, int) int + solve = func(i, j int) int { + if i >= m || j >= n { + return 0 + } + if memo[i][j] != -1 { + return memo[i][j] + } + if text1[i] == text2[j] { + memo[i][j] = 1 + solve(i+1, j+1) + } else { + left := solve(i+1, j) + right := solve(i, j+1) + if left > right { + memo[i][j] = left + } else { + memo[i][j] = right + } + } + return memo[i][j] + } + + return solve(0, 0) +} diff --git a/tests/1001-1500/1143. longest-common-subsequence/sol.java b/tests/1001-1500/1143. longest-common-subsequence/sol.java new file mode 100644 index 00000000..2e5ea581 --- /dev/null +++ b/tests/1001-1500/1143. longest-common-subsequence/sol.java @@ -0,0 +1,26 @@ +class Solution { + public int longestCommonSubsequence(String text1, String text2) { + int m = text1.length(); + int n = text2.length(); + int[][] memo = new int[m][n]; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + memo[i][j] = -1; + } + } + return solve(0, 0, text1, text2, memo, m, n); + } + + private int solve(int i, int j, String text1, String text2, int[][] memo, int m, int n) { + if (i >= m || j >= n) return 0; + if (memo[i][j] != -1) return memo[i][j]; + + if (text1.charAt(i) == text2.charAt(j)) { + memo[i][j] = 1 + solve(i + 1, j + 1, text1, text2, memo, m, n); + } else { + memo[i][j] = Math.max(solve(i + 1, j, text1, text2, memo, m, n), + solve(i, j + 1, text1, text2, memo, m, n)); + } + return memo[i][j]; + } +} diff --git a/tests/1001-1500/1143. longest-common-subsequence/sol.kt b/tests/1001-1500/1143. longest-common-subsequence/sol.kt new file mode 100644 index 00000000..7a3259bd --- /dev/null +++ b/tests/1001-1500/1143. longest-common-subsequence/sol.kt @@ -0,0 +1,21 @@ +class Solution { + fun longestCommonSubsequence(text1: String, text2: String): Int { + val m = text1.length + val n = text2.length + val memo = Array(m) { IntArray(n) { -1 } } + + fun solve(i: Int, j: Int): Int { + if (i >= m || j >= n) return 0 + if (memo[i][j] != -1) return memo[i][j] + + memo[i][j] = if (text1[i] == text2[j]) { + 1 + solve(i + 1, j + 1) + } else { + maxOf(solve(i + 1, j), solve(i, j + 1)) + } + return memo[i][j] + } + + return solve(0, 0) + } +} diff --git a/tests/1001-1500/1143. longest-common-subsequence/sol.py b/tests/1001-1500/1143. longest-common-subsequence/sol.py new file mode 100644 index 00000000..4b1d15aa --- /dev/null +++ b/tests/1001-1500/1143. longest-common-subsequence/sol.py @@ -0,0 +1,25 @@ +class Solution: + def longestCommonSubsequence(self, text1: str, text2: str) -> int: + m, n = len(text1), len(text2) + # Initialize an m x n grid with -1 + memo = [[-1] * n for _ in range(m)] + + def solve(i, j): + # Base case: Out of bounds + if i >= m or j >= n: + return 0 + + # Return cached result + if memo[i][j] != -1: + return memo[i][j] + + # Characters match: Move both pointers + if text1[i] == text2[j]: + memo[i][j] = 1 + solve(i + 1, j + 1) + # Characters differ: Branch out and find the max + else: + memo[i][j] = max(solve(i + 1, j), solve(i, j + 1)) + + return memo[i][j] + + return solve(0, 0) diff --git a/tests/1001-1500/1143. longest-common-subsequence/sol.py2 b/tests/1001-1500/1143. longest-common-subsequence/sol.py2 new file mode 100644 index 00000000..27ab26c4 --- /dev/null +++ b/tests/1001-1500/1143. longest-common-subsequence/sol.py2 @@ -0,0 +1,22 @@ +class Solution(object): + def longestCommonSubsequence(self, text1, text2): + """ + :type text1: str + :type text2: str + :rtype: int + """ + m, n = len(text1), len(text2) + memo = [[-1] * n for _ in range(m)] + + def solve(i, j): + if i >= m or j >= n: + return 0 + if memo[i][j] != -1: + return memo[i][j] + if text1[i] == text2[j]: + memo[i][j] = 1 + solve(i + 1, j + 1) + else: + memo[i][j] = max(solve(i + 1, j), solve(i, j + 1)) + return memo[i][j] + + return solve(0, 0) diff --git a/tests/1001-1500/1143. longest-common-subsequence/sol.rb b/tests/1001-1500/1143. longest-common-subsequence/sol.rb new file mode 100644 index 00000000..6d6913f7 --- /dev/null +++ b/tests/1001-1500/1143. longest-common-subsequence/sol.rb @@ -0,0 +1,21 @@ +# @param {String} text1 +# @param {String} text2 +# @return {Integer} +def longest_common_subsequence(text1, text2) + m, n = text1.length, text2.length + memo = Array.new(m) { Array.new(n, -1) } + + solve = lambda do |i, j| + return 0 if i >= m || j >= n + return memo[i][j] if memo[i][j] != -1 + + if text1[i] == text2[j] + memo[i][j] = 1 + solve.call(i + 1, j + 1) + else + memo[i][j] = [solve.call(i + 1, j), solve.call(i, j + 1)].max + end + memo[i][j] + end + + solve.call(0, 0) +end diff --git a/tests/1001-1500/1143. longest-common-subsequence/sol.rs b/tests/1001-1500/1143. longest-common-subsequence/sol.rs new file mode 100644 index 00000000..034074b3 --- /dev/null +++ b/tests/1001-1500/1143. longest-common-subsequence/sol.rs @@ -0,0 +1,26 @@ +impl Solution { + pub fn longest_common_subsequence(text1: String, text2: String) -> i32 { + let m = text1.len(); + let n = text2.len(); + let mut memo = vec![vec![-1; n]; m]; + let t1: Vec = text1.chars().collect(); + let t2: Vec = text2.chars().collect(); + + fn solve(i: usize, j: usize, m: usize, n: usize, t1: &[char], t2: &[char], memo: &mut Vec>) -> i32 { + if i >= m || j >= n { + return 0; + } + if memo[i][j] != -1 { + return memo[i][j]; + } + if t1[i] == t2[j] { + memo[i][j] = 1 + solve(i + 1, j + 1, m, n, t1, t2, memo); + } else { + memo[i][j] = solve(i + 1, j, m, n, t1, t2, memo).max(solve(i, j + 1, m, n, t1, t2, memo)); + } + memo[i][j] + } + + solve(0, 0, m, n, &t1, &t2, &mut memo) + } +} diff --git a/tests/1001-1500/1143. longest-common-subsequence/sol.swift b/tests/1001-1500/1143. longest-common-subsequence/sol.swift new file mode 100644 index 00000000..9490fdcb --- /dev/null +++ b/tests/1001-1500/1143. longest-common-subsequence/sol.swift @@ -0,0 +1,23 @@ +class Solution { + func longestCommonSubsequence(_ text1: String, _ text2: String) -> Int { + let m = text1.count + let n = text2.count + var memo = Array(repeating: Array(repeating: -1, count: n), count: m) + let arr1 = Array(text1) + let arr2 = Array(text2) + + func solve(_ i: Int, _ j: Int) -> Int { + if i >= m || j >= n { return 0 } + if memo[i][j] != -1 { return memo[i][j] } + + if arr1[i] == arr2[j] { + memo[i][j] = 1 + solve(i + 1, j + 1) + } else { + memo[i][j] = max(solve(i + 1, j), solve(i, j + 1)) + } + return memo[i][j] + } + + return solve(0, 0) + } +} diff --git a/tests/1001-1500/1143. longest-common-subsequence/sol.ts b/tests/1001-1500/1143. longest-common-subsequence/sol.ts new file mode 100644 index 00000000..c3de367a --- /dev/null +++ b/tests/1001-1500/1143. longest-common-subsequence/sol.ts @@ -0,0 +1,19 @@ +function longestCommonSubsequence(text1: string, text2: string): number { + const m = text1.length; + const n = text2.length; + const memo: number[][] = Array.from({ length: m }, () => Array(n).fill(-1)); + + function solve(i: number, j: number): number { + if (i >= m || j >= n) return 0; + if (memo[i][j] !== -1) return memo[i][j]; + + if (text1[i] === text2[j]) { + memo[i][j] = 1 + solve(i + 1, j + 1); + } else { + memo[i][j] = Math.max(solve(i + 1, j), solve(i, j + 1)); + } + return memo[i][j]; + } + + return solve(0, 0); +} diff --git a/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/manifest.yaml b/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/manifest.yaml new file mode 100644 index 00000000..eeec9e02 --- /dev/null +++ b/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/manifest.yaml @@ -0,0 +1,250 @@ +entry: + id: 1144 + title: "decrease-elements-to-make-array-zigzag" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().movesToMakeZigzag({nums})" + rust: "Solution::moves_to_make_zigzag({nums})" + python3: "Solution().movesToMakeZigzag({nums})" + python2: "Solution().movesToMakeZigzag({nums})" + ruby: "moves_to_make_zigzag({nums})" + java: "new Solution().movesToMakeZigzag({nums})" + csharp: "new Solution().MovesToMakeZigzag({nums})" + kotlin: "Solution().movesToMakeZigzag({nums})" + go: "movesToMakeZigzag({nums})" + dart: "Solution().movesToMakeZigzag({nums})" + swift: "Solution().movesToMakeZigzag({nums})" + typescript: "movesToMakeZigzag({nums})" + +judge: + type: "exact" + +limits: + time_ms: 500 + memory_mb: 300 + +oracle: + python3: + call: "Checker().movesToMakeZigzag(nums, {result})" + checker: | + class Checker: + def movesToMakeZigzag(self, nums, result): + if not isinstance(result, int) or isinstance(result, bool) or result < 0: + return False + costs = [] + for mode in (0, 1): + total = 0 + for i, value in enumerate(nums): + if i % 2 != mode: + continue + left = nums[i - 1] if i else 10**9 + right = nums[i + 1] if i + 1 < len(nums) else 10**9 + limit = min(left, right) - 1 + if value > limit: + total += value - limit + costs.append(total) + return result == min(costs) + +seed: 1144 + +tests: + - name: "example_one" + in: + nums: [1, 2, 3] + out: 2 + - name: "example_two" + in: + nums: [9, 6, 1, 6, 2] + out: 4 + - name: "single_element" + in: + nums: [1] + out: 0 + - name: "single_large" + in: + nums: [1000] + out: 0 + - name: "already_even_valleys" + in: + nums: [5, 1, 5, 1, 5] + out: 0 + - name: "already_odd_valleys" + in: + nums: [1, 5, 1, 5, 1] + out: 0 + - name: "two_equal" + in: + nums: [4, 4] + out: 1 + - name: "two_increasing" + in: + nums: [1, 2] + out: 0 + - name: "two_decreasing" + in: + nums: [2, 1] + out: 0 + - name: "three_equal" + in: + nums: [5, 5, 5] + out: 1 + - name: "four_equal" + in: + nums: [7, 7, 7, 7] + out: 2 + - name: "strict_increase" + in: + nums: [1, 2, 3, 4, 5, 6] + out: 4 + - name: "strict_decrease" + in: + nums: [6, 5, 4, 3, 2, 1] + out: 4 + - name: "alternating_plateau" + in: + nums: [2, 1, 2, 1, 2, 1] + out: 0 + - name: "one_peak" + in: + nums: [1, 10, 1] + out: 0 + - name: "one_valley" + in: + nums: [10, 1, 10] + out: 0 + - name: "large_endpoints" + in: + nums: [1000, 1, 1000, 1, 1000] + out: 0 + - name: "large_middle_peak" + in: + nums: [1, 1000, 1, 1000, 1] + out: 0 + - name: "mixed_small" + in: + nums: [3, 3, 2, 4, 2] + out: 1 + - name: "mixed_large" + in: + nums: [10, 8, 10, 8, 10, 8, 10] + out: 0 + - name: "boundary_one_two" + in: + nums: [1, 1, 1, 2, 1] + out: 2 + - name: "two_high_peaks" + in: + nums: [1, 9, 1, 9, 1, 9, 1] + out: 0 + - name: "two_low_peaks" + in: + nums: [9, 1, 9, 1, 9, 1, 9] + out: 0 + - name: "edge_tie_choice" + in: + nums: [8, 9, 8, 7] + out: 2 + - name: "alternating_high_low" + in: + nums: [1000, 999, 1000, 999, 1000, 999] + out: 0 + - name: "plateau_then_peak" + in: + nums: [4, 4, 4, 1, 4, 4, 4] + out: 2 + - name: "descending_tail" + in: + nums: [1000, 999, 998, 997, 996, 995, 994, 993] + out: 6 + - name: "repeated_minima" + in: + nums: [2, 1, 2, 2, 2, 1, 2, 2] + out: 2 + - name: "single_spike" + in: + nums: [3, 3, 3, 1000, 3, 3, 3] + out: 4 + - name: "minimum_values" + in: + nums: [1, 1, 2, 1, 2, 2, 1, 1, 2] + out: 4 + - name: "equal_high_left_boundary" + in: + nums: [1000, 1000, 1] + out: 1 + - name: "equal_high_right_boundary" + in: + nums: [1, 1000, 1000] + out: 1 + - name: "center_tie_with_extreme_neighbors" + in: + nums: [1000, 1, 1, 1000] + out: 1001 + - name: "adjacent_tie_between_peaks" + in: + nums: [1, 1000, 1, 1, 1000, 1] + out: 1001 + - name: "generated_full_range_max_length" + seed: 11 + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 1000 + - name: "generated_low_domain_max_length" + seed: 22 + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 3 + - name: "generated_high_domain_max_length" + seed: 33 + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 998 + max: 1000 + - name: "generated_mid_domain_max_length" + seed: 44 + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 450 + max: 550 + - name: "generated_binary_max_length" + seed: 55 + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 2 + - name: "generated_near_max_length" + seed: 66 + in: + nums: + gen: "array" + len: 999 + of: + gen: "int" + min: 1 + max: 1000 diff --git a/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.cpp b/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.cpp new file mode 100644 index 00000000..35b22e6a --- /dev/null +++ b/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int movesToMakeZigzag(vector& nums) { + int n = nums.size(); + + auto findValleys = [&](int mode) { + int res = 0; + for (int i = 0; i < n; i++) { + if (i % 2 == mode) { + int left = i - 1 >= 0 ? nums[i - 1] : INT_MAX; + int right = i + 1 < n ? nums[i + 1] : INT_MAX; + int minNeighbor = min(left, right); + if (nums[i] >= minNeighbor) { + res += nums[i] - (minNeighbor - 1); + } + } + } + return res; + }; + + return min(findValleys(0), findValleys(1)); + } +}; diff --git a/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.cs b/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.cs new file mode 100644 index 00000000..8ac30a3a --- /dev/null +++ b/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.cs @@ -0,0 +1,22 @@ +public class Solution { + public int MovesToMakeZigzag(int[] nums) { + int n = nums.Length; + return Math.Min(FindValleys(nums, 0), FindValleys(nums, 1)); + } + + private int FindValleys(int[] nums, int mode) { + int res = 0; + int n = nums.Length; + for (int i = 0; i < n; i++) { + if (i % 2 == mode) { + int left = i - 1 >= 0 ? nums[i - 1] : int.MaxValue; + int right = i + 1 < n ? nums[i + 1] : int.MaxValue; + int minNeighbor = Math.Min(left, right); + if (nums[i] >= minNeighbor) { + res += nums[i] - (minNeighbor - 1); + } + } + } + return res; + } +} diff --git a/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.dart b/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.dart new file mode 100644 index 00000000..0912eddf --- /dev/null +++ b/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.dart @@ -0,0 +1,22 @@ +class Solution { + int movesToMakeZigzag(List nums) { + int n = nums.length; + return [findValleys(nums, 0), findValleys(nums, 1)].reduce((a, b) => a < b ? a : b); + } + + int findValleys(List nums, int mode) { + int res = 0; + int n = nums.length; + for (int i = 0; i < n; i++) { + if (i % 2 == mode) { + int left = i - 1 >= 0 ? nums[i - 1] : 0x7FFFFFFFFFFFFFFF; + int right = i + 1 < n ? nums[i + 1] : 0x7FFFFFFFFFFFFFFF; + int minNeighbor = left < right ? left : right; + if (nums[i] >= minNeighbor) { + res += nums[i] - (minNeighbor - 1); + } + } + } + return res; + } +} diff --git a/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.go b/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.go new file mode 100644 index 00000000..14427d74 --- /dev/null +++ b/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.go @@ -0,0 +1,33 @@ +func movesToMakeZigzag(nums []int) int { + n := len(nums) + findValleys := func(mode int) int { + res := 0 + for i := 0; i < n; i++ { + if i % 2 == mode { + left := int(^uint(0) >> 1) // max int + if i - 1 >= 0 { + left = nums[i - 1] + } + right := int(^uint(0) >> 1) + if i + 1 < n { + right = nums[i + 1] + } + minNeighbor := left + if right < minNeighbor { + minNeighbor = right + } + if nums[i] >= minNeighbor { + res += nums[i] - (minNeighbor - 1) + } + } + } + return res + } + + a := findValleys(0) + b := findValleys(1) + if a < b { + return a + } + return b +} diff --git a/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.java b/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.java new file mode 100644 index 00000000..81470738 --- /dev/null +++ b/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.java @@ -0,0 +1,22 @@ +class Solution { + public int movesToMakeZigzag(int[] nums) { + int n = nums.length; + return Math.min(findValleys(nums, 0), findValleys(nums, 1)); + } + + private int findValleys(int[] nums, int mode) { + int res = 0; + int n = nums.length; + for (int i = 0; i < n; i++) { + if (i % 2 == mode) { + int left = i - 1 >= 0 ? nums[i - 1] : Integer.MAX_VALUE; + int right = i + 1 < n ? nums[i + 1] : Integer.MAX_VALUE; + int minNeighbor = Math.min(left, right); + if (nums[i] >= minNeighbor) { + res += nums[i] - (minNeighbor - 1); + } + } + } + return res; + } +} diff --git a/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.kt b/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.kt new file mode 100644 index 00000000..ed2d7878 --- /dev/null +++ b/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.kt @@ -0,0 +1,22 @@ +class Solution { + fun movesToMakeZigzag(nums: IntArray): Int { + val n = nums.size + return minOf(findValleys(nums, 0), findValleys(nums, 1)) + } + + private fun findValleys(nums: IntArray, mode: Int): Int { + var res = 0 + val n = nums.size + for (i in 0 until n) { + if (i % 2 == mode) { + val left = if (i - 1 >= 0) nums[i - 1] else Int.MAX_VALUE + val right = if (i + 1 < n) nums[i + 1] else Int.MAX_VALUE + val minNeighbor = minOf(left, right) + if (nums[i] >= minNeighbor) { + res += nums[i] - (minNeighbor - 1) + } + } + } + return res + } +} diff --git a/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.py b/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.py new file mode 100644 index 00000000..d41e72cf --- /dev/null +++ b/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.py @@ -0,0 +1,16 @@ +class Solution: + def movesToMakeZigzag(self, nums: List[int]) -> int: + n = len(nums) + + def find_valleys(mode): + res = 0 + for i in range(n): + if i % 2 == mode: + left = nums[i - 1] if i - 1 >= 0 else float("inf") + right = nums[i + 1] if i + 1 < n else float("inf") + min_neighbor = min(left, right) + if nums[i] >= min_neighbor: + res += nums[i] - (min_neighbor - 1) + return res + + return min(find_valleys(0), find_valleys(1)) diff --git a/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.py2 b/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.py2 new file mode 100644 index 00000000..ed404aeb --- /dev/null +++ b/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.py2 @@ -0,0 +1,20 @@ +class Solution(object): + def movesToMakeZigzag(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + n = len(nums) + + def find_valleys(mode): + res = 0 + for i in range(n): + if i % 2 == mode: + left = nums[i-1] if i-1 >= 0 else float('inf') + right = nums[i+1] if i+1 < n else float('inf') + min_neighbor = min(left, right) + if nums[i] >= min_neighbor: + res += nums[i] - (min_neighbor - 1) + return res + + return min(find_valleys(0), find_valleys(1)) diff --git a/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.rb b/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.rb new file mode 100644 index 00000000..5fd427c5 --- /dev/null +++ b/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.rb @@ -0,0 +1,22 @@ +# @param {Integer[]} nums +# @return {Integer} +def moves_to_make_zigzag(nums) + n = nums.length + + find_valleys = lambda do |mode| + res = 0 + (0...n).each do |i| + if i % 2 == mode + left = i - 1 >= 0 ? nums[i - 1] : Float::INFINITY + right = i + 1 < n ? nums[i + 1] : Float::INFINITY + min_neighbor = [left, right].min + if nums[i] >= min_neighbor + res += nums[i] - (min_neighbor - 1) + end + end + end + res + end + + [find_valleys.call(0), find_valleys.call(1)].min +end diff --git a/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.rs b/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.rs new file mode 100644 index 00000000..f1eb9559 --- /dev/null +++ b/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.rs @@ -0,0 +1,22 @@ +impl Solution { + pub fn moves_to_make_zigzag(nums: Vec) -> i32 { + let n = nums.len(); + + let find_valleys = |mode: usize| -> i32 { + let mut res = 0; + for i in 0..n { + if i % 2 == mode { + let left = if i > 0 { nums[i - 1] } else { i32::MAX }; + let right = if i + 1 < n { nums[i + 1] } else { i32::MAX }; + let min_neighbor = left.min(right); + if nums[i] >= min_neighbor { + res += nums[i] - (min_neighbor - 1); + } + } + } + res + }; + + find_valleys(0).min(find_valleys(1)) + } +} diff --git a/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.swift b/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.swift new file mode 100644 index 00000000..652f0ddd --- /dev/null +++ b/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.swift @@ -0,0 +1,22 @@ +class Solution { + func movesToMakeZigzag(_ nums: [Int]) -> Int { + let n = nums.count + + func findValleys(_ mode: Int) -> Int { + var res = 0 + for i in 0..= 0 ? nums[i - 1] : Int.max + let right = i + 1 < n ? nums[i + 1] : Int.max + let minNeighbor = min(left, right) + if nums[i] >= minNeighbor { + res += nums[i] - (minNeighbor - 1) + } + } + } + return res + } + + return min(findValleys(0), findValleys(1)) + } +} diff --git a/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.ts b/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.ts new file mode 100644 index 00000000..ab78d688 --- /dev/null +++ b/tests/1001-1500/1144. decrease-elements-to-make-array-zigzag/sol.ts @@ -0,0 +1,20 @@ +function movesToMakeZigzag(nums: number[]): number { + const n = nums.length; + + const findValleys = (mode: number): number => { + let res = 0; + for (let i = 0; i < n; i++) { + if (i % 2 === mode) { + const left = i - 1 >= 0 ? nums[i - 1] : Infinity; + const right = i + 1 < n ? nums[i + 1] : Infinity; + const minNeighbor = Math.min(left, right); + if (nums[i] >= minNeighbor) { + res += nums[i] - (minNeighbor - 1); + } + } + } + return res; + }; + + return Math.min(findValleys(0), findValleys(1)); +} diff --git a/tests/1001-1500/1145. binary-tree-coloring-game/manifest.yaml b/tests/1001-1500/1145. binary-tree-coloring-game/manifest.yaml new file mode 100644 index 00000000..553fec62 --- /dev/null +++ b/tests/1001-1500/1145. binary-tree-coloring-game/manifest.yaml @@ -0,0 +1,966 @@ +entry: + id: 1145 + title: "binary-tree-coloring-game" + params: + root: + type: tree_node + n: + type: int + x: + type: int + call: + cpp: "Solution().btreeGameWinningMove({root}, {n}, {x})" + rust: "Solution::btree_game_winning_move({root}, {n}, {x})" + python3: "Solution().btreeGameWinningMove({root}, {n}, {x})" + python2: "Solution().btreeGameWinningMove({root}, {n}, {x})" + ruby: "btree_game_winning_move({root}, {n}, {x})" + java: "new Solution().btreeGameWinningMove({root}, {n}, {x})" + csharp: "new Solution().BtreeGameWinningMove({root}, {n}, {x})" + kotlin: "Solution().btreeGameWinningMove({root}, {n}, {x})" + go: "btreeGameWinningMove({root}, {n}, {x})" + dart: "Solution().btreeGameWinningMove({root}, {n}, {x})" + swift: "Solution().btreeGameWinningMove({root}, {n}, {x})" + typescript: "btreeGameWinningMove({root}, {n}, {x})" +judge: + type: exact +limits: + time_ms: 500 + memory_mb: 300 +oracle: + python3: + call: "Checker().btreeGameWinningMove(root, n, x, {result})" + checker: | + class Checker: + def btreeGameWinningMove(self, root, n, x, result): + if type(result) is not bool or not root or root[0] is None: + return False + children = {} + queue = [root[0]] + index = 1 + while queue: + value = queue.pop(0) + children[value] = [] + for _ in range(2): + if index >= len(root): + break + child = root[index] + index += 1 + if child is not None: + children[value].append(child) + queue.append(child) + if x not in children or len(children) != n: + return False + def count(value): + return 1 + sum(count(child) for child in children[value]) + child_sizes = [count(child) for child in children[x]] + parent_size = n - 1 - sum(child_sizes) + expected = max(child_sizes + [parent_size]) > n // 2 + return result is expected +seed: 1145 +tests: + - name: official_second_player_takes_larger_side + in: + root: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] + n: 11 + x: 3 + out: true + - name: official_three_node_root + in: + root: [1, 2, 3] + n: 3 + x: 1 + out: false + - name: singleton_has_no_second_choice + in: + root: [1] + n: 1 + x: 1 + out: false + - name: three_node_left_chain_root + in: + root: [1, 2, null] + n: 3 + x: 1 + out: false + - name: three_node_left_chain_leaf + in: + root: [1, 2, null] + n: 3 + x: 2 + out: true + - name: three_node_right_chain_root + in: + root: [1, null, 2] + n: 3 + x: 1 + out: false + - name: three_node_right_chain_leaf + in: + root: [1, null, 2] + n: 3 + x: 2 + out: true + - name: five_node_left_chain_root + in: + root: [1, 2, null, 3, null, 4, null, 5] + n: 5 + x: 1 + out: true + - name: five_node_left_chain_center_split + in: + root: [1, 2, null, 3, null, 4, null, 5] + n: 5 + x: 3 + out: false + - name: five_node_left_chain_near_leaf + in: + root: [1, 2, null, 3, null, 4, null, 5] + n: 5 + x: 4 + out: true + - name: seven_node_perfect_root_tie + in: + root: [1, 2, 3, 4, 5, 6, 7] + n: 7 + x: 1 + out: false + - name: seven_node_perfect_internal_parent_region + in: + root: [1, 2, 3, 4, 5, 6, 7] + n: 7 + x: 2 + out: true + - name: five_node_left_heavy_root + in: + root: [1, 2, 3, 4, 5] + n: 5 + x: 1 + out: true + - name: five_node_left_heavy_balanced_cut + in: + root: [1, 2, 3, 4, 5] + n: 5 + x: 2 + out: false + - name: five_node_left_heavy_right_leaf + in: + root: [1, 2, 3, 4, 5] + n: 5 + x: 3 + out: true + - name: sparse_five_node_internal_with_parent_majority + in: + root: [1, 2, 3, null, 4, null, 5] + n: 5 + x: 2 + out: true + - name: sparse_five_node_deep_leaf + in: + root: [1, 2, 3, null, 4, null, 5] + n: 5 + x: 4 + out: true + - name: nine_node_unbalanced_root + in: + root: [1, 2, 3, 4, 5, 6, null, 7, 8, 9] + n: 9 + x: 1 + out: true + - name: nine_node_unbalanced_internal_tie + in: + root: [1, 2, 3, 4, 5, 6, null, 7, 8, 9] + n: 9 + x: 2 + out: false + - name: nine_node_unbalanced_grandchild + in: + root: [1, 2, 3, 4, 5, 6, null, 7, 8, 9] + n: 9 + x: 4 + out: true + - name: eleven_node_split_at_root + in: + root: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] + n: 11 + x: 1 + out: true + - name: eleven_node_internal_left_majority + in: + root: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] + n: 11 + x: 2 + out: false + - name: eleven_node_last_level_leaf + in: + root: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] + n: 11 + x: 11 + out: true + - name: fifteen_node_perfect_root + in: + root: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] + n: 15 + x: 1 + out: false + - name: fifteen_node_perfect_level_one + in: + root: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] + n: 15 + x: 2 + out: true + - name: fifteen_node_perfect_level_two + in: + root: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] + n: 15 + x: 4 + out: true + - name: fifteen_node_perfect_leaf + in: + root: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] + n: 15 + x: 15 + out: true + - name: fifteen_node_sparse_root + in: + root: + [ + 1, + 2, + 3, + 4, + null, + 5, + 6, + 7, + null, + null, + 8, + 9, + 10, + null, + null, + 11, + 12, + 13, + 14, + 15, + ] + n: 15 + x: 1 + out: true + - name: fifteen_node_sparse_middle + in: + root: + [ + 1, + 2, + 3, + 4, + null, + 5, + 6, + 7, + null, + null, + 8, + 9, + 10, + null, + null, + 11, + 12, + 13, + 14, + 15, + ] + n: 15 + x: 3 + out: false + - name: fifteen_node_sparse_deep_node + in: + root: + [ + 1, + 2, + 3, + 4, + null, + 5, + 6, + 7, + null, + null, + 8, + 9, + 10, + null, + null, + 11, + 12, + 13, + 14, + 15, + ] + n: 15 + x: 8 + out: true + - name: twenty_one_node_left_subtree_equals_half + in: + root: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + ] + n: 21 + x: 1 + out: true + - name: twenty_one_node_internal_parent_majority + in: + root: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + ] + n: 21 + x: 5 + out: true + - name: thirty_one_node_perfect_root + in: + root: + [ + 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, + ] + n: 31 + x: 1 + out: false + - name: thirty_one_node_perfect_internal + in: + root: + [ + 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, + ] + n: 31 + x: 7 + out: true + - name: large_51_internal_three_way_tie + in: + root: + [ + 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, + ] + n: 51 + x: 2 + out: false + - name: large_63_perfect_root_tie + in: + root: + [ + 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, + ] + n: 63 + x: 1 + out: false + - name: large_75_root_left_majority + in: + root: + [ + 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, + ] + n: 75 + x: 1 + out: true + - name: large_91_root_left_majority + in: + root: + [ + 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, + ] + n: 91 + x: 1 + out: true + - name: large_97_root_left_majority + in: + root: + [ + 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, + ] + n: 97 + x: 1 + out: true + - name: large_99_root_left_majority + in: + root: + [ + 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, + ] + n: 99 + x: 1 + out: true diff --git a/tests/1001-1500/1145. binary-tree-coloring-game/sol.cpp b/tests/1001-1500/1145. binary-tree-coloring-game/sol.cpp new file mode 100644 index 00000000..74cdea06 --- /dev/null +++ b/tests/1001-1500/1145. binary-tree-coloring-game/sol.cpp @@ -0,0 +1,44 @@ +/** + * 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: + int subtreeCount(TreeNode* node) { + if (node == nullptr) return 0; + int leftCount = subtreeCount(node->left); + int rightCount = subtreeCount(node->right); + return leftCount + rightCount + 1; + } + + bool btreeGameWinningMove(TreeNode* root, int n, int x) { + std::queue q; + q.push(root); + TreeNode* node = nullptr; + while (!q.empty()) { + TreeNode* front = q.front(); + q.pop(); + if (front->val == x) { + node = front; + break; + } + if (front->left) q.push(front->left); + if (front->right) q.push(front->right); + } + + int leftCount = subtreeCount(node->left); + int rightCount = subtreeCount(node->right); + int parentCount = n - leftCount - rightCount - 1; + if (parentCount > leftCount + rightCount) return true; + else if (leftCount > parentCount + rightCount) return true; + else if (rightCount > parentCount + leftCount) return true; + return false; + } +}; diff --git a/tests/1001-1500/1145. binary-tree-coloring-game/sol.cs b/tests/1001-1500/1145. binary-tree-coloring-game/sol.cs new file mode 100644 index 00000000..bd43e3cd --- /dev/null +++ b/tests/1001-1500/1145. binary-tree-coloring-game/sol.cs @@ -0,0 +1,44 @@ +/** + * 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 { + private int SubtreeCount(TreeNode node) { + if (node == null) return 0; + int leftCount = SubtreeCount(node.left); + int rightCount = SubtreeCount(node.right); + return leftCount + rightCount + 1; + } + + public bool BtreeGameWinningMove(TreeNode root, int n, int x) { + var queue = new System.Collections.Generic.Queue(); + queue.Enqueue(root); + TreeNode node = null; + while (queue.Count > 0) { + TreeNode front = queue.Dequeue(); + if (front.val == x) { + node = front; + break; + } + if (front.left != null) queue.Enqueue(front.left); + if (front.right != null) queue.Enqueue(front.right); + } + + int leftCount = SubtreeCount(node.left); + int rightCount = SubtreeCount(node.right); + int parentCount = n - leftCount - rightCount - 1; + if (parentCount > leftCount + rightCount) return true; + else if (leftCount > parentCount + rightCount) return true; + else if (rightCount > parentCount + leftCount) return true; + return false; + } +} diff --git a/tests/1001-1500/1145. binary-tree-coloring-game/sol.dart b/tests/1001-1500/1145. binary-tree-coloring-game/sol.dart new file mode 100644 index 00000000..a8666cf5 --- /dev/null +++ b/tests/1001-1500/1145. binary-tree-coloring-game/sol.dart @@ -0,0 +1,43 @@ +/** + * 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 subtreeCount(TreeNode? node) { + if (node == null) return 0; + int leftCount = subtreeCount(node.left); + int rightCount = subtreeCount(node.right); + return leftCount + rightCount + 1; + } + + bool btreeGameWinningMove(TreeNode? root, int n, int x) { + var queue = [root]; + TreeNode? node; + while (queue.isNotEmpty) { + var front = queue.removeAt(0); + if (front!.val == x) { + node = front; + break; + } + if (front.left != null) queue.add(front.left); + if (front.right != null) queue.add(front.right); + } + + int leftCount = subtreeCount(node!.left); + int rightCount = subtreeCount(node.right); + int parentCount = n - leftCount - rightCount - 1; + if (parentCount > leftCount + rightCount) { + return true; + } else if (leftCount > parentCount + rightCount) { + return true; + } else if (rightCount > parentCount + leftCount) { + return true; + } + return false; + } +} diff --git a/tests/1001-1500/1145. binary-tree-coloring-game/sol.go b/tests/1001-1500/1145. binary-tree-coloring-game/sol.go new file mode 100644 index 00000000..87923693 --- /dev/null +++ b/tests/1001-1500/1145. binary-tree-coloring-game/sol.go @@ -0,0 +1,48 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func btreeGameWinningMove(root *TreeNode, n int, x int) bool { + var subtreeCount func(*TreeNode) int + subtreeCount = func(node *TreeNode) int { + if node == nil { + return 0 + } + leftCount := subtreeCount(node.Left) + rightCount := subtreeCount(node.Right) + return leftCount + rightCount + 1 + } + + queue := []*TreeNode{root} + var node *TreeNode + for len(queue) > 0 { + front := queue[0] + queue = queue[1:] + if front.Val == x { + node = front + break + } + if front.Left != nil { + queue = append(queue, front.Left) + } + if front.Right != nil { + queue = append(queue, front.Right) + } + } + + leftCount := subtreeCount(node.Left) + rightCount := subtreeCount(node.Right) + parentCount := n - leftCount - rightCount - 1 + if parentCount > leftCount+rightCount { + return true + } else if leftCount > parentCount+rightCount { + return true + } else if rightCount > parentCount+leftCount { + return true + } + return false +} diff --git a/tests/1001-1500/1145. binary-tree-coloring-game/sol.java b/tests/1001-1500/1145. binary-tree-coloring-game/sol.java new file mode 100644 index 00000000..0c90f589 --- /dev/null +++ b/tests/1001-1500/1145. binary-tree-coloring-game/sol.java @@ -0,0 +1,46 @@ +/** + * 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 { + private int subtreeCount(TreeNode node) { + if (node == null) return 0; + int leftCount = subtreeCount(node.left); + int rightCount = subtreeCount(node.right); + return leftCount + rightCount + 1; + } + + public boolean btreeGameWinningMove(TreeNode root, int n, int x) { + java.util.Queue queue = new java.util.LinkedList<>(); + queue.offer(root); + TreeNode node = null; + while (!queue.isEmpty()) { + TreeNode front = queue.poll(); + if (front.val == x) { + node = front; + break; + } + if (front.left != null) queue.offer(front.left); + if (front.right != null) queue.offer(front.right); + } + + int leftCount = subtreeCount(node.left); + int rightCount = subtreeCount(node.right); + int parentCount = n - leftCount - rightCount - 1; + if (parentCount > leftCount + rightCount) return true; + else if (leftCount > parentCount + rightCount) return true; + else if (rightCount > parentCount + leftCount) return true; + return false; + } +} diff --git a/tests/1001-1500/1145. binary-tree-coloring-game/sol.kt b/tests/1001-1500/1145. binary-tree-coloring-game/sol.kt new file mode 100644 index 00000000..7e7fbade --- /dev/null +++ b/tests/1001-1500/1145. binary-tree-coloring-game/sol.kt @@ -0,0 +1,41 @@ +/** + * 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 { + private fun subtreeCount(node: TreeNode?): Int { + if (node == null) return 0 + val leftCount = subtreeCount(node.left) + val rightCount = subtreeCount(node.right) + return leftCount + rightCount + 1 + } + + fun btreeGameWinningMove(root: TreeNode?, n: Int, x: Int): Boolean { + val queue = java.util.LinkedList() + queue.offer(root) + var node: TreeNode? = null + while (queue.isNotEmpty()) { + val front = queue.poll() + if (front!!.`val` == x) { + node = front + break + } + if (front.left != null) queue.offer(front.left) + if (front.right != null) queue.offer(front.right) + } + + val leftCount = subtreeCount(node!!.left) + val rightCount = subtreeCount(node.right) + val parentCount = n - leftCount - rightCount - 1 + if (parentCount > leftCount + rightCount) return true + else if (leftCount > parentCount + rightCount) return true + else if (rightCount > parentCount + leftCount) return true + return false + } +} diff --git a/tests/1001-1500/1145. binary-tree-coloring-game/sol.py b/tests/1001-1500/1145. binary-tree-coloring-game/sol.py new file mode 100644 index 00000000..3715652c --- /dev/null +++ b/tests/1001-1500/1145. binary-tree-coloring-game/sol.py @@ -0,0 +1,43 @@ +from collections import deque + + +# 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 subtree_count(self, node): + if node is None: + return 0 + + left_count = self.subtree_count(node.left) + right_count = self.subtree_count(node.right) + return left_count + right_count + 1 + + def btreeGameWinningMove(self, root: Optional[TreeNode], n: int, x: int) -> bool: + # find the node with value x + queue = deque([root]) + node = None + while queue: + front = queue.popleft() + if front.val == x: + node = front + break + if front.left: + queue.append(front.left) + if front.right: + queue.append(front.right) + + # count subtree length going from either left, right or parent directions + left_count = self.subtree_count(node.left) + right_count = self.subtree_count(node.right) + parent_count = n - left_count - right_count - 1 + if parent_count > left_count + right_count: + return True + elif left_count > parent_count + right_count: + return True + elif right_count > parent_count + left_count: + return True + return False diff --git a/tests/1001-1500/1145. binary-tree-coloring-game/sol.py2 b/tests/1001-1500/1145. binary-tree-coloring-game/sol.py2 new file mode 100644 index 00000000..15213fb8 --- /dev/null +++ b/tests/1001-1500/1145. binary-tree-coloring-game/sol.py2 @@ -0,0 +1,44 @@ +# 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 subtree_count(self, node): + if node is None: + return 0 + left_count = self.subtree_count(node.left) + right_count = self.subtree_count(node.right) + return left_count + right_count + 1 + + def btreeGameWinningMove(self, root, n, x): + """ + :type root: Optional[TreeNode] + :type n: int + :type x: int + :rtype: bool + """ + from collections import deque + queue = deque([root]) + node = None + while queue: + front = queue.popleft() + if front.val == x: + node = front + break + if front.left: + queue.append(front.left) + if front.right: + queue.append(front.right) + + left_count = self.subtree_count(node.left) + right_count = self.subtree_count(node.right) + parent_count = n - left_count - right_count - 1 + if parent_count > left_count + right_count: + return True + elif left_count > parent_count + right_count: + return True + elif right_count > parent_count + left_count: + return True + return False diff --git a/tests/1001-1500/1145. binary-tree-coloring-game/sol.rb b/tests/1001-1500/1145. binary-tree-coloring-game/sol.rb new file mode 100644 index 00000000..6c453574 --- /dev/null +++ b/tests/1001-1500/1145. binary-tree-coloring-game/sol.rb @@ -0,0 +1,45 @@ +# 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} n +# @param {Integer} x +# @return {Boolean} +def btree_game_winning_move(root, n, x) + subtree_count = lambda do |node| + return 0 if node.nil? + left_count = subtree_count.call(node.left) + right_count = subtree_count.call(node.right) + left_count + right_count + 1 + end + + queue = [root] + node = nil + until queue.empty? + front = queue.shift + if front.val == x + node = front + break + end + queue.push(front.left) if front.left + queue.push(front.right) if front.right + end + + left_count = subtree_count.call(node.left) + right_count = subtree_count.call(node.right) + parent_count = n - left_count - right_count - 1 + if parent_count > left_count + right_count + return true + elsif left_count > parent_count + right_count + return true + elsif right_count > parent_count + left_count + return true + end + false +end diff --git a/tests/1001-1500/1145. binary-tree-coloring-game/sol.rs b/tests/1001-1500/1145. binary-tree-coloring-game/sol.rs new file mode 100644 index 00000000..4c072ed0 --- /dev/null +++ b/tests/1001-1500/1145. binary-tree-coloring-game/sol.rs @@ -0,0 +1,66 @@ +// 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 btree_game_winning_move(root: Option>>, n: i32, x: i32) -> bool { + fn subtree_count(node: Option<&Rc>>) -> i32 { + match node { + None => 0, + Some(n) => { + let n = n.borrow(); + let left_count = subtree_count(n.left.as_ref()); + let right_count = subtree_count(n.right.as_ref()); + left_count + right_count + 1 + } + } + } + + let mut queue = std::collections::VecDeque::new(); + queue.push_back(root.clone()); + let mut target: Option>> = None; + while let Some(front) = queue.pop_front() { + if let Some(f) = front { + if f.borrow().val == x { + target = Some(f.clone()); + break; + } + let f = f.borrow(); + if f.left.is_some() { + queue.push_back(f.left.clone()); + } + if f.right.is_some() { + queue.push_back(f.right.clone()); + } + } + } + + let target = target.unwrap(); + let target = target.borrow(); + let left_count = subtree_count(target.left.as_ref()); + let right_count = subtree_count(target.right.as_ref()); + let parent_count = n - left_count - right_count - 1; + if parent_count > left_count + right_count { + return true; + } else if left_count > parent_count + right_count { + return true; + } else if right_count > parent_count + left_count { + return true; + } + false + } +} diff --git a/tests/1001-1500/1145. binary-tree-coloring-game/sol.swift b/tests/1001-1500/1145. binary-tree-coloring-game/sol.swift new file mode 100644 index 00000000..b7051900 --- /dev/null +++ b/tests/1001-1500/1145. binary-tree-coloring-game/sol.swift @@ -0,0 +1,49 @@ +/** + * 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 subtreeCount(_ node: TreeNode?) -> Int { + guard let node = node else { return 0 } + let leftCount = subtreeCount(node.left) + let rightCount = subtreeCount(node.right) + return leftCount + rightCount + 1 + } + + func btreeGameWinningMove(_ root: TreeNode?, _ n: Int, _ x: Int) -> Bool { + var queue = [root] + var node: TreeNode? = nil + while !queue.isEmpty { + guard let front = queue.removeFirst() else { continue } + if front.val == x { + node = front + break + } + if let left = front.left { queue.append(left) } + if let right = front.right { queue.append(right) } + } + + let leftCount = subtreeCount(node!.left) + let rightCount = subtreeCount(node!.right) + let parentCount = n - leftCount - rightCount - 1 + if parentCount > leftCount + rightCount { + return true + } else if leftCount > parentCount + rightCount { + return true + } else if rightCount > parentCount + leftCount { + return true + } + return false + } +} diff --git a/tests/1001-1500/1145. binary-tree-coloring-game/sol.ts b/tests/1001-1500/1145. binary-tree-coloring-game/sol.ts new file mode 100644 index 00000000..20f6857c --- /dev/null +++ b/tests/1001-1500/1145. binary-tree-coloring-game/sol.ts @@ -0,0 +1,46 @@ +/** + * 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 btreeGameWinningMove( + root: TreeNode | null, + n: number, + x: number, +): boolean { + const subtreeCount = (node: TreeNode | null): number => { + if (node === null) return 0; + const leftCount = subtreeCount(node.left); + const rightCount = subtreeCount(node.right); + return leftCount + rightCount + 1; + }; + + const queue: (TreeNode | null)[] = [root]; + let node: TreeNode | null = null; + while (queue.length > 0) { + const front = queue.shift()!; + if (front.val === x) { + node = front; + break; + } + if (front.left !== null) queue.push(front.left); + if (front.right !== null) queue.push(front.right); + } + + const leftCount = subtreeCount(node!.left); + const rightCount = subtreeCount(node!.right); + const parentCount = n - leftCount - rightCount - 1; + if (parentCount > leftCount + rightCount) return true; + else if (leftCount > parentCount + rightCount) return true; + else if (rightCount > parentCount + leftCount) return true; + return false; +} diff --git a/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/manifest.yaml b/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/manifest.yaml new file mode 100644 index 00000000..5fd7c70f --- /dev/null +++ b/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/manifest.yaml @@ -0,0 +1,223 @@ +entry: + id: 1147 + title: longest-chunked-palindrome-decomposition + params: + text: + type: string + call: + cpp: "Solution().longestDecomposition({text})" + rust: "Solution::longest_decomposition({text})" + python3: "Solution().longestDecomposition({text})" + python2: "Solution().longestDecomposition({text})" + ruby: "longest_decomposition({text})" + java: "new Solution().longestDecomposition({text})" + csharp: "new Solution().LongestDecomposition({text})" + kotlin: "Solution().longestDecomposition({text})" + go: "longestDecomposition({text})" + dart: "Solution().longestDecomposition({text})" + swift: "Solution().longestDecomposition({text})" + typescript: "longestDecomposition({text})" +judge: + type: exact +limits: + time_ms: 5000 + memory_mb: 256 +oracle: + python3: + call: "Checker().longestDecomposition(text, {result})" + checker: | + class Checker: + def longestDecomposition(self, text, result): + if type(result) is not int: + return False + left, right, chunks = 0, len(text) - 1, 0 + while left <= right: + for size in range(1, (right - left + 1) // 2 + 1): + if text[left:left + size] == text[right - size + 1:right + 1]: + chunks += 2 + left += size + right -= size + break + else: + return result == chunks + 1 + return result == chunks +seed: 1147 +tests: + - name: example-one + in: + text: "ghiabcdefhelloadamhelloabcdefghi" + out: 7 + - name: example-two + in: + text: "merchant" + out: 1 + - name: example-three + in: + text: "antaprezatepzapreanta" + out: 11 + - name: single-character + in: + text: "a" + out: 1 + - name: two-distinct + in: + text: "ab" + out: 1 + - name: two-equal + in: + text: "aa" + out: 2 + - name: three-palindrome + in: + text: "aba" + out: 3 + - name: four-palindrome + in: + text: "abba" + out: 4 + - name: no-matching-ends + in: + text: "abcdefg" + out: 1 + - name: repeated-single-character + in: + text: "aaaaaaaaaa" + out: 10 + - name: alternating-repeated-block + in: + text: "abababab" + out: 4 + - name: character-palindrome + in: + text: "racecar" + out: 7 + - name: nested-character-palindrome + in: + text: "abcxyzzyxcba" + out: 12 + - name: repeated-three-letter-block + in: + text: "abcabcabcabc" + out: 4 + - name: many-single-character-chunks + in: + text: "abcddcba" + out: 8 + - name: unmatched-central-block + in: + text: "abccdefcba" + out: 7 + - name: overlapping-equal-prefixes + in: + text: "aaaaabaaaaa" + out: 11 + - name: word-sized-chunks + in: + text: "onetwothreefourthreetwoone" + out: 7 + - name: near-palindrome-central-mismatch + in: + text: "abccbxba" + out: 5 + - name: mixed-chunk-lengths + in: + text: "levelupuplevel" + out: 12 + - name: repeated-outer-and-inner-blocks + in: + text: "abcxyzabcxyzabc" + out: 5 + - name: long-edge-chunk + in: + text: "zzzaaaazzz" + out: 10 + - name: even-character-palindrome + in: + text: "aabcddcbaa" + out: 10 + - name: two-identical-long-chunks + in: + text: "aabcaabc" + out: 2 + - name: repeated-palindromic-block + in: + text: "abcbaabcba" + out: 10 + - name: odd-character-palindrome + in: + text: "xyzabccbazxy" + out: 10 + - name: deep-single-character-decomposition + in: + text: "abcdeffedcba" + out: 12 + - name: classic-overlap-pattern + in: + text: "abacabadabacaba" + out: 15 + - name: alphabet-with-single-center + in: + text: "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba" + out: 51 + - name: long-distinct-string + in: + text: "abcdefghijklmno" + out: 1 + - name: almost-uniform-unmatched + in: + text: "aaaaab" + out: 1 + - name: shortest-outer-match-not-character + in: + text: "volvo" + out: 3 + - name: repeated-two-letter-chunks + in: + text: "xyzxyz" + out: 2 + - name: nontrivial-center-after-pairs + in: + text: "foobarbazbarfoo" + out: 5 + - name: generated-max-binary + seed: 114701 + in: + text: + gen: str + len: 1000 + alphabet: "ab" + - name: generated-max-ternary + seed: 114702 + in: + text: + gen: str + len: 1000 + alphabet: "abc" + - name: generated-max-small-alphabet + seed: 114703 + in: + text: + gen: str + len: 1000 + alphabet: "abcde" + - name: generated-max-half-alphabet + seed: 114704 + in: + text: + gen: str + len: 1000 + alphabet: "abcdefghijklm" + - name: generated-max-full-alphabet + seed: 114705 + in: + text: + gen: str + len: 1000 + alphabet: "abcdefghijklmnopqrstuvwxyz" + - name: generated-max-biased-alphabet + seed: 114706 + in: + text: + gen: str + len: 1000 + alphabet: "aaaabbc" diff --git a/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.cpp b/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.cpp new file mode 100644 index 00000000..cbb29161 --- /dev/null +++ b/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int longestDecomposition(string text) { + int i = 0, j = text.size() - 1, n = 0, count = 0; + while (i <= j) { + if (text[i] == text[j]) { + if (text.substr(i, n + 1) == text.substr(j, n + 1)) { + count += 2; + i += n + 1; + j -= 1; + n = 0; + continue; + } + } + j -= 1; + n += 1; + } + return i == j + 1 ? count : count - 1; + } +}; diff --git a/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.cs b/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.cs new file mode 100644 index 00000000..f1770c9c --- /dev/null +++ b/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.cs @@ -0,0 +1,19 @@ +public class Solution { + public int LongestDecomposition(string text) { + int i = 0, j = text.Length - 1, n = 0, count = 0; + while (i <= j) { + if (text[i] == text[j]) { + if (text.Substring(i, n + 1) == text.Substring(j, n + 1)) { + count += 2; + i += n + 1; + j -= 1; + n = 0; + continue; + } + } + j -= 1; + n += 1; + } + return i == j + 1 ? count : count - 1; + } +} diff --git a/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.dart b/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.dart new file mode 100644 index 00000000..ad5fba21 --- /dev/null +++ b/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.dart @@ -0,0 +1,19 @@ +class Solution { + int longestDecomposition(String text) { + int i = 0, j = text.length - 1, n = 0, count = 0; + while (i <= j) { + if (text[i] == text[j]) { + if (text.substring(i, i + n + 1) == text.substring(j, j + n + 1)) { + count += 2; + i += n + 1; + j -= 1; + n = 0; + continue; + } + } + j -= 1; + n += 1; + } + return i == j + 1 ? count : count - 1; + } +} diff --git a/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.go b/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.go new file mode 100644 index 00000000..a6123cac --- /dev/null +++ b/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.go @@ -0,0 +1,20 @@ +func longestDecomposition(text string) int { + i, j, n, count := 0, len(text)-1, 0, 0 + for i <= j { + if text[i] == text[j] { + if text[i:i+n+1] == text[j:j+n+1] { + count += 2 + i += n + 1 + j -= 1 + n = 0 + continue + } + } + j -= 1 + n += 1 + } + if i == j+1 { + return count + } + return count - 1 +} diff --git a/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.java b/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.java new file mode 100644 index 00000000..40e11390 --- /dev/null +++ b/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.java @@ -0,0 +1,19 @@ +class Solution { + public int longestDecomposition(String text) { + int i = 0, j = text.length() - 1, n = 0, count = 0; + while (i <= j) { + if (text.charAt(i) == text.charAt(j)) { + if (text.substring(i, i + n + 1).equals(text.substring(j, j + n + 1))) { + count += 2; + i += n + 1; + j -= 1; + n = 0; + continue; + } + } + j -= 1; + n += 1; + } + return i == j + 1 ? count : count - 1; + } +} diff --git a/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.kt b/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.kt new file mode 100644 index 00000000..a0f11071 --- /dev/null +++ b/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.kt @@ -0,0 +1,22 @@ +class Solution { + fun longestDecomposition(text: String): Int { + var i = 0 + var j = text.length - 1 + var n = 0 + var count = 0 + while (i <= j) { + if (text[i] == text[j]) { + if (text.substring(i, i + n + 1) == text.substring(j, j + n + 1)) { + count += 2 + i += n + 1 + j -= 1 + n = 0 + continue + } + } + j -= 1 + n += 1 + } + return if (i == j + 1) count else count - 1 + } +} diff --git a/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.py b/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.py new file mode 100644 index 00000000..d67dd7de --- /dev/null +++ b/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.py @@ -0,0 +1,19 @@ +class Solution: + def longestDecomposition(self, text: str) -> int: + ( + i, + j, + n, + count, + ) = 0, len(text) - 1, 0, 0 + while i <= j: + if text[i] == text[j]: + if text[i : i + n + 1] == text[j : j + n + 1]: + count += 2 + i += n + 1 + j -= 1 + n = 0 + continue + j -= 1 + n += 1 + return count if i == j + 1 else count - 1 diff --git a/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.py2 b/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.py2 new file mode 100644 index 00000000..a7397657 --- /dev/null +++ b/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.py2 @@ -0,0 +1,18 @@ +class Solution(object): + def longestDecomposition(self, text): + """ + :type text: str + :rtype: int + """ + i, j, n, count = 0, len(text) - 1, 0, 0 + while i <= j: + if text[i] == text[j]: + if text[i:i+n+1] == text[j:j+n+1]: + count += 2 + i += n + 1 + j -= 1 + n = 0 + continue + j -= 1 + n += 1 + return count if i == j + 1 else count - 1 diff --git a/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.rb b/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.rb new file mode 100644 index 00000000..6829718f --- /dev/null +++ b/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.rb @@ -0,0 +1,19 @@ +# @param {String} text +# @return {Integer} +def longest_decomposition(text) + i, j, n, count = 0, text.length - 1, 0, 0 + while i <= j + if text[i] == text[j] + if text[i, n+1] == text[j, n+1] + count += 2 + i += n + 1 + j -= 1 + n = 0 + next + end + end + j -= 1 + n += 1 + end + i == j + 1 ? count : count - 1 +end diff --git a/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.rs b/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.rs new file mode 100644 index 00000000..9f9421eb --- /dev/null +++ b/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.rs @@ -0,0 +1,23 @@ +impl Solution { + pub fn longest_decomposition(text: String) -> i32 { + let bytes = text.as_bytes(); + let mut i = 0; + let mut j = text.len() as i32 - 1; + let mut n = 0; + let mut count = 0; + while i <= j { + if bytes[i as usize] == bytes[j as usize] { + if text[i as usize..i as usize + n as usize + 1] == text[j as usize..j as usize + n as usize + 1] { + count += 2; + i += n + 1; + j -= 1; + n = 0; + continue; + } + } + j -= 1; + n += 1; + } + if i == j + 1 { count } else { count - 1 } + } +} diff --git a/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.swift b/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.swift new file mode 100644 index 00000000..9f029539 --- /dev/null +++ b/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func longestDecomposition(_ text: String) -> Int { + let chars = Array(text) + var i = 0, j = chars.count - 1, n = 0, count = 0 + while i <= j { + if chars[i] == chars[j] { + if String(chars[i...i+n]) == String(chars[j...j+n]) { + count += 2 + i += n + 1 + j -= 1 + n = 0 + continue + } + } + j -= 1 + n += 1 + } + return i == j + 1 ? count : count - 1 + } +} diff --git a/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.ts b/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.ts new file mode 100644 index 00000000..cf037939 --- /dev/null +++ b/tests/1001-1500/1147. longest-chunked-palindrome-decomposition/sol.ts @@ -0,0 +1,20 @@ +function longestDecomposition(text: string): number { + let i = 0, + j = text.length - 1, + n = 0, + count = 0; + while (i <= j) { + if (text[i] === text[j]) { + if (text.substring(i, i + n + 1) === text.substring(j, j + n + 1)) { + count += 2; + i += n + 1; + j -= 1; + n = 0; + continue; + } + } + j -= 1; + n += 1; + } + return i === j + 1 ? count : count - 1; +} diff --git a/tests/1001-1500/1154. day-of-the-year/manifest.yaml b/tests/1001-1500/1154. day-of-the-year/manifest.yaml new file mode 100644 index 00000000..0f759f67 --- /dev/null +++ b/tests/1001-1500/1154. day-of-the-year/manifest.yaml @@ -0,0 +1,207 @@ +entry: + id: 1154 + title: day-of-the-year + params: + date: + type: string + call: + cpp: "Solution().dayOfYear({date})" + rust: "Solution::day_of_year({date})" + python3: "Solution().dayOfYear({date})" + python2: "Solution().dayOfYear({date})" + ruby: "day_of_year({date})" + java: "new Solution().dayOfYear({date})" + csharp: "new Solution().DayOfYear({date})" + kotlin: "Solution().dayOfYear({date})" + go: "dayOfYear({date})" + dart: "Solution().dayOfYear({date})" + swift: "Solution().dayOfYear({date})" + typescript: "dayOfYear({date})" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().dayOfYear(date, {result})" + checker: | + class Checker: + def dayOfYear(self, date, result): + if ( + type(result) is not int + or not isinstance(date, str) + or len(date) != 10 + or date[4] != "-" + or date[7] != "-" + or not (date[:4] + date[5:7] + date[8:]).isdigit() + ): + return False + y, m, d = int(date[:4]), int(date[5:7]), int(date[8:]) + leap = y % 400 == 0 or (y % 4 == 0 and y % 100 != 0) + days = [31, 29 if leap else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + if not (1900 <= y <= 2019 and 1 <= m <= 12 and 1 <= d <= days[m-1]): + return False + return result == d + sum(days[:m-1]) +seed: 1154 +tests: + - name: example-january + in: + date: "2019-01-09" + out: 9 + - name: example-february + in: + date: "2019-02-10" + out: 41 + - name: lower-bound + in: + date: "1900-01-01" + out: 1 + - name: upper-bound + in: + date: "2019-12-31" + out: 365 + - name: leap-2000 + in: + date: "2000-02-29" + out: 60 + - name: nonleap-1900 + in: + date: "1900-02-28" + out: 59 + - name: nonleap-1900-march + in: + date: "1900-03-01" + out: 60 + - name: leap-1904 + in: + date: "1904-02-29" + out: 60 + - name: century-2000-march + in: + date: "2000-03-01" + out: 61 + - name: nonleap-current-february + in: + date: "2019-02-28" + out: 59 + - name: january-first + in: + date: "2015-01-01" + out: 1 + - name: january-last + in: + date: "2015-01-31" + out: 31 + - name: february-first + in: + date: "2015-02-01" + out: 32 + - name: february-last + in: + date: "2015-02-28" + out: 59 + - name: march-first + in: + date: "2015-03-01" + out: 60 + - name: march-last + in: + date: "2015-03-31" + out: 90 + - name: april-first + in: + date: "2016-04-01" + out: 92 + - name: april-last + in: + date: "2016-04-30" + out: 121 + - name: may-last + in: + date: "2016-05-31" + out: 152 + - name: june-last + in: + date: "2016-06-30" + out: 182 + - name: july-first + in: + date: "2016-07-01" + out: 183 + - name: july-last + in: + date: "2016-07-31" + out: 213 + - name: august-first + in: + date: "2016-08-01" + out: 214 + - name: august-last + in: + date: "2016-08-31" + out: 244 + - name: september-last + in: + date: "2016-09-30" + out: 274 + - name: october-first + in: + date: "2016-10-01" + out: 275 + - name: october-last + in: + date: "2016-10-31" + out: 305 + - name: november-last + in: + date: "2016-11-30" + out: 335 + - name: december-first + in: + date: "2016-12-01" + out: 336 + - name: leap-day-after + in: + date: "2012-03-01" + out: 61 + - name: leap-year-end + in: + date: "2012-12-31" + out: 366 + - name: old-leap-year + in: + date: "1924-02-29" + out: 60 + - name: recent-leap-year + in: + date: "2016-02-29" + out: 60 + - name: year-2001-midyear + in: + date: "2001-07-15" + out: 196 + - name: year-1999-end + in: + date: "1999-12-31" + out: 365 + - name: leap-year-january-first + in: + date: "2016-01-01" + out: 1 + - name: leap-year-february-before-leap-day + in: + date: "2016-02-28" + out: 59 + - name: leap-year-march-last + in: + date: "2016-03-31" + out: 91 + - name: nonleap-april-last + in: + date: "2019-04-30" + out: 120 + - name: nonleap-november-last + in: + date: "2019-11-30" + out: 334 diff --git a/tests/1001-1500/1154. day-of-the-year/sol.cpp b/tests/1001-1500/1154. day-of-the-year/sol.cpp new file mode 100644 index 00000000..dc4628d1 --- /dev/null +++ b/tests/1001-1500/1154. day-of-the-year/sol.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int dayOfYear(string date) { + unordered_map val = { + {1, 0}, {2, 31}, {3, 59}, {4, 90}, {5, 120}, {6, 151}, + {7, 181}, {8, 212}, {9, 243}, {10, 273}, {11, 304}, {12, 334} + }; + int d = stoi(date.substr(8)); + int m = stoi(date.substr(5, 2)); + int y = stoi(date.substr(0, 4)); + bool isLeap = (y % 400 == 0) || (y % 4 == 0 && y % 100 != 0); + if (isLeap) { + for (int i = 3; i <= 12; i++) { + val[i] += 1; + } + } + return d + val[m]; + } +}; diff --git a/tests/1001-1500/1154. day-of-the-year/sol.cs b/tests/1001-1500/1154. day-of-the-year/sol.cs new file mode 100644 index 00000000..28dc1ab1 --- /dev/null +++ b/tests/1001-1500/1154. day-of-the-year/sol.cs @@ -0,0 +1,18 @@ +public class Solution { + public int DayOfYear(string date) { + var val = new Dictionary { + {1, 0}, {2, 31}, {3, 59}, {4, 90}, {5, 120}, {6, 151}, + {7, 181}, {8, 212}, {9, 243}, {10, 273}, {11, 304}, {12, 334} + }; + int d = int.Parse(date.Substring(8)); + int m = int.Parse(date.Substring(5, 2)); + int y = int.Parse(date.Substring(0, 4)); + bool isLeap = (y % 400 == 0) || (y % 4 == 0 && y % 100 != 0); + if (isLeap) { + for (int i = 3; i <= 12; i++) { + val[i] += 1; + } + } + return d + val[m]; + } +} diff --git a/tests/1001-1500/1154. day-of-the-year/sol.dart b/tests/1001-1500/1154. day-of-the-year/sol.dart new file mode 100644 index 00000000..e51b0733 --- /dev/null +++ b/tests/1001-1500/1154. day-of-the-year/sol.dart @@ -0,0 +1,18 @@ +class Solution { + int dayOfYear(String date) { + Map val = { + 1: 0, 2: 31, 3: 59, 4: 90, 5: 120, 6: 151, + 7: 181, 8: 212, 9: 243, 10: 273, 11: 304, 12: 334 + }; + int d = int.parse(date.substring(8)); + int m = int.parse(date.substring(5, 7)); + int y = int.parse(date.substring(0, 4)); + bool isLeap = (y % 400 == 0) || (y % 4 == 0 && y % 100 != 0); + if (isLeap) { + for (int i = 3; i <= 12; i++) { + val[i] = val[i]! + 1; + } + } + return d + val[m]!; + } +} diff --git a/tests/1001-1500/1154. day-of-the-year/sol.go b/tests/1001-1500/1154. day-of-the-year/sol.go new file mode 100644 index 00000000..77819ec6 --- /dev/null +++ b/tests/1001-1500/1154. day-of-the-year/sol.go @@ -0,0 +1,16 @@ +func dayOfYear(date string) int { + val := map[int]int{ + 1: 0, 2: 31, 3: 59, 4: 90, 5: 120, 6: 151, + 7: 181, 8: 212, 9: 243, 10: 273, 11: 304, 12: 334, + } + d, _ := strconv.Atoi(date[8:]) + m, _ := strconv.Atoi(date[5:7]) + y, _ := strconv.Atoi(date[0:4]) + isLeap := (y%400 == 0) || (y%4 == 0 && y%100 != 0) + if isLeap { + for i := 3; i <= 12; i++ { + val[i] += 1 + } + } + return d + val[m] +} diff --git a/tests/1001-1500/1154. day-of-the-year/sol.java b/tests/1001-1500/1154. day-of-the-year/sol.java new file mode 100644 index 00000000..6f4df918 --- /dev/null +++ b/tests/1001-1500/1154. day-of-the-year/sol.java @@ -0,0 +1,15 @@ +class Solution { + public int dayOfYear(String date) { + int[] val = {0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334}; + int d = Integer.parseInt(date.substring(8)); + int m = Integer.parseInt(date.substring(5, 7)); + int y = Integer.parseInt(date.substring(0, 4)); + boolean isLeap = (y % 400 == 0) || (y % 4 == 0 && y % 100 != 0); + if (isLeap) { + for (int i = 3; i <= 12; i++) { + val[i] += 1; + } + } + return d + val[m]; + } +} diff --git a/tests/1001-1500/1154. day-of-the-year/sol.kt b/tests/1001-1500/1154. day-of-the-year/sol.kt new file mode 100644 index 00000000..d60f88f7 --- /dev/null +++ b/tests/1001-1500/1154. day-of-the-year/sol.kt @@ -0,0 +1,18 @@ +class Solution { + fun dayOfYear(date: String): Int { + val valMap = mutableMapOf( + 1 to 0, 2 to 31, 3 to 59, 4 to 90, 5 to 120, 6 to 151, + 7 to 181, 8 to 212, 9 to 243, 10 to 273, 11 to 304, 12 to 334 + ) + val d = date.substring(8).toInt() + val m = date.substring(5, 7).toInt() + val y = date.substring(0, 4).toInt() + val isLeap = (y % 400 == 0) || (y % 4 == 0 && y % 100 != 0) + if (isLeap) { + for (i in 3..12) { + valMap[i] = valMap[i]!! + 1 + } + } + return d + valMap[m]!! + } +} diff --git a/tests/1001-1500/1154. day-of-the-year/sol.py b/tests/1001-1500/1154. day-of-the-year/sol.py new file mode 100644 index 00000000..4bdccaf9 --- /dev/null +++ b/tests/1001-1500/1154. day-of-the-year/sol.py @@ -0,0 +1,27 @@ +class Solution: + def dayOfYear(self, date: str) -> int: + date = date + val = { + 1: 0, + 2: 31, + 3: 59, + 4: 90, + 5: 120, + 6: 151, + 7: 181, + 8: 212, + 9: 243, + 10: 273, + 11: 304, + 12: 334, + } + + d = int(date[8:]) + m = int(date[5:7]) + y = int(date[0:4]) + is_leap = (y % 400 == 0) or (y % 4 == 0 and y % 100 != 0) + if is_leap: + for i in range(3, 13): + val[i] += 1 + + return d + val[m] diff --git a/tests/1001-1500/1154. day-of-the-year/sol.py2 b/tests/1001-1500/1154. day-of-the-year/sol.py2 new file mode 100644 index 00000000..0857d1cd --- /dev/null +++ b/tests/1001-1500/1154. day-of-the-year/sol.py2 @@ -0,0 +1,15 @@ +class Solution(object): + def dayOfYear(self, date): + """ + :type date: str + :rtype: int + """ + val = {1: 0, 2: 31, 3: 59, 4: 90, 5: 120, 6: 151, 7: 181, 8: 212, 9: 243, 10: 273, 11: 304, 12: 334} + d = int(date[8:]) + m = int(date[5:7]) + y = int(date[0:4]) + is_leap = (y % 400 == 0) or (y % 4 == 0 and y % 100 != 0) + if is_leap: + for i in range(3, 13): + val[i] += 1 + return d + val[m] diff --git a/tests/1001-1500/1154. day-of-the-year/sol.rb b/tests/1001-1500/1154. day-of-the-year/sol.rb new file mode 100644 index 00000000..e6a4b235 --- /dev/null +++ b/tests/1001-1500/1154. day-of-the-year/sol.rb @@ -0,0 +1,13 @@ +# @param {String} date +# @return {Integer} +def day_of_year(date) + val = {1 => 0, 2 => 31, 3 => 59, 4 => 90, 5 => 120, 6 => 151, 7 => 181, 8 => 212, 9 => 243, 10 => 273, 11 => 304, 12 => 334} + d = date[8..9].to_i + m = date[5..6].to_i + y = date[0..3].to_i + is_leap = (y % 400 == 0) || (y % 4 == 0 && y % 100 != 0) + if is_leap + (3..12).each { |i| val[i] += 1 } + end + return d + val[m] +end diff --git a/tests/1001-1500/1154. day-of-the-year/sol.rs b/tests/1001-1500/1154. day-of-the-year/sol.rs new file mode 100644 index 00000000..1b4ea7f0 --- /dev/null +++ b/tests/1001-1500/1154. day-of-the-year/sol.rs @@ -0,0 +1,19 @@ +impl Solution { + pub fn day_of_year(date: String) -> i32 { + use std::collections::HashMap; + let mut val: HashMap = HashMap::from([ + (1, 0), (2, 31), (3, 59), (4, 90), (5, 120), (6, 151), + (7, 181), (8, 212), (9, 243), (10, 273), (11, 304), (12, 334), + ]); + let d: i32 = date[8..].parse().unwrap(); + let m: i32 = date[5..7].parse().unwrap(); + let y: i32 = date[0..4].parse().unwrap(); + let is_leap = (y % 400 == 0) || (y % 4 == 0 && y % 100 != 0); + if is_leap { + for i in 3..=12 { + *val.get_mut(&i).unwrap() += 1; + } + } + d + val[&m] + } +} diff --git a/tests/1001-1500/1154. day-of-the-year/sol.swift b/tests/1001-1500/1154. day-of-the-year/sol.swift new file mode 100644 index 00000000..075ccf46 --- /dev/null +++ b/tests/1001-1500/1154. day-of-the-year/sol.swift @@ -0,0 +1,18 @@ +class Solution { + func dayOfYear(_ date: String) -> Int { + var val: [Int: Int] = [ + 1: 0, 2: 31, 3: 59, 4: 90, 5: 120, 6: 151, + 7: 181, 8: 212, 9: 243, 10: 273, 11: 304, 12: 334 + ] + let d = Int(date.suffix(2))! + let m = Int(date[date.index(date.startIndex, offsetBy: 5).. dp(target + 1, 0); + dp[0] = 1; + + for (int i = 0; i < n; i++) { + vector newDp(target + 1, 0); + int windowSum = 0; + + for (int s = 1; s <= target; s++) { + windowSum = (windowSum + dp[s - 1]) % MOD; + + if (s > k) { + windowSum = (windowSum - dp[s - k - 1] + MOD) % MOD; + } + + newDp[s] = windowSum; + } + + dp = newDp; + } + + return dp[target]; + } +}; diff --git a/tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.cs b/tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.cs new file mode 100644 index 00000000..5fc16c29 --- /dev/null +++ b/tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.cs @@ -0,0 +1,27 @@ +public class Solution { + public int NumRollsToTarget(int n, int k, int target) { + const int MOD = 1000000007; + + int[] dp = new int[target + 1]; + dp[0] = 1; + + for (int i = 0; i < n; i++) { + int[] newDp = new int[target + 1]; + int windowSum = 0; + + for (int s = 1; s <= target; s++) { + windowSum = (windowSum + dp[s - 1]) % MOD; + + if (s > k) { + windowSum = (windowSum - dp[s - k - 1] + MOD) % MOD; + } + + newDp[s] = windowSum; + } + + dp = newDp; + } + + return dp[target]; + } +} diff --git a/tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.dart b/tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.dart new file mode 100644 index 00000000..7021c919 --- /dev/null +++ b/tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.dart @@ -0,0 +1,27 @@ +class Solution { + int numRollsToTarget(int n, int k, int target) { + const int MOD = 1000000007; + + var dp = List.filled(target + 1, 0); + dp[0] = 1; + + for (int i = 0; i < n; i++) { + var newDp = List.filled(target + 1, 0); + int windowSum = 0; + + for (int s = 1; s <= target; s++) { + windowSum = (windowSum + dp[s - 1]) % MOD; + + if (s > k) { + windowSum = (windowSum - dp[s - k - 1] + MOD) % MOD; + } + + newDp[s] = windowSum; + } + + dp = newDp; + } + + return dp[target]; + } +} diff --git a/tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.go b/tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.go new file mode 100644 index 00000000..b449e8bc --- /dev/null +++ b/tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.go @@ -0,0 +1,25 @@ +func numRollsToTarget(n int, k int, target int) int { + const MOD = 1000000007 + + dp := make([]int, target + 1) + dp[0] = 1 + + for i := 0; i < n; i++ { + newDp := make([]int, target + 1) + windowSum := 0 + + for s := 1; s <= target; s++ { + windowSum = (windowSum + dp[s - 1]) % MOD + + if s > k { + windowSum = (windowSum - dp[s - k - 1] + MOD) % MOD + } + + newDp[s] = windowSum + } + + dp = newDp + } + + return dp[target] +} diff --git a/tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.java b/tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.java new file mode 100644 index 00000000..bdf1bc40 --- /dev/null +++ b/tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.java @@ -0,0 +1,27 @@ +class Solution { + public int numRollsToTarget(int n, int k, int target) { + final int MOD = 1000000007; + + int[] dp = new int[target + 1]; + dp[0] = 1; + + for (int i = 0; i < n; i++) { + int[] newDp = new int[target + 1]; + int windowSum = 0; + + for (int s = 1; s <= target; s++) { + windowSum = (windowSum + dp[s - 1]) % MOD; + + if (s > k) { + windowSum = (windowSum - dp[s - k - 1] + MOD) % MOD; + } + + newDp[s] = windowSum; + } + + dp = newDp; + } + + return dp[target]; + } +} diff --git a/tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.kt b/tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.kt new file mode 100644 index 00000000..5851e706 --- /dev/null +++ b/tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.kt @@ -0,0 +1,27 @@ +class Solution { + fun numRollsToTarget(n: Int, k: Int, target: Int): Int { + val MOD = 1000000007 + + var dp = IntArray(target + 1) + dp[0] = 1 + + for (i in 0 until n) { + val newDp = IntArray(target + 1) + var windowSum = 0 + + for (s in 1..target) { + windowSum = (windowSum + dp[s - 1]) % MOD + + if (s > k) { + windowSum = (windowSum - dp[s - k - 1] + MOD) % MOD + } + + newDp[s] = windowSum + } + + dp = newDp + } + + return dp[target] + } +} diff --git a/tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.py b/tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.py new file mode 100644 index 00000000..b5f56bc4 --- /dev/null +++ b/tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.py @@ -0,0 +1,28 @@ +class Solution: + def numRollsToTarget(self, n: int, k: int, target: int) -> int: + MOD = 10**9 + 7 + + # dp[s] = number of ways to get sum 's' + dp = [0] * (target + 1) + dp[0] = 1 # One way to get sum 0 with 0 dice + + # We 'construct' the solution dimension by dimension (CBC style) + for _ in range(n): + new_dp = [0] * (target + 1) + window_sum = 0 + + # This is the 'Fast' part: instead of a k-loop, we use + # the property of the lattice's periodicity (the die faces) + for s in range(1, target + 1): + # Add the 'newest' possible face value contribution + window_sum = (window_sum + dp[s - 1]) % MOD + + # Subtract the contribution that is now 'out of range' (> k faces) + if s > k: + window_sum = (window_sum - dp[s - k - 1] + MOD) % MOD + + new_dp[s] = window_sum + + dp = new_dp + + return dp[target] diff --git a/tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.py2 b/tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.py2 new file mode 100644 index 00000000..84484811 --- /dev/null +++ b/tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.py2 @@ -0,0 +1,28 @@ +class Solution(object): + def numRollsToTarget(self, n, k, target): + """ + :type n: int + :type k: int + :type target: int + :rtype: int + """ + MOD = 10**9 + 7 + + dp = [0] * (target + 1) + dp[0] = 1 + + for _ in range(n): + new_dp = [0] * (target + 1) + window_sum = 0 + + for s in range(1, target + 1): + window_sum = (window_sum + dp[s - 1]) % MOD + + if s > k: + window_sum = (window_sum - dp[s - k - 1] + MOD) % MOD + + new_dp[s] = window_sum + + dp = new_dp + + return dp[target] diff --git a/tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.rb b/tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.rb new file mode 100644 index 00000000..c205dee6 --- /dev/null +++ b/tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.rb @@ -0,0 +1,29 @@ +# @param {Integer} n +# @param {Integer} k +# @param {Integer} target +# @return {Integer} +def num_rolls_to_target(n, k, target) + mod = 10**9 + 7 + + dp = Array.new(target + 1, 0) + dp[0] = 1 + + n.times do + new_dp = Array.new(target + 1, 0) + window_sum = 0 + + (1..target).each do |s| + window_sum = (window_sum + dp[s - 1]) % mod + + if s > k + window_sum = (window_sum - dp[s - k - 1] + mod) % mod + end + + new_dp[s] = window_sum + end + + dp = new_dp + end + + dp[target] +end diff --git a/tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.rs b/tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.rs new file mode 100644 index 00000000..10243e65 --- /dev/null +++ b/tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.rs @@ -0,0 +1,30 @@ +impl Solution { + pub fn num_rolls_to_target(n: i32, k: i32, target: i32) -> i32 { + const MOD: i32 = 1_000_000_007; + let n = n as usize; + let k = k as usize; + let target = target as usize; + + let mut dp = vec![0; target + 1]; + dp[0] = 1; + + for _ in 0..n { + let mut new_dp = vec![0; target + 1]; + let mut window_sum = 0; + + for s in 1..=target { + window_sum = (window_sum + dp[s - 1]) % MOD; + + if s > k { + window_sum = (window_sum - dp[s - k - 1] + MOD) % MOD; + } + + new_dp[s] = window_sum; + } + + dp = new_dp; + } + + dp[target] + } +} diff --git a/tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.swift b/tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.swift new file mode 100644 index 00000000..59d05e88 --- /dev/null +++ b/tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.swift @@ -0,0 +1,27 @@ +class Solution { + func numRollsToTarget(_ n: Int, _ k: Int, _ target: Int) -> Int { + let MOD = 1000000007 + + var dp = Array(repeating: 0, count: target + 1) + dp[0] = 1 + + for _ in 0.. k { + windowSum = (windowSum - dp[s - k - 1] + MOD) % MOD + } + + newDp[s] = windowSum + } + + dp = newDp + } + + return dp[target] + } +} diff --git a/tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.ts b/tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.ts new file mode 100644 index 00000000..76cb2e52 --- /dev/null +++ b/tests/1001-1500/1155. number-of-dice-rolls-with-target-sum/sol.ts @@ -0,0 +1,25 @@ +function numRollsToTarget(n: number, k: number, target: number): number { + const MOD = 1000000007; + + let dp: number[] = new Array(target + 1).fill(0); + dp[0] = 1; + + for (let i = 0; i < n; i++) { + const newDp: number[] = new Array(target + 1).fill(0); + let windowSum = 0; + + for (let s = 1; s <= target; s++) { + windowSum = (windowSum + dp[s - 1]) % MOD; + + if (s > k) { + windowSum = (windowSum - dp[s - k - 1] + MOD) % MOD; + } + + newDp[s] = windowSum; + } + + dp = newDp; + } + + return dp[target]; +} diff --git a/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/manifest.yaml b/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/manifest.yaml new file mode 100644 index 00000000..67b31b14 --- /dev/null +++ b/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/manifest.yaml @@ -0,0 +1,221 @@ +entry: + id: 1156 + title: "swap-for-longest-repeated-character-substring" + params: + text: + type: string + call: + cpp: "Solution().maxRepOpt1({text})" + rust: "Solution::max_rep_opt1({text})" + python3: "Solution().maxRepOpt1({text})" + python2: "Solution().maxRepOpt1({text})" + ruby: "max_rep_opt1({text})" + java: "new Solution().maxRepOpt1({text})" + csharp: "new Solution().MaxRepOpt1({text})" + kotlin: "Solution().maxRepOpt1({text})" + go: "maxRepOpt1({text})" + dart: "Solution().maxRepOpt1({text})" + swift: "Solution().maxRepOpt1({text})" + typescript: "maxRepOpt1({text})" +judge: + type: "exact" +limits: + time_ms: 500 + memory_mb: 300 +oracle: + python3: + call: "Checker().maxRepOpt1(text, {result})" + checker: | + from collections import Counter + + class Checker: + def maxRepOpt1(self, text, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + counts = Counter(text) + runs = [] + start = 0 + for index in range(1, len(text) + 1): + if index == len(text) or text[index] != text[start]: + runs.append((text[start], index - start)) + start = index + + best = 0 + for index, (ch, length) in enumerate(runs): + # A run can gain one matching character from elsewhere. + best = max(best, min(counts[ch], length + 1)) + # Exactly one intervening character permits joining two runs. + if (index + 2 < len(runs) and runs[index + 1][1] == 1 + and runs[index + 2][0] == ch): + best = max(best, min(counts[ch], length + 1 + runs[index + 2][1])) + return result == best +seed: 1156 +tests: + - name: official_one + in: + text: "ababa" + out: 3 + - name: official_two + in: + text: "aaabaaa" + out: 6 + - name: official_three + in: + text: "aaaaa" + out: 5 + - name: single + in: + text: "a" + out: 1 + - name: two_different + in: + text: "ab" + out: 1 + - name: two_equal + in: + text: "aa" + out: 2 + - name: all_distinct + in: + text: "abcdef" + out: 1 + - name: separated_pair + in: + text: "aba" + out: 2 + - name: separated_triplet + in: + text: "abcaa" + out: 3 + - name: two_groups + in: + text: "aabbb" + out: 3 + - name: swap_one_gap + in: + text: "aabaa" + out: 4 + - name: gap_larger_than_one + in: + text: "aabaca" + out: 4 + - name: alternating + in: + text: "abababab" + out: 3 + - name: dominant_middle + in: + text: "baaab" + out: 3 + - name: dominant_edges + in: + text: "aaabacaa" + out: 5 + - name: three_char_alphabet + in: + text: "abcabcabc" + out: 2 + - name: repeated_blocks + in: + text: "aabbccaa" + out: 3 + - name: unique_extra + in: + text: "aaaaab" + out: 5 + - name: no_swap_needed + in: + text: "bbbbac" + out: 4 + - name: late_pair + in: + text: "xyzxy" + out: 2 + - name: long_run_with_gap + in: + text: "aaabaaac" + out: 6 + - name: symmetric_bridge + in: + text: "aaaaabaaaaa" + out: 10 + - name: two_character_gap + in: + text: "aaabbaaac" + out: 4 + - name: minority_at_both_ends + in: + text: "baaaaab" + out: 5 + - name: oracle_small_1 + in: + text: "cabac" + - name: oracle_small_2 + in: + text: "ccadcc" + - name: oracle_small_3 + in: + text: "abccbaab" + - name: oracle_small_4 + in: + text: "zzxyzzx" + - name: oracle_small_5 + in: + text: "qwertqq" + - name: generated_max_binary + seed: 115601 + in: + text: + gen: str + len: 20000 + alphabet: "ab" + - name: oracle_pattern_1 + in: + text: "aabacada" + - name: oracle_pattern_2 + in: + text: "mnopmmop" + - name: oracle_pattern_3 + in: + text: "rrsrrt" + - name: oracle_pattern_4 + in: + text: "abacabad" + - name: oracle_pattern_5 + in: + text: "kkkkjkkk" + - name: generated_max_quaternary + seed: 115602 + in: + text: + gen: str + len: 20000 + alphabet: "abcd" + - name: generated_max_eight_letters + seed: 115603 + in: + text: + gen: str + len: 20000 + alphabet: "abcdefgh" + - name: generated_max_half_alphabet + seed: 115604 + in: + text: + gen: str + len: 20000 + alphabet: "abcdefghijklmn" + - name: generated_max_full_alphabet + seed: 115605 + in: + text: + gen: str + len: 20000 + alphabet: "abcdefghijklmnopqrstuvwxyz" + - name: generated_max_skewed_alphabet + seed: 115606 + in: + text: + gen: str + len: 20000 + alphabet: "aaaabc" diff --git a/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.cpp b/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.cpp new file mode 100644 index 00000000..d175bb62 --- /dev/null +++ b/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + int maxRepOpt1(string text) { + unordered_map total; + for (char c : text) { + total[c]++; + } + int n = text.length(); + int ans = 0; + + for (auto& [ch, ch_total] : total) { + int left = 0; + int count = 0; + + for (int right = 0; right < n; right++) { + if (text[right] == ch) { + count++; + } + + while ((right - left + 1) - count > 1) { + if (text[left] == ch) { + count--; + } + left++; + } + + ans = max(ans, min(right - left + 1, ch_total)); + } + } + + return ans; + } +}; diff --git a/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.cs b/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.cs new file mode 100644 index 00000000..5a7a0995 --- /dev/null +++ b/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.cs @@ -0,0 +1,38 @@ +public class Solution { + public int MaxRepOpt1(string text) { + Dictionary total = new Dictionary(); + foreach (char c in text) { + if (total.ContainsKey(c)) { + total[c]++; + } else { + total[c] = 1; + } + } + int n = text.Length; + int ans = 0; + + foreach (var kvp in total) { + char ch = kvp.Key; + int chTotal = kvp.Value; + int left = 0; + int count = 0; + + for (int right = 0; right < n; right++) { + if (text[right] == ch) { + count++; + } + + while ((right - left + 1) - count > 1) { + if (text[left] == ch) { + count--; + } + left++; + } + + ans = Math.Max(ans, Math.Min(right - left + 1, chTotal)); + } + } + + return ans; + } +} diff --git a/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.dart b/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.dart new file mode 100644 index 00000000..899e2eca --- /dev/null +++ b/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.dart @@ -0,0 +1,35 @@ +class Solution { + int maxRepOpt1(String text) { + Map total = {}; + for (var c in text.split('')) { + total[c] = (total[c] ?? 0) + 1; + } + int n = text.length; + int ans = 0; + + for (var ch in total.keys) { + int left = 0; + int count = 0; + + for (int right = 0; right < n; right++) { + if (text[right] == ch) { + count++; + } + + while ((right - left + 1) - count > 1) { + if (text[left] == ch) { + count--; + } + left++; + } + + int windowLen = right - left + 1; + ans = ans > (windowLen < total[ch]! ? windowLen : total[ch]!) + ? ans + : (windowLen < total[ch]! ? windowLen : total[ch]!); + } + } + + return ans; + } +} diff --git a/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.go b/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.go new file mode 100644 index 00000000..f74eff4a --- /dev/null +++ b/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.go @@ -0,0 +1,36 @@ +func maxRepOpt1(text string) int { + total := make(map[byte]int) + for i := 0; i < len(text); i++ { + total[text[i]]++ + } + n := len(text) + ans := 0 + + for ch := range total { + left := 0 + count := 0 + + for right := 0; right < n; right++ { + if text[right] == ch { + count++ + } + + for (right - left + 1) - count > 1 { + if text[left] == ch { + count-- + } + left++ + } + + current := right - left + 1 + if current > total[ch] { + current = total[ch] + } + if current > ans { + ans = current + } + } + } + + return ans +} diff --git a/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.java b/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.java new file mode 100644 index 00000000..1110b119 --- /dev/null +++ b/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.java @@ -0,0 +1,34 @@ +class Solution { + public int maxRepOpt1(String text) { + int[] total = new int[26]; + for (char c : text.toCharArray()) { + total[c - 'a']++; + } + int n = text.length(); + int ans = 0; + + for (int i = 0; i < 26; i++) { + if (total[i] == 0) continue; + char ch = (char)(i + 'a'); + int left = 0; + int count = 0; + + for (int right = 0; right < n; right++) { + if (text.charAt(right) == ch) { + count++; + } + + while ((right - left + 1) - count > 1) { + if (text.charAt(left) == ch) { + count--; + } + left++; + } + + ans = Math.max(ans, Math.min(right - left + 1, total[i])); + } + } + + return ans; + } +} diff --git a/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.kt b/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.kt new file mode 100644 index 00000000..130582f6 --- /dev/null +++ b/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.kt @@ -0,0 +1,34 @@ +class Solution { + fun maxRepOpt1(text: String): Int { + val total = IntArray(26) + for (c in text) { + total[c - 'a']++ + } + val n = text.length + var ans = 0 + + for (i in 0 until 26) { + if (total[i] == 0) continue + val ch = 'a' + i + var left = 0 + var count = 0 + + for (right in 0 until n) { + if (text[right] == ch) { + count++ + } + + while ((right - left + 1) - count > 1) { + if (text[left] == ch) { + count-- + } + left++ + } + + ans = maxOf(ans, minOf(right - left + 1, total[i])) + } + } + + return ans + } +} diff --git a/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.py b/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.py new file mode 100644 index 00000000..3260b204 --- /dev/null +++ b/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.py @@ -0,0 +1,25 @@ +from collections import Counter + + +class Solution: + def maxRepOpt1(self, text: str) -> int: + total = Counter(text) + n = len(text) + ans = 0 + + for ch in total: + left = 0 + count = 0 + + for right in range(n): + if text[right] == ch: + count += 1 + + while (right - left + 1) - count > 1: + if text[left] == ch: + count -= 1 + left += 1 + + ans = max(ans, min(right - left + 1, total[ch])) + + return ans diff --git a/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.py2 b/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.py2 new file mode 100644 index 00000000..f188206b --- /dev/null +++ b/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.py2 @@ -0,0 +1,27 @@ +class Solution(object): + def maxRepOpt1(self, text): + """ + :type text: str + :rtype: int + """ + from collections import Counter + total = Counter(text) + n = len(text) + ans = 0 + + for ch in total: + left = 0 + count = 0 + + for right in range(n): + if text[right] == ch: + count += 1 + + while (right - left + 1) - count > 1: + if text[left] == ch: + count -= 1 + left += 1 + + ans = max(ans, min(right - left + 1, total[ch])) + + return ans diff --git a/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.rb b/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.rb new file mode 100644 index 00000000..c168dd93 --- /dev/null +++ b/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.rb @@ -0,0 +1,30 @@ +# @param {String} text +# @return {Integer} +def max_rep_opt1(text) + total = Hash.new(0) + text.each_char { |c| total[c] += 1 } + n = text.length + ans = 0 + + total.keys.each do |ch| + left = 0 + count = 0 + + (0...n).each do |right| + if text[right] == ch + count += 1 + end + + while (right - left + 1) - count > 1 + if text[left] == ch + count -= 1 + end + left += 1 + end + + ans = [ans, [right - left + 1, total[ch]].min].max + end + end + + ans +end diff --git a/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.rs b/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.rs new file mode 100644 index 00000000..423f799c --- /dev/null +++ b/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.rs @@ -0,0 +1,35 @@ +impl Solution { + pub fn max_rep_opt1(text: String) -> i32 { + use std::collections::HashMap; + let mut total = HashMap::new(); + for c in text.chars() { + *total.entry(c).or_insert(0) += 1; + } + let n = text.len(); + let mut ans = 0; + let chars: Vec = text.chars().collect(); + + for (&ch, &ch_total) in &total { + let mut left = 0; + let mut count = 0; + + for right in 0..n { + if chars[right] == ch { + count += 1; + } + + while (right - left + 1) - count > 1 { + if chars[left] == ch { + count -= 1; + } + left += 1; + } + + let window_len = (right - left + 1) as i32; + ans = ans.max(window_len.min(ch_total)); + } + } + + ans + } +} diff --git a/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.swift b/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.swift new file mode 100644 index 00000000..c5d1c6b9 --- /dev/null +++ b/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.swift @@ -0,0 +1,33 @@ +class Solution { + func maxRepOpt1(_ text: String) -> Int { + var total = [Character: Int]() + for c in text { + total[c, default: 0] += 1 + } + let n = text.count + var ans = 0 + let chars = Array(text) + + for (ch, chTotal) in total { + var left = 0 + var count = 0 + + for right in 0.. 1 { + if chars[left] == ch { + count -= 1 + } + left += 1 + } + + ans = max(ans, min(right - left + 1, chTotal)) + } + } + + return ans + } +} diff --git a/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.ts b/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.ts new file mode 100644 index 00000000..5a6c67c9 --- /dev/null +++ b/tests/1001-1500/1156. swap-for-longest-repeated-character-substring/sol.ts @@ -0,0 +1,30 @@ +function maxRepOpt1(text: string): number { + const total: Map = new Map(); + for (const c of text) { + total.set(c, (total.get(c) || 0) + 1); + } + const n = text.length; + let ans = 0; + + for (const [ch, chTotal] of total) { + let left = 0; + let count = 0; + + for (let right = 0; right < n; right++) { + if (text[right] === ch) { + count++; + } + + while (right - left + 1 - count > 1) { + if (text[left] === ch) { + count--; + } + left++; + } + + ans = Math.max(ans, Math.min(right - left + 1, chTotal)); + } + } + + return ans; +} diff --git a/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/manifest.yaml b/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/manifest.yaml new file mode 100644 index 00000000..8af7b28e --- /dev/null +++ b/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/manifest.yaml @@ -0,0 +1,320 @@ +entry: + id: 1160 + title: "find-words-that-can-be-formed-by-characters" + params: + words: + type: array + items: + type: string + chars: + type: string + call: + cpp: "Solution().countCharacters({words}, {chars})" + rust: "Solution::count_characters({words}, {chars})" + python3: "Solution().countCharacters({words}, {chars})" + python2: "Solution().countCharacters({words}, {chars})" + ruby: "count_characters({words}, {chars})" + java: "new Solution().countCharacters({words}, {chars})" + csharp: "new Solution().CountCharacters({words}, {chars})" + kotlin: "Solution().countCharacters({words}, {chars})" + go: "countCharacters({words}, {chars})" + dart: "Solution().countCharacters({words}, {chars})" + swift: "Solution().countCharacters({words}, {chars})" + typescript: "countCharacters({words}, {chars})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().countCharacters(words, chars, {result})" + checker: | + class Checker: + def countCharacters(self, words, chars, result): + available = {} + for c in chars: + available[c] = available.get(c, 0) + 1 + expected = 0 + for word in words: + needed = {} + for c in word: + needed[c] = needed.get(c, 0) + 1 + if all(needed[c] <= available.get(c, 0) for c in needed): + expected += len(word) + return result == expected + +seed: 1160 + +tests: + - name: "example-one" + in: + words: + - cat + - bt + - hat + - tree + chars: "atach" + out: 6 + - name: "example-two" + in: + words: ["hello", "world", "leetcode"] + chars: "welldonehoneyr" + out: 10 + - name: "one-letter-match" + in: + words: ["a"] + chars: "a" + out: 1 + - name: "one-letter-miss" + in: + words: ["z"] + chars: "a" + out: 0 + - name: "all-letters-available" + in: + words: ["abc", "cab", "bca"] + chars: "abc" + out: 9 + - name: "repeated-letter-exact" + in: + words: ["aaa", "aa", "aaaa"] + chars: "aaa" + out: 5 + - name: "repeated-letter-shortage" + in: + words: ["aaa", "aaaa", "a"] + chars: "aa" + out: 1 + - name: "duplicates-independent" + in: + words: ["ab", "ab", "ab", "ba"] + chars: "ab" + out: 8 + - name: "no-word-possible" + in: + words: ["x", "yy", "zzz"] + chars: "abcdefghijklmnopqrstuvw" + out: 0 + - name: "every-word-impossible" + in: + words: ["dog", "cat", "bird"] + chars: "eeeeeeee" + out: 0 + - name: "mixed-single-letters" + in: + words: ["a", "b", "c", "d", "e"] + chars: "ace" + out: 3 + - name: "case-sensitive-lowercase" + in: + words: ["hello", "he", "ll", "o"] + chars: "hello" + out: 10 + - name: "exact-long-word" + in: + words: ["abcdefghijklmnopqrst"] + chars: "abcdefghijklmnopqrst" + out: 20 + - name: "long-word-one-short" + in: + words: ["abcdefghijklmnopqrst"] + chars: "abcdefghijklmnopqrsx" + out: 0 + - name: "many-vowels" + in: + words: ["book", "cook", "look", "bookkeeper"] + chars: "ookbcl" + out: 12 + - name: "interleaved-repeats" + in: + words: ["aabb", "abab", "baba", "aaab"] + chars: "aabb" + out: 12 + - name: "word-order-irrelevant" + in: + words: ["zoo", "no", "one", "zero"] + chars: "zeroon" + out: 12 + - name: "single-char-budget" + in: + words: ["aaaaa", "b", "aa"] + chars: "aab" + out: 3 + - name: "alphabet-end" + in: + words: ["xyz", "zyx", "xxy"] + chars: "xyz" + out: 6 + - name: "all-alphabet" + in: + words: ["abcdefghijklmnopqrstuvwxyz", "abc", "zzz"] + chars: "abcdefghijklmnopqrstuvwxyz" + out: 29 + - name: "partial-alphabet" + in: + words: ["abc", "def", "gh", "ijkl"] + chars: "abcdefghi" + out: 8 + - name: "overlapping-needs" + in: + words: ["apple", "pear", "grape", "papaya"] + chars: "applegr" + out: 14 + - name: "long-repeated-a" + in: + words: ["aaaaaaaaaa", "aaaaaaaaa", "aaaaaaaaaaa"] + chars: "aaaaaaaaaa" + out: 19 + - name: "mixed-lengths" + in: + words: ["a", "ab", "abc", "abcd", "abcde", "abcdef"] + chars: "abcde" + out: 15 + - name: "palindromes" + in: + words: ["aba", "abba", "abcba", "aaaa"] + chars: "aabbaa" + out: 11 + - name: "disjoint-words" + in: + words: ["abc", "def", "ghi", "jkl"] + chars: "abcdefghijkl" + out: 12 + - name: "one-missing-repeat" + in: + words: ["letter", "tree", "tee", "rel"] + chars: "letter" + out: 16 + - name: "large-character-budget" + in: + words: ["abcdefghij", "jihgfedcba", "aaaaabbbbb", "ccccccccccc"] + chars: "aabbccddeeffgghhiijj" + out: 20 + - name: "many-identical-words" + in: + words: ["code", "code", "code", "code", "codec"] + chars: "code" + out: 16 + - name: "rare-letter-failures" + in: + words: ["quick", "brown", "fox", "jumps", "lazy", "dog"] + chars: "thequickbrownfox" + out: 13 + - name: "maximum-single-word-exact" + in: + words: + [ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + ] + chars: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + out: 100 + - name: "maximum-single-word-one-missing" + in: + words: + [ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", + ] + chars: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + out: 0 + - name: "character-budget-boundaries" + in: + words: + [ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + ] + chars: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + out: 200 + - name: "independent-long-word-reuse" + in: + words: + [ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + ] + chars: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + out: 1000 + - name: "per-letter-frequency-boundaries" + in: + words: ["aabbbc", "aabbc", "abbbc", "aabb", "cc"] + chars: "aabbbc" + out: 20 + - name: "generated-single" + in: + words: + gen: "array" + len: 1000 + of: + gen: "str" + len: 100 + alphabet: "a" + chars: + gen: "str" + len: 100 + alphabet: "a" + - name: "generated-two-letter-maximum" + in: + words: + gen: "array" + len: 1000 + of: + gen: "str" + len: 100 + alphabet: "ab" + chars: + gen: "str" + len: 100 + alphabet: "ab" + - name: "generated-four-letter-near-maximum" + in: + words: + gen: "array" + len: 950 + of: + gen: "str" + len: 99 + alphabet: "abcd" + chars: + gen: "str" + len: 100 + alphabet: "abcd" + - name: "generated-full-alphabet-maximum" + in: + words: + gen: "array" + len: 1000 + of: + gen: "str" + len: 100 + alphabet: "abcdefghijklmnopqrstuvwxyz" + chars: + gen: "str" + len: 100 + alphabet: "abcdefghijklmnopqrstuvwxyz" + - name: "generated-five-letter-maximum" + in: + words: + gen: "array" + len: 1000 + of: + gen: "str" + len: 100 + alphabet: "vwxyz" + chars: + gen: "str" + len: 100 + alphabet: "vwxyz" diff --git a/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.cpp b/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.cpp new file mode 100644 index 00000000..4e38de4f --- /dev/null +++ b/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int countCharacters(vector& words, string chars) { + unordered_map ch; + for (char c : chars) { + ch[c]++; + } + + int res = 0; + for (const string& word : words) { + unordered_map copy = ch; + bool good = true; + for (char c : word) { + if (copy.find(c) != copy.end() && copy[c] > 0) { + copy[c]--; + } else { + res -= word.length(); + good = false; + break; + } + } + res += word.length(); + } + return res; + } +}; diff --git a/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.cs b/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.cs new file mode 100644 index 00000000..4bdaae64 --- /dev/null +++ b/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.cs @@ -0,0 +1,29 @@ +public class Solution { + public int CountCharacters(string[] words, string chars) { + Dictionary ch = new Dictionary(); + foreach (char c in chars) { + if (ch.ContainsKey(c)) { + ch[c]++; + } else { + ch[c] = 1; + } + } + + int res = 0; + foreach (string word in words) { + Dictionary copy = new Dictionary(ch); + bool good = true; + foreach (char c in word) { + if (copy.ContainsKey(c) && copy[c] > 0) { + copy[c]--; + } else { + res -= word.Length; + good = false; + break; + } + } + res += word.Length; + } + return res; + } +} diff --git a/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.dart b/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.dart new file mode 100644 index 00000000..3ed7f27c --- /dev/null +++ b/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.dart @@ -0,0 +1,25 @@ +class Solution { + int countCharacters(List words, String chars) { + Map ch = {}; + for (var c in chars.split('')) { + ch[c] = (ch[c] ?? 0) + 1; + } + + int res = 0; + for (var word in words) { + Map copy = Map.from(ch); + bool good = true; + for (var c in word.split('')) { + if (copy.containsKey(c) && copy[c]! > 0) { + copy[c] = copy[c]! - 1; + } else { + res -= word.length; + good = false; + break; + } + } + res += word.length; + } + return res; + } +} diff --git a/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.go b/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.go new file mode 100644 index 00000000..bd62a045 --- /dev/null +++ b/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.go @@ -0,0 +1,31 @@ +func countCharacters(words []string, chars string) int { + ch := make(map[rune]int) + for _, c := range chars { + ch[c] = ch[c] + 1 + } + + res := 0 + for _, word := range words { + copy := make(map[rune]int) + for k, v := range ch { + copy[k] = v + } + good := true + for _, c := range word { + if val, ok := copy[c]; ok && val > 0 { + copy[c]-- + } else { + res -= len(word) + good = false + break + } + } + if good { + res += len(word) + } else { + res += len(word) + } + _ = good + } + return res +} diff --git a/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.java b/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.java new file mode 100644 index 00000000..e3078a80 --- /dev/null +++ b/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.java @@ -0,0 +1,25 @@ +class Solution { + public int countCharacters(String[] words, String chars) { + int[] ch = new int[26]; + for (char c : chars.toCharArray()) { + ch[c - 'a']++; + } + + int res = 0; + for (String word : words) { + int[] copy = ch.clone(); + boolean good = true; + for (char c : word.toCharArray()) { + if (copy[c - 'a'] > 0) { + copy[c - 'a']--; + } else { + res -= word.length(); + good = false; + break; + } + } + res += word.length(); + } + return res; + } +} diff --git a/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.kt b/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.kt new file mode 100644 index 00000000..da22d853 --- /dev/null +++ b/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.kt @@ -0,0 +1,25 @@ +class Solution { + fun countCharacters(words: Array, chars: String): Int { + val ch = IntArray(26) + for (c in chars) { + ch[c - 'a']++ + } + + var res = 0 + for (word in words) { + val copy = ch.clone() + var good = true + for (c in word) { + if (copy[c - 'a'] > 0) { + copy[c - 'a']-- + } else { + res -= word.length + good = false + break + } + } + res += word.length + } + return res + } +} diff --git a/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.py b/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.py new file mode 100644 index 00000000..9ec6ceb9 --- /dev/null +++ b/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.py @@ -0,0 +1,21 @@ +class Solution: + def countCharacters(self, words: List[str], chars: str) -> int: + ch = {} + + for c in chars: + ch[c] = 1 + ch.get(c, 0) + + res = 0 + for word in words: + copy = ch.copy() + + for c in word: + if c in copy and copy[c] != 0: + copy[c] -= 1 + else: + res -= len(word) + break + + res += len(word) + + return res diff --git a/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.py2 b/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.py2 new file mode 100644 index 00000000..5bd66f92 --- /dev/null +++ b/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.py2 @@ -0,0 +1,22 @@ +class Solution(object): + def countCharacters(self, words, chars): + """ + :type words: List[str] + :type chars: str + :rtype: int + """ + ch = {} + for c in chars: + ch[c] = 1 + ch.get(c, 0) + + res = 0 + for word in words: + copy = ch.copy() + for c in word: + if c in copy and copy[c] != 0: + copy[c] -= 1 + else: + res -= len(word) + break + res += len(word) + return res diff --git a/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.rb b/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.rb new file mode 100644 index 00000000..0606b3cf --- /dev/null +++ b/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.rb @@ -0,0 +1,26 @@ +# @param {String[]} words +# @param {String} chars +# @return {Integer} +def count_characters(words, chars) + ch = {} + chars.each_char do |c| + ch[c] = (ch[c] || 0) + 1 + end + + res = 0 + words.each do |word| + copy = ch.dup + good = true + word.each_char do |c| + if copy.key?(c) && copy[c] != 0 + copy[c] -= 1 + else + res -= word.length + good = false + break + end + end + res += word.length + end + res +end diff --git a/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.rs b/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.rs new file mode 100644 index 00000000..1f8b32d8 --- /dev/null +++ b/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.rs @@ -0,0 +1,33 @@ +impl Solution { + pub fn count_characters(words: Vec, chars: String) -> i32 { + use std::collections::HashMap; + + let mut ch: HashMap = HashMap::new(); + for c in chars.chars() { + *ch.entry(c).or_insert(0) += 1; + } + + let mut res = 0; + for word in words { + let mut copy = ch.clone(); + let mut good = true; + for c in word.chars() { + if let Some(count) = copy.get_mut(&c) { + if *count > 0 { + *count -= 1; + } else { + res -= word.len() as i32; + good = false; + break; + } + } else { + res -= word.len() as i32; + good = false; + break; + } + } + res += word.len() as i32; + } + res + } +} diff --git a/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.swift b/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.swift new file mode 100644 index 00000000..b0ff2c60 --- /dev/null +++ b/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.swift @@ -0,0 +1,25 @@ +class Solution { + func countCharacters(_ words: [String], _ chars: String) -> Int { + var ch = [Character: Int]() + for c in chars { + ch[c, default: 0] += 1 + } + + var res = 0 + for word in words { + var copy = ch + var good = true + for c in word { + if let count = copy[c], count > 0 { + copy[c] = count - 1 + } else { + res -= word.count + good = false + break + } + } + res += word.count + } + return res + } +} diff --git a/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.ts b/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.ts new file mode 100644 index 00000000..3c2bc5fb --- /dev/null +++ b/tests/1001-1500/1160. find-words-that-can-be-formed-by-characters/sol.ts @@ -0,0 +1,23 @@ +function countCharacters(words: string[], chars: string): number { + const ch: { [key: string]: number } = {}; + for (const c of chars) { + ch[c] = (ch[c] || 0) + 1; + } + + let res = 0; + for (const word of words) { + const copy = { ...ch }; + let good = true; + for (const c of word) { + if (copy[c] !== undefined && copy[c] > 0) { + copy[c]--; + } else { + res -= word.length; + good = false; + break; + } + } + res += word.length; + } + return res; +} diff --git a/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/manifest.yaml b/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/manifest.yaml new file mode 100644 index 00000000..b687a280 --- /dev/null +++ b/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/manifest.yaml @@ -0,0 +1,322 @@ +entry: + id: 1161 + title: maximum-level-sum-of-a-binary-tree + params: + root: + type: tree_node + call: + cpp: "Solution().maxLevelSum({root})" + rust: "Solution::max_level_sum({root})" + python3: "Solution().maxLevelSum({root})" + python2: "Solution().maxLevelSum({root})" + ruby: "max_level_sum({root})" + java: "new Solution().maxLevelSum({root})" + csharp: "new Solution().MaxLevelSum({root})" + kotlin: "Solution().maxLevelSum({root})" + go: "maxLevelSum({root})" + dart: "Solution().maxLevelSum({root})" + swift: "Solution().maxLevelSum({root})" + typescript: "maxLevelSum({root})" +judge: + type: exact +limits: + time_ms: 1000 + memory_mb: 256 +oracle: + python3: + call: "Checker().maxLevelSum(root, {result})" + checker: | + class Checker: + def maxLevelSum(self, root, result): + if isinstance(result, bool) or not isinstance(result, int): + return False + if not isinstance(root, list) or not root or root[0] is None: + return False + if any(isinstance(value, bool) or not isinstance(value, int) + for value in root if value is not None): + return False + current = [root[0]] + position = 1 + best_level = 1 + best_sum = root[0] + level = 1 + while current: + level_sum = sum(current) + if level_sum > best_sum: + best_sum = level_sum + best_level = level + next_level = [] + for _ in current: + for _ in range(2): + if position < len(root) and root[position] is not None: + next_level.append(root[position]) + position += 1 + current = next_level + level += 1 + return result == best_level +seed: 1161 +tests: + - name: single_positive + in: + root: [1] + out: 1 + - name: single_negative + in: + root: [-100000] + out: 1 + - name: example_one + in: + root: [1, 7, 0, 7, -8] + out: 2 + - name: example_two + in: + root: [989, null, 10250, 98693, -89388, null, null, null, -32127] + out: 2 + - name: root_beats_children + in: + root: [10, 1, 2] + out: 1 + - name: children_beat_root + in: + root: [1, 5, 6] + out: 2 + - name: deepest_level_wins + in: + root: [-10, -5, -5, 1, 1, 1, 1] + out: 3 + - name: all_negative_complete + in: + root: [-1, -2, -3, -4, -5, -6, -7] + out: 1 + - name: earliest_tie_at_root + in: + root: [5, 2, 3] + out: 1 + - name: earliest_tie_below_root + in: + root: [1, 4, 4, 2, 2, 2, 2] + out: 2 + - name: left_chain + in: + root: [1, 2, null, 3, null, 4, null, 5] + out: 5 + - name: right_chain + in: + root: [1, null, 2, null, 3, null, 4, null, 5] + out: 5 + - name: alternating_chain + in: + root: [1, 2, null, null, 3, 4, null] + out: 4 + - name: sparse_left_subtree + in: + root: [4, 9, null, 3, -2, null, null, 10] + out: 4 + - name: sparse_right_subtree + in: + root: [-4, null, 9, null, 3, -2, 10] + out: 2 + - name: wide_positive_last_level + in: + root: [-100, -100, -100, 50, 50, 50, 50] + out: 3 + - name: wide_negative_last_level + in: + root: [100000, -100000, -100000, -100000, -100000, -100000, -100000] + out: 1 + - name: mixed_complete_four_levels + in: + root: [8, -3, 4, -2, 7, -5, 6, 1, 1, 1, 1, 1, 1, 1, 1] + out: 1 + - name: full_five_levels_uniform + in: + root: + [ + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 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: recovery_after_negative_level + in: + root: [100, -50, -50, -50, -50, 100, 100, 100, 100] + out: 4 + - name: maximum_values_at_level_two + in: + root: [-100000, 100000, 100000, -100000, -100000, -100000, -100000] + out: 2 + - name: minimum_values_at_level_two + in: + root: [100000, -100000, -100000, 100000, 100000, 100000, 100000] + out: 3 + - name: zero_levels_tie + in: + root: [0, 0, 0, 0, 0, 0, 0] + out: 1 + - name: asymmetric_three_levels + in: + root: [3, -10, 8, 20, null, -4, 7] + out: 3 + - name: one_child_per_parent + in: + root: [-8, 4, null, -6, null, 20, null, -30, null, 40] + out: 6 + - name: compressed_bfs_gap + in: + root: [2, null, 3, 4, null, null, 5] + out: 4 + - name: level_two_negative_level_three_positive + in: + root: [1, -3, -2, 4, 4, 4, 4] + out: 3 + - name: level_one_and_three_tie + in: + root: [10, -8, -7, 5, 5, 0, 0] + out: 1 + - name: level_two_and_four_tie + in: + root: [-20, 6, 6, -5, -5, -5, -5, 3, 3, 3, 3] + out: 2 + - name: incomplete_last_level_wins + in: + root: [-5, -4, -3, -2, -1, 20] + out: 3 + - name: incomplete_last_level_loses + in: + root: [50, 20, 20, -100, -100, -100] + out: 1 + - name: large_sum_without_overflow + in: + root: + [ + -100000, + 100000, + 100000, + 100000, + 100000, + 100000, + 100000, + 100000, + 100000, + 100000, + 100000, + 100000, + 100000, + 100000, + 100000, + ] + out: 4 + - name: negative_root_positive_grandchildren + in: + root: [-99, -50, -50, 100, 100, 100, 100] + out: 3 + - name: uneven_depth_with_tie + in: + root: [7, 2, 5, 1, 1, null, 3, 2, null] + out: 1 + - name: stress_random_full_tree_one + seed: 116101 + in: + root: + gen: array + len: 10000 + distinct: false + sorted: false + elemType: int + of: + gen: int + min: -100000 + max: 100000 + - name: stress_random_full_tree_two + seed: 116102 + in: + root: + gen: array + len: 9999 + distinct: false + sorted: false + elemType: int + of: + gen: int + min: -100000 + max: 100000 + - name: stress_random_full_tree_three + seed: 116103 + in: + root: + gen: array + len: 9998 + distinct: false + sorted: false + elemType: int + of: + gen: int + min: -100000 + max: 100000 + - name: stress_random_full_tree_four + seed: 116104 + in: + root: + gen: array + len: 9997 + distinct: false + sorted: false + elemType: int + of: + gen: int + min: -100000 + max: 100000 + - name: stress_random_full_tree_five + seed: 116105 + in: + root: + gen: array + len: 9996 + distinct: false + sorted: false + elemType: int + of: + gen: int + min: -100000 + max: 100000 + - name: stress_random_full_tree_six + seed: 116106 + in: + root: + gen: array + len: 9995 + distinct: false + sorted: false + elemType: int + of: + gen: int + min: -100000 + max: 100000 diff --git a/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.cpp b/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.cpp new file mode 100644 index 00000000..0c2bd545 --- /dev/null +++ b/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.cpp @@ -0,0 +1,38 @@ +/** + * 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: + int maxLevelSum(TreeNode* root) { + int idx = 0; + int maxSum = INT_MIN; + queue q; + q.push(root); + int level = 1; + while (!q.empty()) { + int qz = q.size(); + int curSum = 0; + for (int i = 0; i < qz; i++) { + TreeNode* node = q.front(); + q.pop(); + curSum += node->val; + if (node->left) q.push(node->left); + if (node->right) q.push(node->right); + } + if (curSum > maxSum) { + idx = level; + maxSum = curSum; + } + level++; + } + return idx; + } +}; diff --git a/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.cs b/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.cs new file mode 100644 index 00000000..56e55cc4 --- /dev/null +++ b/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.cs @@ -0,0 +1,38 @@ +/** + * 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 MaxLevelSum(TreeNode root) { + int idx = 0; + int maxSum = int.MinValue; + var q = new Queue(); + q.Enqueue(root); + int level = 1; + while (q.Count > 0) { + int qz = q.Count; + int curSum = 0; + for (int i = 0; i < qz; i++) { + TreeNode node = q.Dequeue(); + curSum += node.val; + if (node.left != null) q.Enqueue(node.left); + if (node.right != null) q.Enqueue(node.right); + } + if (curSum > maxSum) { + idx = level; + maxSum = curSum; + } + level++; + } + return idx; + } +} diff --git a/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.dart b/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.dart new file mode 100644 index 00000000..17cc51b6 --- /dev/null +++ b/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.dart @@ -0,0 +1,33 @@ +/** + * 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 maxLevelSum(TreeNode? root) { + int idx = 0; + int maxSum = -1 << 63; + var q = [root!]; + int level = 1; + while (q.isNotEmpty) { + int qz = q.length; + int curSum = 0; + for (int i = 0; i < qz; i++) { + var node = q.removeAt(0); + curSum += node.val; + if (node.left != null) q.add(node.left!); + if (node.right != null) q.add(node.right!); + } + if (curSum > maxSum) { + idx = level; + maxSum = curSum; + } + level++; + } + return idx; + } +} diff --git a/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.go b/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.go new file mode 100644 index 00000000..7f3faf52 --- /dev/null +++ b/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.go @@ -0,0 +1,35 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func maxLevelSum(root *TreeNode) int { + idx := 0 + maxSum := -1 << 31 + q := []*TreeNode{root} + level := 1 + for len(q) > 0 { + qz := len(q) + curSum := 0 + for i := 0; i < qz; i++ { + node := q[0] + q = q[1:] + curSum += node.Val + if node.Left != nil { + q = append(q, node.Left) + } + if node.Right != nil { + q = append(q, node.Right) + } + } + if curSum > maxSum { + idx = level + maxSum = curSum + } + level++ + } + return idx +} diff --git a/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.java b/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.java new file mode 100644 index 00000000..5d25478a --- /dev/null +++ b/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.java @@ -0,0 +1,40 @@ +/** + * 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 maxLevelSum(TreeNode root) { + int idx = 0; + int maxSum = Integer.MIN_VALUE; + java.util.Queue q = new java.util.LinkedList<>(); + q.offer(root); + int level = 1; + while (!q.isEmpty()) { + int qz = q.size(); + int curSum = 0; + for (int i = 0; i < qz; i++) { + TreeNode node = q.poll(); + curSum += node.val; + if (node.left != null) q.offer(node.left); + if (node.right != null) q.offer(node.right); + } + if (curSum > maxSum) { + idx = level; + maxSum = curSum; + } + level++; + } + return idx; + } +} diff --git a/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.kt b/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.kt new file mode 100644 index 00000000..a3ee5491 --- /dev/null +++ b/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.kt @@ -0,0 +1,35 @@ +/** + * 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 maxLevelSum(root: TreeNode?): Int { + var idx = 0 + var maxSum = Int.MIN_VALUE + val q: java.util.Queue = java.util.LinkedList() + q.offer(root) + var level = 1 + while (q.isNotEmpty()) { + val qz = q.size + var curSum = 0 + repeat(qz) { + val node = q.poll() + curSum += node.`val` + node.left?.let { q.offer(it) } + node.right?.let { q.offer(it) } + } + if (curSum > maxSum) { + idx = level + maxSum = curSum + } + level++ + } + return idx + } +} diff --git a/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.py b/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.py new file mode 100644 index 00000000..3389ced7 --- /dev/null +++ b/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.py @@ -0,0 +1,30 @@ +from collections import deque +from math import inf + + +# 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 maxLevelSum(self, root: Optional[TreeNode]) -> int: + idx, Sum = 0, -inf + q = deque() + q.append(root) + level = 1 + while q: + qz = len(q) + curSum = 0 + for i in range(qz): + Node = q.popleft() + curSum += Node.val + if Node.left: + q.append(Node.left) + if Node.right: + q.append(Node.right) + if curSum > Sum: + idx, Sum = level, curSum + level += 1 + return idx diff --git a/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.py2 b/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.py2 new file mode 100644 index 00000000..68ff84e1 --- /dev/null +++ b/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.py2 @@ -0,0 +1,30 @@ +# 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 maxLevelSum(self, root): + """ + :type root: Optional[TreeNode] + :rtype: int + """ + from collections import deque + idx, max_sum = 0, float('-inf') + q = deque([root]) + level = 1 + while q: + qz = len(q) + cur_sum = 0 + for _ in range(qz): + node = q.popleft() + cur_sum += node.val + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) + if cur_sum > max_sum: + idx, max_sum = level, cur_sum + level += 1 + return idx diff --git a/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.rb b/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.rb new file mode 100644 index 00000000..b4b46a64 --- /dev/null +++ b/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.rb @@ -0,0 +1,33 @@ +# 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 {Integer} +def max_level_sum(root) + idx = 0 + max_sum = -Float::INFINITY + q = [root] + level = 1 + while !q.empty? + qz = q.size + cur_sum = 0 + qz.times do + node = q.shift + cur_sum += node.val + q << node.left if node.left + q << node.right if node.right + end + if cur_sum > max_sum + idx = level + max_sum = cur_sum + end + level += 1 + end + idx +end diff --git a/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.rs b/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.rs new file mode 100644 index 00000000..38eaa1c0 --- /dev/null +++ b/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.rs @@ -0,0 +1,48 @@ +// 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 max_level_sum(root: Option>>) -> i32 { + let mut idx = 0; + let mut max_sum = i32::MIN; + let mut q = std::collections::VecDeque::new(); + q.push_back(root.unwrap()); + let mut level = 1; + while !q.is_empty() { + let qz = q.len(); + let mut cur_sum = 0; + for _ in 0..qz { + let node = q.pop_front().unwrap(); + let node = node.borrow(); + cur_sum += node.val; + if let Some(left) = &node.left { + q.push_back(left.clone()); + } + if let Some(right) = &node.right { + q.push_back(right.clone()); + } + } + if cur_sum > max_sum { + idx = level; + max_sum = cur_sum; + } + level += 1; + } + idx + } +} diff --git a/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.swift b/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.swift new file mode 100644 index 00000000..eac0a69f --- /dev/null +++ b/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.swift @@ -0,0 +1,39 @@ +/** + * 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 maxLevelSum(_ root: TreeNode?) -> Int { + var idx = 0 + var maxSum = Int.min + var q = [root!] + var level = 1 + while !q.isEmpty { + let qz = q.count + var curSum = 0 + for _ in 0.. maxSum { + idx = level + maxSum = curSum + } + level += 1 + } + return idx + } +} diff --git a/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.ts b/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.ts new file mode 100644 index 00000000..c9e31feb --- /dev/null +++ b/tests/1001-1500/1161. maximum-level-sum-of-a-binary-tree/sol.ts @@ -0,0 +1,36 @@ +/** + * 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 maxLevelSum(root: TreeNode | null): number { + let idx = 0; + let maxSum = -Infinity; + const q: TreeNode[] = [root!]; + let level = 1; + while (q.length > 0) { + const qz = q.length; + let curSum = 0; + for (let i = 0; i < qz; i++) { + const node = q.shift()!; + curSum += node.val; + if (node.left) q.push(node.left); + if (node.right) q.push(node.right); + } + if (curSum > maxSum) { + idx = level; + maxSum = curSum; + } + level++; + } + return idx; +} diff --git a/tests/1001-1500/1162. as-far-from-land-as-possible/manifest.yaml b/tests/1001-1500/1162. as-far-from-land-as-possible/manifest.yaml new file mode 100644 index 00000000..83b88eeb --- /dev/null +++ b/tests/1001-1500/1162. as-far-from-land-as-possible/manifest.yaml @@ -0,0 +1,505 @@ +entry: + id: 1162 + title: as-far-from-land-as-possible + params: + grid: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().maxDistance({grid})" + rust: "Solution::max_distance({grid})" + python3: "Solution().maxDistance({grid})" + python2: "Solution().maxDistance({grid})" + ruby: "max_distance({grid})" + java: "new Solution().maxDistance({grid})" + csharp: "new Solution().MaxDistance({grid})" + kotlin: "Solution().maxDistance({grid})" + go: "maxDistance({grid})" + dart: "Solution().maxDistance({grid})" + swift: "Solution().maxDistance({grid})" + typescript: "maxDistance({grid})" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().maxDistance(grid, {result})" + checker: | + class Checker: + def maxDistance(self, grid, result): + if type(result) is not int or not isinstance(grid, list): + return False + n = len(grid) + if n < 1 or any(not isinstance(row, list) or len(row) != n for row in grid): + return False + if any(cell not in (0, 1) for row in grid for cell in row): + return False + land_count = sum(cell for row in grid for cell in row) + if land_count == 0 or land_count == n * n: + return result == -1 + inf = 2 * n + dist = [[0 if grid[r][c] else inf for c in range(n)] for r in range(n)] + for r in range(n): + for c in range(n): + if r: + dist[r][c] = min(dist[r][c], dist[r - 1][c] + 1) + if c: + dist[r][c] = min(dist[r][c], dist[r][c - 1] + 1) + for r in range(n - 1, -1, -1): + for c in range(n - 1, -1, -1): + if r + 1 < n: + dist[r][c] = min(dist[r][c], dist[r + 1][c] + 1) + if c + 1 < n: + dist[r][c] = min(dist[r][c], dist[r][c + 1] + 1) + return result == max(dist[r][c] for r in range(n) for c in range(n) if grid[r][c] == 0) +seed: 1162 +tests: + - name: example-corners + in: + grid: + elemType: int + value: + - [1, 0, 1] + - [0, 0, 0] + - [1, 0, 1] + out: 2 + - name: example-single-corner + in: + grid: + elemType: int + value: + - [1, 0, 0] + - [0, 0, 0] + - [0, 0, 0] + out: 4 + - name: one-cell-land + in: + grid: + elemType: int + value: + - [1] + out: -1 + - name: one-cell-water + in: + grid: + elemType: int + value: + - [0] + out: -1 + - name: all-land-two + in: + grid: + elemType: int + value: + - [1, 1] + - [1, 1] + out: -1 + - name: all-water-two + in: + grid: + elemType: int + value: + - [0, 0] + - [0, 0] + out: -1 + - name: opposite-corners-three + in: + grid: + elemType: int + value: + - [1, 0, 0] + - [0, 0, 0] + - [0, 0, 1] + out: 2 + - name: center-land-three + in: + grid: + elemType: int + value: + - [0, 0, 0] + - [0, 1, 0] + - [0, 0, 0] + out: 2 + - name: center-water-three + in: + grid: + elemType: int + value: + - [1, 1, 1] + - [1, 0, 1] + - [1, 1, 1] + out: 1 + - name: top-row-land-four + in: + grid: + elemType: int + value: + - [1, 1, 1, 1] + - [0, 0, 0, 0] + - [0, 0, 0, 0] + - [0, 0, 0, 0] + out: 3 + - name: diagonal-land-four + in: + grid: + elemType: int + value: + - [1, 0, 0, 0] + - [0, 1, 0, 0] + - [0, 0, 1, 0] + - [0, 0, 0, 1] + out: 3 + - name: border-land-five + in: + grid: + elemType: int + value: + - [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] + out: 2 + - name: checkerboard-three + in: + grid: + elemType: int + value: + - [1, 0, 1] + - [0, 1, 0] + - [1, 0, 1] + out: 1 + - name: left-column-four + in: + grid: + elemType: int + value: + - [1, 0, 0, 0] + - [1, 0, 0, 0] + - [1, 0, 0, 0] + - [1, 0, 0, 0] + out: 3 + - name: isolated-center-and-corners + in: + grid: + elemType: int + value: + - [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] + out: 2 + - name: water-diamond-pocket + in: + grid: + elemType: int + value: + - [1, 1, 1, 1, 1] + - [1, 1, 0, 1, 1] + - [1, 0, 0, 0, 1] + - [1, 1, 0, 1, 1] + - [1, 1, 1, 1, 1] + out: 2 + - name: diagonal-corners-five + in: + grid: + elemType: int + value: + - [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] + out: 4 + - name: four-corners-five + in: + grid: + elemType: int + value: + - [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: 4 + - name: central-block-six + in: + grid: + elemType: int + value: + - [0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0] + - [0, 0, 1, 1, 0, 0] + - [0, 0, 1, 1, 0, 0] + - [0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0] + out: 4 + - name: one-corner-six + in: + grid: + elemType: int + value: + - [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] + out: 10 + - name: opposite-corners-six + in: + grid: + elemType: int + value: + - [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, 1] + out: 5 + - name: horizontal-band-six + in: + grid: + elemType: int + value: + - [0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0] + - [1, 1, 1, 1, 1, 1] + - [0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0] + out: 3 + - name: vertical-band-six + in: + grid: + elemType: int + value: + - [0, 0, 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, 0, 0, 0] + - [0, 0, 1, 0, 0, 0] + out: 3 + - name: cross-six + in: + grid: + elemType: int + value: + - [0, 0, 1, 0, 0, 0] + - [0, 0, 1, 0, 0, 0] + - [1, 1, 1, 1, 1, 1] + - [0, 0, 1, 0, 0, 0] + - [0, 0, 1, 0, 0, 0] + - [0, 0, 1, 0, 0, 0] + out: 3 + - name: four-corners-six + in: + grid: + elemType: int + value: + - [1, 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] + - [1, 0, 0, 0, 0, 1] + out: 4 + - name: dense-triangular-pocket + in: + grid: + elemType: int + value: + - [1, 1, 1, 1, 1] + - [1, 1, 1, 0, 1] + - [1, 1, 0, 0, 1] + - [1, 0, 0, 0, 1] + - [1, 1, 1, 1, 1] + out: 1 + - name: checkerboard-five + in: + grid: + elemType: int + value: + - [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: 1 + - name: ring-seven + in: + grid: + elemType: int + value: + - [1, 1, 1, 1, 1, 1, 1] + - [1, 0, 0, 0, 0, 0, 1] + - [1, 0, 0, 0, 0, 0, 1] + - [1, 0, 0, 0, 0, 0, 1] + - [1, 0, 0, 0, 0, 0, 1] + - [1, 0, 0, 0, 0, 0, 1] + - [1, 1, 1, 1, 1, 1, 1] + out: 3 + - name: one-corner-seven + in: + grid: + elemType: int + value: + - [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] + out: 12 + - name: off-center-cluster-seven + in: + grid: + elemType: int + value: + - [0, 0, 0, 0, 0, 0, 0] + - [0, 1, 1, 0, 0, 0, 0] + - [0, 1, 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] + out: 8 + - name: alternating-rows-seven + in: + grid: + elemType: int + value: + - [1, 1, 1, 1, 1, 1, 1] + - [0, 0, 0, 0, 0, 0, 0] + - [1, 1, 1, 1, 1, 1, 1] + - [0, 0, 0, 0, 0, 0, 0] + - [1, 1, 1, 1, 1, 1, 1] + - [0, 0, 0, 0, 0, 0, 0] + - [1, 1, 1, 1, 1, 1, 0] + out: 1 + - name: offset-single-land-five + in: + grid: + elemType: int + value: + - [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] + out: 6 + - name: four-corners-eight + in: + grid: + elemType: int + value: + - [1, 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] + - [1, 0, 0, 0, 0, 0, 0, 1] + out: 6 + - name: checkerboard-eight + in: + grid: + elemType: int + value: + - [1, 0, 1, 0, 1, 0, 1, 0] + - [0, 1, 0, 1, 0, 1, 0, 1] + - [1, 0, 1, 0, 1, 0, 1, 0] + - [0, 1, 0, 1, 0, 1, 0, 1] + - [1, 0, 1, 0, 1, 0, 1, 0] + - [0, 1, 0, 1, 0, 1, 0, 1] + - [1, 0, 1, 0, 1, 0, 1, 0] + - [0, 1, 0, 1, 0, 1, 0, 1] + out: 1 + - name: generated-100-seed-17 + seed: 17 + in: + grid: + gen: array + len: 100 + of: + gen: array + len: 100 + of: + gen: int + min: 0 + max: 1 + - name: generated-100-seed-29 + seed: 29 + in: + grid: + gen: array + len: 100 + of: + gen: array + len: 100 + of: + gen: int + min: 0 + max: 1 + - name: generated-100-seed-43 + seed: 43 + in: + grid: + gen: array + len: 100 + of: + gen: array + len: 100 + of: + gen: int + min: 0 + max: 1 + - name: generated-100-seed-61 + seed: 61 + in: + grid: + gen: array + len: 100 + of: + gen: array + len: 100 + of: + gen: int + min: 0 + max: 1 + - name: generated-100-seed-79 + seed: 79 + in: + grid: + gen: array + len: 100 + of: + gen: array + len: 100 + of: + gen: int + min: 0 + max: 1 + - name: generated-100-seed-97 + seed: 97 + in: + grid: + gen: array + len: 100 + of: + gen: array + len: 100 + of: + gen: int + min: 0 + max: 1 diff --git a/tests/1001-1500/1162. as-far-from-land-as-possible/sol.cpp b/tests/1001-1500/1162. as-far-from-land-as-possible/sol.cpp new file mode 100644 index 00000000..d392348d --- /dev/null +++ b/tests/1001-1500/1162. as-far-from-land-as-possible/sol.cpp @@ -0,0 +1,48 @@ +class Solution { +public: + int maxDistance(vector>& grid) { + if (grid.empty() || grid[0].empty()) { + return -1; + } + + int n = grid.size(); + queue> frontier; + + for (int r = 0; r < n; r++) { + for (int c = 0; c < n; c++) { + if (grid[r][c] == 1) { + frontier.push({r, c}); + } + } + } + + if (frontier.empty() || frontier.size() == n * n) { + return -1; + } + + vector> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; + int distance = -1; + + while (!frontier.empty()) { + int size = frontier.size(); + distance++; + + for (int i = 0; i < size; i++) { + auto [r, c] = frontier.front(); + frontier.pop(); + + for (auto [dr, dc] : directions) { + int nr = r + dr; + int nc = c + dc; + + if (nr >= 0 && nr < n && nc >= 0 && nc < n && grid[nr][nc] == 0) { + grid[nr][nc] = 1; + frontier.push({nr, nc}); + } + } + } + } + + return distance; + } +}; diff --git a/tests/1001-1500/1162. as-far-from-land-as-possible/sol.cs b/tests/1001-1500/1162. as-far-from-land-as-possible/sol.cs new file mode 100644 index 00000000..429fb97b --- /dev/null +++ b/tests/1001-1500/1162. as-far-from-land-as-possible/sol.cs @@ -0,0 +1,46 @@ +public class Solution { + public int MaxDistance(int[][] grid) { + if (grid == null || grid.Length == 0 || grid[0].Length == 0) { + return -1; + } + + int n = grid.Length; + var frontier = new Queue<(int, int)>(); + + for (int r = 0; r < n; r++) { + for (int c = 0; c < n; c++) { + if (grid[r][c] == 1) { + frontier.Enqueue((r, c)); + } + } + } + + if (frontier.Count == 0 || frontier.Count == n * n) { + return -1; + } + + (int, int)[] directions = { (-1, 0), (1, 0), (0, -1), (0, 1) }; + int distance = -1; + + while (frontier.Count > 0) { + int size = frontier.Count; + distance++; + + for (int i = 0; i < size; i++) { + var (r, c) = frontier.Dequeue(); + + foreach (var (dr, dc) in directions) { + int nr = r + dr; + int nc = c + dc; + + if (nr >= 0 && nr < n && nc >= 0 && nc < n && grid[nr][nc] == 0) { + grid[nr][nc] = 1; + frontier.Enqueue((nr, nc)); + } + } + } + } + + return distance; + } +} diff --git a/tests/1001-1500/1162. as-far-from-land-as-possible/sol.dart b/tests/1001-1500/1162. as-far-from-land-as-possible/sol.dart new file mode 100644 index 00000000..5f0d47b5 --- /dev/null +++ b/tests/1001-1500/1162. as-far-from-land-as-possible/sol.dart @@ -0,0 +1,48 @@ +class Solution { + int maxDistance(List> grid) { + if (grid.isEmpty || grid[0].isEmpty) { + return -1; + } + + int n = grid.length; + List> frontier = []; + + for (int r = 0; r < n; r++) { + for (int c = 0; c < n; c++) { + if (grid[r][c] == 1) { + frontier.add([r, c]); + } + } + } + + if (frontier.isEmpty || frontier.length == n * n) { + return -1; + } + + List> directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]; + int distance = -1; + + while (frontier.isNotEmpty) { + List> nextFrontier = []; + distance++; + + for (var cell in frontier) { + int r = cell[0], c = cell[1]; + + for (var dir in directions) { + int nr = r + dir[0]; + int nc = c + dir[1]; + + if (nr >= 0 && nr < n && nc >= 0 && nc < n && grid[nr][nc] == 0) { + grid[nr][nc] = 1; + nextFrontier.add([nr, nc]); + } + } + } + + frontier = nextFrontier; + } + + return distance; + } +} diff --git a/tests/1001-1500/1162. as-far-from-land-as-possible/sol.go b/tests/1001-1500/1162. as-far-from-land-as-possible/sol.go new file mode 100644 index 00000000..a16199fc --- /dev/null +++ b/tests/1001-1500/1162. as-far-from-land-as-possible/sol.go @@ -0,0 +1,44 @@ +func maxDistance(grid [][]int) int { + if len(grid) == 0 || len(grid[0]) == 0 { + return -1 + } + + n := len(grid) + type point struct{ r, c int } + frontier := make([]point, 0) + + for r := 0; r < n; r++ { + for c := 0; c < n; c++ { + if grid[r][c] == 1 { + frontier = append(frontier, point{r, c}) + } + } + } + + if len(frontier) == 0 || len(frontier) == n*n { + return -1 + } + + directions := [][2]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}} + distance := -1 + + for len(frontier) > 0 { + nextFrontier := make([]point, 0) + distance++ + + for _, p := range frontier { + for _, dir := range directions { + nr, nc := p.r+dir[0], p.c+dir[1] + + if nr >= 0 && nr < n && nc >= 0 && nc < n && grid[nr][nc] == 0 { + grid[nr][nc] = 1 + nextFrontier = append(nextFrontier, point{nr, nc}) + } + } + } + + frontier = nextFrontier + } + + return distance +} diff --git a/tests/1001-1500/1162. as-far-from-land-as-possible/sol.java b/tests/1001-1500/1162. as-far-from-land-as-possible/sol.java new file mode 100644 index 00000000..51f9dffd --- /dev/null +++ b/tests/1001-1500/1162. as-far-from-land-as-possible/sol.java @@ -0,0 +1,47 @@ +class Solution { + public int maxDistance(int[][] grid) { + if (grid == null || grid.length == 0 || grid[0].length == 0) { + return -1; + } + + int n = grid.length; + java.util.Queue frontier = new java.util.LinkedList<>(); + + for (int r = 0; r < n; r++) { + for (int c = 0; c < n; c++) { + if (grid[r][c] == 1) { + frontier.offer(new int[]{r, c}); + } + } + } + + if (frontier.isEmpty() || frontier.size() == n * n) { + return -1; + } + + int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; + int distance = -1; + + while (!frontier.isEmpty()) { + int size = frontier.size(); + distance++; + + for (int i = 0; i < size; i++) { + int[] cell = frontier.poll(); + int r = cell[0], c = cell[1]; + + for (int[] dir : directions) { + int nr = r + dir[0]; + int nc = c + dir[1]; + + if (nr >= 0 && nr < n && nc >= 0 && nc < n && grid[nr][nc] == 0) { + grid[nr][nc] = 1; + frontier.offer(new int[]{nr, nc}); + } + } + } + } + + return distance; + } +} diff --git a/tests/1001-1500/1162. as-far-from-land-as-possible/sol.kt b/tests/1001-1500/1162. as-far-from-land-as-possible/sol.kt new file mode 100644 index 00000000..7a974f21 --- /dev/null +++ b/tests/1001-1500/1162. as-far-from-land-as-possible/sol.kt @@ -0,0 +1,46 @@ +class Solution { + fun maxDistance(grid: Array): Int { + if (grid.isEmpty() || grid[0].isEmpty()) { + return -1 + } + + val n = grid.size + val frontier = ArrayDeque>() + + for (r in 0 until n) { + for (c in 0 until n) { + if (grid[r][c] == 1) { + frontier.add(Pair(r, c)) + } + } + } + + if (frontier.isEmpty() || frontier.size == n * n) { + return -1 + } + + val directions = listOf(-1 to 0, 1 to 0, 0 to -1, 0 to 1) + var distance = -1 + + while (frontier.isNotEmpty()) { + val size = frontier.size + distance++ + + repeat(size) { + val (r, c) = frontier.removeFirst() + + for ((dr, dc) in directions) { + val nr = r + dr + val nc = c + dc + + if (nr in 0 until n && nc in 0 until n && grid[nr][nc] == 0) { + grid[nr][nc] = 1 + frontier.add(Pair(nr, nc)) + } + } + } + } + + return distance + } +} diff --git a/tests/1001-1500/1162. as-far-from-land-as-possible/sol.py b/tests/1001-1500/1162. as-far-from-land-as-possible/sol.py new file mode 100644 index 00000000..11c1be50 --- /dev/null +++ b/tests/1001-1500/1162. as-far-from-land-as-possible/sol.py @@ -0,0 +1,39 @@ +class Solution: + def maxDistance(self, grid: List[List[int]]) -> int: + if not grid or not grid[0]: + return -1 + + n = len(grid) + frontier = [] + + # 1. Initial State Formulation (Identify the source components) + for r in range(n): + for c in range(n): + if grid[r][c] == 1: + frontier.append((r, c)) + + # Edge Cases: If the grid is completely land or completely water, dilation cannot occur + if len(frontier) == 0 or len(frontier) == n * n: + return -1 + + # 2. Successive Dilation Phase (Fixed-Point Propagation) + directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] + distance = -1 + + while frontier: + next_frontier = [] + # Increment distance with each progressive expansion wave + distance += 1 + + for r, c in frontier: + for dr, dc in directions: + nr, nc = r + dr, c + dc + + # If the structuring element hits water, the land component expands + if 0 <= nr < n and 0 <= nc < n and grid[nr][nc] == 0: + grid[nr][nc] = 1 # Water cell transitions to land + next_frontier.append((nr, nc)) + + frontier = next_frontier + + return distance diff --git a/tests/1001-1500/1162. as-far-from-land-as-possible/sol.py2 b/tests/1001-1500/1162. as-far-from-land-as-possible/sol.py2 new file mode 100644 index 00000000..976853bd --- /dev/null +++ b/tests/1001-1500/1162. as-far-from-land-as-possible/sol.py2 @@ -0,0 +1,38 @@ +class Solution(object): + def maxDistance(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + if not grid or not grid[0]: + return -1 + + n = len(grid) + frontier = [] + + for r in range(n): + for c in range(n): + if grid[r][c] == 1: + frontier.append((r, c)) + + if len(frontier) == 0 or len(frontier) == n * n: + return -1 + + directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] + distance = -1 + + while frontier: + next_frontier = [] + distance += 1 + + for r, c in frontier: + for dr, dc in directions: + nr, nc = r + dr, c + dc + + if 0 <= nr < n and 0 <= nc < n and grid[nr][nc] == 0: + grid[nr][nc] = 1 + next_frontier.append((nr, nc)) + + frontier = next_frontier + + return distance diff --git a/tests/1001-1500/1162. as-far-from-land-as-possible/sol.rb b/tests/1001-1500/1162. as-far-from-land-as-possible/sol.rb new file mode 100644 index 00000000..0e233258 --- /dev/null +++ b/tests/1001-1500/1162. as-far-from-land-as-possible/sol.rb @@ -0,0 +1,39 @@ +# @param {Integer[][]} grid +# @return {Integer} +def max_distance(grid) + return -1 if grid.nil? || grid.empty? || grid[0].nil? || grid[0].empty? + + n = grid.length + frontier = [] + + (0...n).each do |r| + (0...n).each do |c| + frontier << [r, c] if grid[r][c] == 1 + end + end + + return -1 if frontier.empty? || frontier.length == n * n + + directions = [[-1, 0], [1, 0], [0, -1], [0, 1]] + distance = -1 + + until frontier.empty? + next_frontier = [] + distance += 1 + + frontier.each do |r, c| + directions.each do |dr, dc| + nr, nc = r + dr, c + dc + + if nr >= 0 && nr < n && nc >= 0 && nc < n && grid[nr][nc] == 0 + grid[nr][nc] = 1 + next_frontier << [nr, nc] + end + end + end + + frontier = next_frontier + end + + distance +end diff --git a/tests/1001-1500/1162. as-far-from-land-as-possible/sol.rs b/tests/1001-1500/1162. as-far-from-land-as-possible/sol.rs new file mode 100644 index 00000000..1d32ac74 --- /dev/null +++ b/tests/1001-1500/1162. as-far-from-land-as-possible/sol.rs @@ -0,0 +1,52 @@ +impl Solution { + pub fn max_distance(grid: Vec>) -> i32 { + if grid.is_empty() || grid[0].is_empty() { + return -1; + } + + let n = grid.len(); + let mut grid = grid; + let mut frontier: Vec<(usize, usize)> = Vec::new(); + + for r in 0..n { + for c in 0..n { + if grid[r][c] == 1 { + frontier.push((r, c)); + } + } + } + + if frontier.is_empty() || frontier.len() == n * n { + return -1; + } + + let directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]; + let mut distance = -1; + + while !frontier.is_empty() { + let mut next_frontier: Vec<(usize, usize)> = Vec::new(); + distance += 1; + + for (r, c) in &frontier { + for (dr, dc) in &directions { + let nr = *r as i32 + dr; + let nc = *c as i32 + dc; + + if nr >= 0 && nr < n as i32 && nc >= 0 && nc < n as i32 { + let nr = nr as usize; + let nc = nc as usize; + + if grid[nr][nc] == 0 { + grid[nr][nc] = 1; + next_frontier.push((nr, nc)); + } + } + } + } + + frontier = next_frontier; + } + + distance + } +} diff --git a/tests/1001-1500/1162. as-far-from-land-as-possible/sol.swift b/tests/1001-1500/1162. as-far-from-land-as-possible/sol.swift new file mode 100644 index 00000000..7b7fb830 --- /dev/null +++ b/tests/1001-1500/1162. as-far-from-land-as-possible/sol.swift @@ -0,0 +1,47 @@ +class Solution { + func maxDistance(_ grid: [[Int]]) -> Int { + if grid.isEmpty || grid[0].isEmpty { + return -1 + } + + let n = grid.count + var grid = grid + var frontier: [(Int, Int)] = [] + + for r in 0..= 0 && nr < n && nc >= 0 && nc < n && grid[nr][nc] == 0 { + grid[nr][nc] = 1 + nextFrontier.append((nr, nc)) + } + } + } + + frontier = nextFrontier + } + + return distance + } +} diff --git a/tests/1001-1500/1162. as-far-from-land-as-possible/sol.ts b/tests/1001-1500/1162. as-far-from-land-as-possible/sol.ts new file mode 100644 index 00000000..044b51fa --- /dev/null +++ b/tests/1001-1500/1162. as-far-from-land-as-possible/sol.ts @@ -0,0 +1,49 @@ +function maxDistance(grid: number[][]): number { + if (!grid || grid.length === 0 || grid[0].length === 0) { + return -1; + } + + const n = grid.length; + let frontier: [number, number][] = []; + + for (let r = 0; r < n; r++) { + for (let c = 0; c < n; c++) { + if (grid[r][c] === 1) { + frontier.push([r, c]); + } + } + } + + if (frontier.length === 0 || frontier.length === n * n) { + return -1; + } + + const directions: [number, number][] = [ + [-1, 0], + [1, 0], + [0, -1], + [0, 1], + ]; + let distance = -1; + + while (frontier.length > 0) { + const nextFrontier: [number, number][] = []; + distance++; + + for (const [r, c] of frontier) { + for (const [dr, dc] of directions) { + const nr = r + dr; + const nc = c + dc; + + if (nr >= 0 && nr < n && nc >= 0 && nc < n && grid[nr][nc] === 0) { + grid[nr][nc] = 1; + nextFrontier.push([nr, nc]); + } + } + } + + frontier = nextFrontier; + } + + return distance; +} diff --git a/tests/1001-1500/1163. last-substring-in-lexicographical-order/manifest.yaml b/tests/1001-1500/1163. last-substring-in-lexicographical-order/manifest.yaml new file mode 100644 index 00000000..bbf2a2cb --- /dev/null +++ b/tests/1001-1500/1163. last-substring-in-lexicographical-order/manifest.yaml @@ -0,0 +1,232 @@ +entry: + id: 1163 + title: last-substring-in-lexicographical-order + params: + s: + type: string + call: + cpp: "Solution().lastSubstring({s})" + rust: "Solution::last_substring({s})" + python3: "Solution().lastSubstring({s})" + python2: "Solution().lastSubstring({s})" + ruby: "last_substring({s})" + java: "new Solution().lastSubstring({s})" + csharp: "new Solution().LastSubstring({s})" + kotlin: "Solution().lastSubstring({s})" + go: "lastSubstring({s})" + dart: "Solution().lastSubstring({s})" + swift: "Solution().lastSubstring({s})" + typescript: "lastSubstring({s})" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().lastSubstring(s, {result})" + checker: | + class Checker: + def lastSubstring(self, s, result): + if type(s) is not str or type(result) is not str: + return False + n = len(s) + m = len(result) + if m == 0 or m > n or s[n - m:] != result: + return False + + # Z-values compare the proposed suffix to every suffix of s. + combined = result + "#" + s + z = [0] * len(combined) + left = right = 0 + for i in range(1, len(combined)): + if i <= right: + z[i] = min(right - i + 1, z[i - left]) + while i + z[i] < len(combined) and combined[z[i]] == combined[i + z[i]]: + z[i] += 1 + if i + z[i] - 1 > right: + left, right = i, i + z[i] - 1 + + for start in range(n): + common = z[m + 1 + start] + suffix_len = n - start + if common == m: + if suffix_len > m: + return False + elif common < suffix_len and result[common] < s[start + common]: + return False + return True +seed: 1163 +tests: + - name: example-abab + in: + s: abab + out: bab + - name: example-leetcode + in: + s: leetcode + out: tcode + - name: single-a + in: + s: a + out: a + - name: single-z + in: + s: z + out: z + - name: ascending + in: + s: abcdef + out: f + - name: descending + in: + s: fedcba + out: fedcba + - name: all-a + in: + s: aaaaaaaa + out: aaaaaaaa + - name: all-z + in: + s: zzzzzzzz + out: zzzzzzzz + - name: largest-at-start + in: + s: zabcdef + out: zabcdef + - name: largest-at-end + in: + s: abcdefz + out: z + - name: repeated-ab + in: + s: abababab + out: bababab + - name: repeated-ba + in: + s: babababa + out: babababa + - name: ties-long-prefix + in: + s: aazaaaz + out: zaaaz + - name: z-prefix-tie + in: + s: zzzazzzb + out: zzzb + - name: two-maxima + in: + s: azaz + out: zaz + - name: max-before-lower + in: + s: bzba + out: zba + - name: max-suffix-choice + in: + s: cabcabc + out: cabcabc + - name: alternating-three + in: + s: acacacb + out: cb + - name: near-equal-suffixes + in: + s: aaaaaabaaaaaac + out: c + - name: late-z + in: + s: bbbbbbbbbzbbbb + out: zbbbb + - name: mixed-alphabet + in: + s: qwertyuiopasdfghjklzxcvbnm + out: zxcvbnm + - name: z-and-y + in: + s: yzyzyzzzy + out: zzzy + - name: max-char-runs + in: + s: aaazaaazaaaz + out: zaaazaaaz + - name: suffix-contained + in: + s: abcabdabce + out: e + - name: many-candidates + in: + s: xaxxbxxcxxdxx + out: xxdxx + - name: palindrome + in: + s: abccbaabccba + out: ccbaabccba + - name: middle-maximum + in: + s: mnopzmnop + out: zmnop + - name: long-equal-blocks + in: + s: zzzzyzzzzxzzzz + out: zzzzyzzzzxzzzz + - name: final-maximal-run + in: + s: abcxyzxyz + out: zxyz + - name: late-maximum + in: + s: helloworldzhello + out: zhello + - name: b-after-long-a-prefix + in: + s: aaaaabaaaaa + out: baaaaa + - name: repeated-z-with-late-tiebreak + in: + s: azzzazzzb + out: zzzb + - name: dominant-run-before-smaller-run + in: + s: zazzzazzy + out: zzzazzy + - name: repeated-nonmaximum-pattern + in: + s: banana + out: nana + - name: generated-binary-50k + in: + s: + gen: str + len: 50000 + alphabet: ab + - name: generated-small-alphabet-75k + in: + s: + gen: str + len: 75000 + alphabet: abc + - name: generated-four-symbol-100k + in: + s: + gen: str + len: 100000 + alphabet: admz + - name: generated-broad-alphabet-200k + in: + s: + gen: str + len: 200000 + alphabet: abcxyz + - name: generated-near-maximum-399999 + in: + s: + gen: str + len: 399999 + alphabet: abcz + - name: generated-maximum-400k + in: + s: + gen: str + len: 400000 + alphabet: amyz diff --git a/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.cpp b/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.cpp new file mode 100644 index 00000000..e7b84890 --- /dev/null +++ b/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + string lastSubstring(string s) { + int i = 0, j = 1, k = 0; + int n = s.size(); + while (j + k < n) { + if (s[i + k] == s[j + k]) { + k++; + continue; + } else if (s[i + k] > s[j + k]) { + j = j + k + 1; + } else { + i = max(i + k + 1, j); + j = i + 1; + } + k = 0; + } + return s.substr(i); + } +}; diff --git a/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.cs b/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.cs new file mode 100644 index 00000000..3e791219 --- /dev/null +++ b/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.cs @@ -0,0 +1,19 @@ +public class Solution { + public string LastSubstring(string s) { + int i = 0, j = 1, k = 0; + int n = s.Length; + while (j + k < n) { + if (s[i + k] == s[j + k]) { + k++; + continue; + } else if (s[i + k] > s[j + k]) { + j = j + k + 1; + } else { + i = Math.Max(i + k + 1, j); + j = i + 1; + } + k = 0; + } + return s.Substring(i); + } +} diff --git a/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.dart b/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.dart new file mode 100644 index 00000000..72593f89 --- /dev/null +++ b/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.dart @@ -0,0 +1,19 @@ +class Solution { + String lastSubstring(String s) { + int i = 0, j = 1, k = 0; + int n = s.length; + while (j + k < n) { + if (s[i + k] == s[j + k]) { + k++; + continue; + } else if (s[i + k].codeUnitAt(0) > s[j + k].codeUnitAt(0)) { + j = j + k + 1; + } else { + i = (i + k + 1 > j ? i + k + 1 : j); + j = i + 1; + } + k = 0; + } + return s.substring(i); + } +} diff --git a/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.go b/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.go new file mode 100644 index 00000000..fdf44b47 --- /dev/null +++ b/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.go @@ -0,0 +1,17 @@ +func lastSubstring(s string) string { + i, j, k := 0, 1, 0 + n := len(s) + for j+k < n { + if s[i+k] == s[j+k] { + k++ + continue + } else if s[i+k] > s[j+k] { + j = j + k + 1 + } else { + i = max(i+k+1, j) + j = i + 1 + } + k = 0 + } + return s[i:] +} diff --git a/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.java b/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.java new file mode 100644 index 00000000..6be34f5b --- /dev/null +++ b/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.java @@ -0,0 +1,19 @@ +class Solution { + public String lastSubstring(String s) { + int i = 0, j = 1, k = 0; + int n = s.length(); + while (j + k < n) { + if (s.charAt(i + k) == s.charAt(j + k)) { + k++; + continue; + } else if (s.charAt(i + k) > s.charAt(j + k)) { + j = j + k + 1; + } else { + i = Math.max(i + k + 1, j); + j = i + 1; + } + k = 0; + } + return s.substring(i); + } +} diff --git a/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.kt b/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.kt new file mode 100644 index 00000000..43fa0ab9 --- /dev/null +++ b/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.kt @@ -0,0 +1,25 @@ +class Solution { + fun lastSubstring(s: String): String { + var i = 0 + var j = 1 + var k = 0 + val n = s.length + while (j + k < n) { + when { + s[i + k] == s[j + k] -> { + k++ + continue + } + s[i + k] > s[j + k] -> { + j = j + k + 1 + } + else -> { + i = maxOf(i + k + 1, j) + j = i + 1 + } + } + k = 0 + } + return s.substring(i) + } +} diff --git a/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.py b/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.py new file mode 100644 index 00000000..f090120d --- /dev/null +++ b/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.py @@ -0,0 +1,15 @@ +class Solution: + def lastSubstring(self, s: str) -> str: + i, j, k = 0, 1, 0 + + while j + k < len(s): + if s[i + k] == s[j + k]: + k += 1 + continue + elif s[i + k] > s[j + k]: + j = j + k + 1 + else: + i = max(i + k + 1, j) + j = i + 1 + k = 0 + return s[i:] diff --git a/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.py2 b/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.py2 new file mode 100644 index 00000000..41079c00 --- /dev/null +++ b/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.py2 @@ -0,0 +1,18 @@ +class Solution(object): + def lastSubstring(self, s): + """ + :type s: str + :rtype: str + """ + i, j, k = 0, 1, 0 + while j + k < len(s): + if s[i+k] == s[j+k]: + k += 1 + continue + elif s[i+k] > s[j+k]: + j = j + k + 1 + else: + i = max(i + k + 1, j) + j = i + 1 + k = 0 + return s[i:] diff --git a/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.rb b/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.rb new file mode 100644 index 00000000..34d87b58 --- /dev/null +++ b/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.rb @@ -0,0 +1,18 @@ +# @param {String} s +# @return {String} +def last_substring(s) + i, j, k = 0, 1, 0 + while j + k < s.length + if s[i+k] == s[j+k] + k += 1 + next + elsif s[i+k] > s[j+k] + j = j + k + 1 + else + i = [i + k + 1, j].max + j = i + 1 + end + k = 0 + end + s[i..-1] +end diff --git a/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.rs b/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.rs new file mode 100644 index 00000000..c88a76c5 --- /dev/null +++ b/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.rs @@ -0,0 +1,20 @@ +impl Solution { + pub fn last_substring(s: String) -> String { + let bytes = s.as_bytes(); + let n = bytes.len(); + let (mut i, mut j, mut k) = (0, 1, 0); + while j + k < n { + if bytes[i + k] == bytes[j + k] { + k += 1; + continue; + } else if bytes[i + k] > bytes[j + k] { + j = j + k + 1; + } else { + i = std::cmp::max(i + k + 1, j); + j = i + 1; + } + k = 0; + } + s[i..].to_string() + } +} diff --git a/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.swift b/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.swift new file mode 100644 index 00000000..c69f3992 --- /dev/null +++ b/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func lastSubstring(_ s: String) -> String { + let chars = Array(s) + var i = 0, j = 1, k = 0 + let n = chars.count + while j + k < n { + if chars[i + k] == chars[j + k] { + k += 1 + continue + } else if chars[i + k] > chars[j + k] { + j = j + k + 1 + } else { + i = max(i + k + 1, j) + j = i + 1 + } + k = 0 + } + return String(chars[i...]) + } +} diff --git a/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.ts b/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.ts new file mode 100644 index 00000000..24af6a63 --- /dev/null +++ b/tests/1001-1500/1163. last-substring-in-lexicographical-order/sol.ts @@ -0,0 +1,19 @@ +function lastSubstring(s: string): string { + let i = 0, + j = 1, + k = 0; + const n = s.length; + while (j + k < n) { + if (s[i + k] === s[j + k]) { + k++; + continue; + } else if (s[i + k] > s[j + k]) { + j = j + k + 1; + } else { + i = Math.max(i + k + 1, j); + j = i + 1; + } + k = 0; + } + return s.substring(i); +} diff --git a/tests/1001-1500/1169. invalid-transactions/manifest.yaml b/tests/1001-1500/1169. invalid-transactions/manifest.yaml new file mode 100644 index 00000000..672f8275 --- /dev/null +++ b/tests/1001-1500/1169. invalid-transactions/manifest.yaml @@ -0,0 +1,185 @@ +entry: + id: 1169 + title: "invalid-transactions" + params: + transactions: + type: array + items: + type: string + call: + cpp: "Solution().invalidTransactions({transactions})" + rust: "Solution::invalid_transactions({transactions})" + python3: "Solution().invalidTransactions({transactions})" + python2: "Solution().invalidTransactions({transactions})" + ruby: "invalid_transactions({transactions})" + java: "new Solution().invalidTransactions({transactions})" + csharp: "new Solution().InvalidTransactions({transactions})" + kotlin: "Solution().invalidTransactions({transactions})" + go: "invalidTransactions({transactions})" + dart: "Solution().invalidTransactions({transactions})" + swift: "Solution().invalidTransactions({transactions})" + typescript: "invalidTransactions({transactions})" + +judge: + type: "ignore_order" + +limits: + time_ms: 700 + memory_mb: 300 + +oracle: + python3: + call: "Checker().invalidTransactions(transactions, {result})" + checker: | + from collections import Counter + + class Checker: + def invalidTransactions(self, transactions, result): + if not isinstance(result, list) or any(not isinstance(x, str) for x in result): + return False + parsed = [] + for raw in transactions: + parts = raw.split(',') + if len(parts) != 4: + return False + name, time, amount, city = parts + parsed.append((name, int(time), int(amount), city, raw)) + expected = [] + for i, (name, time, amount, city, raw) in enumerate(parsed): + bad = amount > 1000 + if not bad: + for j, (name2, time2, amount2, city2, raw2) in enumerate(parsed): + if i != j and name == name2 and city != city2 and abs(time - time2) <= 60: + bad = True + break + if bad: + expected.append(raw) + return Counter(result) == Counter(expected) + +seed: 116900 + +tests: + - name: "example_cross_city" + in: + transactions: ["alice,20,800,mtv", "alice,50,100,beijing"] + - name: "example_high_amount_same_city" + in: + transactions: ["alice,20,800,mtv", "alice,50,1200,mtv"] + - name: "example_different_names" + in: + transactions: ["alice,20,800,mtv", "bob,50,1200,mtv"] + - name: "single_valid" + in: + transactions: ["bob,0,1,x"] + - name: "single_over_limit" + in: + transactions: ["bob,0,1001,x"] + - name: "amount_boundary_valid" + in: + transactions: ["a,10,1000,one"] + - name: "amount_boundary_invalid" + in: + transactions: ["a,10,1001,one"] + - name: "same_city_window" + in: + transactions: ["a,10,900,x", "a,70,900,x"] + - name: "different_city_outside_window" + in: + transactions: ["a,10,900,x", "a,71,900,y"] + - name: "different_city_at_sixty" + in: + transactions: ["a,10,900,x", "a,70,900,y"] + - name: "different_city_sixty_one" + in: + transactions: ["a,10,900,x", "a,71,900,y"] + - name: "three_cities_chain" + in: + transactions: ["a,0,10,x", "a,30,20,y", "a,90,30,z"] + - name: "same_name_multiple_same_city" + in: + transactions: ["a,0,10,x", "a,20,20,x", "a,40,30,x"] + - name: "mixed_users" + in: + transactions: ["a,0,10,x", "b,0,2000,y", "a,10,20,y"] + - name: "high_amount_and_window" + in: + transactions: ["a,100,1500,x", "a,140,5,y"] + - name: "high_amount_old_transaction" + in: + transactions: ["a,0,1500,x", "a,61,5,y"] + - name: "duplicate_records" + in: + transactions: ["a,5,10,x", "a,5,10,x", "a,5,10,y"] + - name: "same_time_different_city" + in: + transactions: ["a,500,1,x", "a,500,2,y"] + - name: "zero_time_zero_amount" + in: + transactions: ["a,0,0,x", "a,0,0,y"] + - name: "maximum_time" + in: + transactions: ["a,1000,1000,x", "a,940,1000,y"] + - name: "maximum_time_outside" + in: + transactions: ["a,1000,1000,x", "a,939,1000,y"] + - name: "unsorted_input" + in: + transactions: ["a,100,1,y", "a,0,1,x", "a,50,1,z"] + - name: "only_one_side_high" + in: + transactions: ["a,0,1500,x", "a,100,1,y", "b,0,3,z"] + - name: "four_transactions_window" + in: + transactions: ["a,0,1,x", "a,10,1,y", "a,20,1,z", "a,80,1,x"] + - name: "window_expiry_keeps_later" + in: + transactions: ["a,0,1,x", "a,61,1,y", "a,121,1,x"] + - name: "different_names_same_city" + in: + transactions: ["a,10,1,x", "b,20,1,y", "c,30,1,z"] + - name: "many_high_amounts" + in: + transactions: ["a,1,1001,x", "b,2,2000,y", "c,3,1500,z"] + - name: "high_amount_duplicate_text" + in: + transactions: ["a,1,1200,x", "a,1,1200,x", "a,1,1200,y"] + - name: "cross_city_far_apart" + in: + transactions: ["a,100,500,x", "a,200,500,y", "a,300,500,z"] + - name: "two_pairs" + in: + transactions: ["a,10,10,x", "a,20,10,y", "b,10,10,x", "b,20,10,y"] + - name: "boundary_amount_cross_city" + in: + transactions: ["a,400,1000,x", "a,460,1000,y"] + - name: "near_boundary_amount_cross_city" + in: + transactions: ["a,400,1000,x", "a,461,1000,y"] + - name: "large_same_name_group" + in: + transactions: ["a,0,1,a", "a,15,1,b", "a,30,1,c", "a,45,1,d", "a,60,1,e"] + - name: "large_group_with_expensive" + in: + transactions: + ["a,0,1,a", "a,30,1001,b", "a,60,1,c", "a,90,1,a", "a,150,1,b"] + - name: "mixed_valid_invalid_group" + in: + transactions: + ["a,0,1,x", "a,61,1,y", "a,62,1002,z", "b,0,1,q", "b,61,1,q"] + - name: "all_same_city_high_times" + in: + transactions: ["a,0,1,x", "a,60,1,x", "a,120,1,x", "a,180,1001,x"] + - name: "repeated_cross_city_and_high" + in: + transactions: + ["a,10,1,x", "a,70,1,y", "a,130,1,x", "a,190,1001,y", "b,10,1,z"] + - name: "selective_invalidation_after_window_boundary" + in: + transactions: ["a,0,1,x", "a,60,1,y", "a,120,1,y"] + - name: "sparse_cross_city_pair_among_same_city_records" + in: + transactions: + ["a,0,1,x", "a,20,1,x", "a,40,1,y", "a,100,1,y", "a,160,1,y"] + - name: "duplicate_text_with_one_separate_valid_record" + in: + transactions: ["a,10,1001,x", "a,10,1001,x", "a,80,1,x", "b,20,1,y"] diff --git a/tests/1001-1500/1169. invalid-transactions/sol.cpp b/tests/1001-1500/1169. invalid-transactions/sol.cpp new file mode 100644 index 00000000..d5297712 --- /dev/null +++ b/tests/1001-1500/1169. invalid-transactions/sol.cpp @@ -0,0 +1,61 @@ +class Solution { +public: + vector invalidTransactions(vector& transactions) { + unordered_map>> userTxns; + vector invalids; + + for (string& txn : transactions) { + stringstream ss(txn); + string item; + vector vals; + while (getline(ss, item, ',')) { + vals.push_back(item); + } + userTxns[vals[0]].push_back(vals); + } + + for (auto& [user, txns] : userTxns) { + sort(txns.begin(), txns.end(), [](const vector& a, const vector& b) { + return stoi(a[1]) < stoi(b[1]); + }); + unordered_map cities; + int l = 0; + unordered_set invalidTxnWithinWindow; + + for (int r = 0; r < txns.size(); r++) { + cities[txns[r][3]]++; + while (l < r && stoi(txns[r][1]) - stoi(txns[l][1]) > 60) { + if (--cities[txns[l][3]] == 0) { + cities.erase(txns[l][3]); + } + invalidTxnWithinWindow.erase(l); + l++; + } + + if (stoi(txns[r][2]) > 1000) { + string joined; + for (int j = 0; j < txns[r].size(); j++) { + if (j > 0) joined += ","; + joined += txns[r][j]; + } + invalids.push_back(joined); + } + if (cities.size() > 1) { + for (int i = l; i <= r; i++) { + if (stoi(txns[i][2]) <= 1000 && invalidTxnWithinWindow.find(i) == invalidTxnWithinWindow.end()) { + string joined; + for (int j = 0; j < txns[i].size(); j++) { + if (j > 0) joined += ","; + joined += txns[i][j]; + } + invalids.push_back(joined); + invalidTxnWithinWindow.insert(i); + } + } + } + } + } + + return invalids; + } +}; diff --git a/tests/1001-1500/1169. invalid-transactions/sol.cs b/tests/1001-1500/1169. invalid-transactions/sol.cs new file mode 100644 index 00000000..ffcff00e --- /dev/null +++ b/tests/1001-1500/1169. invalid-transactions/sol.cs @@ -0,0 +1,51 @@ +public class Solution { + public IList InvalidTransactions(string[] transactions) { + var userTxns = new Dictionary>(); + var invalids = new List(); + + foreach (var txn in transactions) { + var vals = txn.Split(','); + if (!userTxns.ContainsKey(vals[0])) { + userTxns[vals[0]] = new List(); + } + userTxns[vals[0]].Add(vals); + } + + foreach (var kvp in userTxns) { + var txns = kvp.Value; + txns.Sort((a, b) => int.Parse(a[1]).CompareTo(int.Parse(b[1]))); + var cities = new Dictionary(); + int l = 0; + var invalidTxnWithinWindow = new HashSet(); + + for (int r = 0; r < txns.Count; r++) { + var txn = txns[r]; + if (!cities.ContainsKey(txn[3])) cities[txn[3]] = 0; + cities[txn[3]]++; + + while (l < r && int.Parse(txns[r][1]) - int.Parse(txns[l][1]) > 60) { + cities[txns[l][3]]--; + if (cities[txns[l][3]] == 0) { + cities.Remove(txns[l][3]); + } + invalidTxnWithinWindow.Remove(l); + l++; + } + + if (int.Parse(txn[2]) > 1000) { + invalids.Add(string.Join(",", txn)); + } + if (cities.Count > 1) { + for (int i = l; i <= r; i++) { + if (int.Parse(txns[i][2]) <= 1000 && !invalidTxnWithinWindow.Contains(i)) { + invalids.Add(string.Join(",", txns[i])); + invalidTxnWithinWindow.Add(i); + } + } + } + } + } + + return invalids; + } +} diff --git a/tests/1001-1500/1169. invalid-transactions/sol.dart b/tests/1001-1500/1169. invalid-transactions/sol.dart new file mode 100644 index 00000000..34622a86 --- /dev/null +++ b/tests/1001-1500/1169. invalid-transactions/sol.dart @@ -0,0 +1,45 @@ +class Solution { + List invalidTransactions(List transactions) { + Map>> userTxns = {}; + List invalids = []; + + for (var txn in transactions) { + var vals = txn.split(","); + userTxns.putIfAbsent(vals[0], () => []).add(vals); + } + + for (var entry in userTxns.entries) { + var txns = entry.value; + txns.sort((a, b) => int.parse(a[1]).compareTo(int.parse(b[1]))); + Map cities = {}; + int l = 0; + Set invalidTxnWithinWindow = {}; + + for (int r = 0; r < txns.length; r++) { + cities[txns[r][3]] = (cities[txns[r][3]] ?? 0) + 1; + while (l < r && int.parse(txns[r][1]) - int.parse(txns[l][1]) > 60) { + cities[txns[l][3]] = cities[txns[l][3]]! - 1; + if (cities[txns[l][3]] == 0) { + cities.remove(txns[l][3]); + } + invalidTxnWithinWindow.remove(l); + l++; + } + + if (int.parse(txns[r][2]) > 1000) { + invalids.add(txns[r].join(",")); + } + if (cities.length > 1) { + for (int i = l; i <= r; i++) { + if (int.parse(txns[i][2]) <= 1000 && !invalidTxnWithinWindow.contains(i)) { + invalids.add(txns[i].join(",")); + invalidTxnWithinWindow.add(i); + } + } + } + } + } + + return invalids; + } +} diff --git a/tests/1001-1500/1169. invalid-transactions/sol.go b/tests/1001-1500/1169. invalid-transactions/sol.go new file mode 100644 index 00000000..d129b33c --- /dev/null +++ b/tests/1001-1500/1169. invalid-transactions/sol.go @@ -0,0 +1,53 @@ +func invalidTransactions(transactions []string) []string { + userTxns := make(map[string][][]string) + invalids := []string{} + + for _, txn := range transactions { + vals := strings.Split(txn, ",") + userTxns[vals[0]] = append(userTxns[vals[0]], vals) + } + + for _, txns := range userTxns { + sort.Slice(txns, func(i, j int) bool { + a, _ := strconv.Atoi(txns[i][1]) + b, _ := strconv.Atoi(txns[j][1]) + return a < b + }) + cities := make(map[string]int) + l := 0 + invalidTxnWithinWindow := make(map[int]bool) + + for r := 0; r < len(txns); r++ { + cities[txns[r][3]]++ + for l < r { + timeR, _ := strconv.Atoi(txns[r][1]) + timeL, _ := strconv.Atoi(txns[l][1]) + if timeR-timeL <= 60 { + break + } + cities[txns[l][3]]-- + if cities[txns[l][3]] == 0 { + delete(cities, txns[l][3]) + } + delete(invalidTxnWithinWindow, l) + l++ + } + + amount, _ := strconv.Atoi(txns[r][2]) + if amount > 1000 { + invalids = append(invalids, strings.Join(txns[r], ",")) + } + if len(cities) > 1 { + for i := l; i <= r; i++ { + amt, _ := strconv.Atoi(txns[i][2]) + if amt <= 1000 && !invalidTxnWithinWindow[i] { + invalids = append(invalids, strings.Join(txns[i], ",")) + invalidTxnWithinWindow[i] = true + } + } + } + } + } + + return invalids +} diff --git a/tests/1001-1500/1169. invalid-transactions/sol.java b/tests/1001-1500/1169. invalid-transactions/sol.java new file mode 100644 index 00000000..63478158 --- /dev/null +++ b/tests/1001-1500/1169. invalid-transactions/sol.java @@ -0,0 +1,47 @@ +class Solution { + public List invalidTransactions(String[] transactions) { + Map> userTxns = new HashMap<>(); + List invalids = new ArrayList<>(); + + for (String txn : transactions) { + String[] vals = txn.split(","); + userTxns.computeIfAbsent(vals[0], k -> new ArrayList<>()).add(vals); + } + + for (String user : userTxns.keySet()) { + List txns = userTxns.get(user); + txns.sort((a, b) -> Integer.compare(Integer.parseInt(a[1]), Integer.parseInt(b[1]))); + Map cities = new HashMap<>(); + int l = 0; + Set invalidTxnWithinWindow = new HashSet<>(); + + for (int r = 0; r < txns.size(); r++) { + String[] txn = txns.get(r); + cities.put(txn[3], cities.getOrDefault(txn[3], 0) + 1); + while (l < r && Integer.parseInt(txns.get(r)[1]) - Integer.parseInt(txns.get(l)[1]) > 60) { + cities.put(txns.get(l)[3], cities.get(txns.get(l)[3]) - 1); + if (cities.get(txns.get(l)[3]) == 0) { + cities.remove(txns.get(l)[3]); + } + invalidTxnWithinWindow.remove(l); + l++; + } + + if (Integer.parseInt(txn[2]) > 1000) { + invalids.add(String.join(",", txn)); + } + if (cities.size() > 1) { + for (int i = l; i <= r; i++) { + String[] inner = txns.get(i); + if (Integer.parseInt(inner[2]) <= 1000 && !invalidTxnWithinWindow.contains(i)) { + invalids.add(String.join(",", inner)); + invalidTxnWithinWindow.add(i); + } + } + } + } + } + + return invalids; + } +} diff --git a/tests/1001-1500/1169. invalid-transactions/sol.kt b/tests/1001-1500/1169. invalid-transactions/sol.kt new file mode 100644 index 00000000..8d36ef45 --- /dev/null +++ b/tests/1001-1500/1169. invalid-transactions/sol.kt @@ -0,0 +1,46 @@ +class Solution { + fun invalidTransactions(transactions: Array): List { + val userTxns = mutableMapOf>>() + val invalids = mutableListOf() + + for (txn in transactions) { + val vals = txn.split(",") + userTxns.getOrPut(vals[0]) { mutableListOf() }.add(vals) + } + + for ((_, txns) in userTxns) { + txns.sortBy { it[1].toInt() } + val cities = mutableMapOf() + var l = 0 + val invalidTxnWithinWindow = mutableSetOf() + + for (r in txns.indices) { + val txn = txns[r] + cities[txn[3]] = cities.getOrDefault(txn[3], 0) + 1 + while (l < r && txns[r][1].toInt() - txns[l][1].toInt() > 60) { + cities[txns[l][3]] = cities[txns[l][3]]!! - 1 + if (cities[txns[l][3]] == 0) { + cities.remove(txns[l][3]) + } + invalidTxnWithinWindow.remove(l) + l++ + } + + if (txn[2].toInt() > 1000) { + invalids.add(txn.joinToString(",")) + } + if (cities.size > 1) { + for (i in l..r) { + val inner = txns[i] + if (inner[2].toInt() <= 1000 && i !in invalidTxnWithinWindow) { + invalids.add(inner.joinToString(",")) + invalidTxnWithinWindow.add(i) + } + } + } + } + } + + return invalids + } +} diff --git a/tests/1001-1500/1169. invalid-transactions/sol.py b/tests/1001-1500/1169. invalid-transactions/sol.py new file mode 100644 index 00000000..9c766111 --- /dev/null +++ b/tests/1001-1500/1169. invalid-transactions/sol.py @@ -0,0 +1,39 @@ +class Solution: + def invalidTransactions(self, transactions: List[str]) -> List[str]: + userTxns = {} + + invalids = [] + + for txn in transactions: + vals = txn.split(",") + if vals[0] not in userTxns: + userTxns[vals[0]] = [] + userTxns[vals[0]].append(vals) + + for user in userTxns: + txns = userTxns[user] + txns.sort(key=lambda x: int(x[1])) + cities = {} + l = 0 + invalidTxnWithinWindow = set() + + for r in range(len(txns)): + c = cities.get(txns[r][3], 0) + cities[txns[r][3]] = c + 1 + while l < r and int(txns[r][1]) - int(txns[l][1]) > 60: + cities[txns[l][3]] -= 1 + if cities[txns[l][3]] == 0: + del cities[txns[l][3]] + if l in invalidTxnWithinWindow: + invalidTxnWithinWindow.remove(l) + l += 1 + + if int(txns[r][2]) > 1000: + invalids.append(",".join(txns[r])) + if len(cities) > 1: + for i in range(l, r + 1): + if int(txns[i][2]) <= 1000 and i not in invalidTxnWithinWindow: + invalids.append(",".join(txns[i])) + invalidTxnWithinWindow.add(i) + + return invalids diff --git a/tests/1001-1500/1169. invalid-transactions/sol.py2 b/tests/1001-1500/1169. invalid-transactions/sol.py2 new file mode 100644 index 00000000..e8ed8e38 --- /dev/null +++ b/tests/1001-1500/1169. invalid-transactions/sol.py2 @@ -0,0 +1,42 @@ +class Solution(object): + def invalidTransactions(self, transactions): + """ + :type transactions: List[str] + :rtype: List[str] + """ + userTxns = {} + invalids = [] + + for txn in transactions: + vals = txn.split(",") + if vals[0] not in userTxns: + userTxns[vals[0]] = [] + userTxns[vals[0]].append(vals) + + for user in userTxns: + txns = userTxns[user] + txns.sort(key=lambda x: int(x[1])) + cities = {} + l = 0 + invalidTxnWithinWindow = set() + + for r in range(len(txns)): + c = cities.get(txns[r][3], 0) + cities[txns[r][3]] = c + 1 + while l < r and int(txns[r][1]) - int(txns[l][1]) > 60: + cities[txns[l][3]] -= 1 + if cities[txns[l][3]] == 0: + del cities[txns[l][3]] + if l in invalidTxnWithinWindow: + invalidTxnWithinWindow.remove(l) + l += 1 + + if int(txns[r][2]) > 1000: + invalids.append(",".join(txns[r])) + if len(cities) > 1: + for i in range(l, r + 1): + if int(txns[i][2]) <= 1000 and i not in invalidTxnWithinWindow: + invalids.append(",".join(txns[i])) + invalidTxnWithinWindow.add(i) + + return invalids diff --git a/tests/1001-1500/1169. invalid-transactions/sol.rb b/tests/1001-1500/1169. invalid-transactions/sol.rb new file mode 100644 index 00000000..e4cf0946 --- /dev/null +++ b/tests/1001-1500/1169. invalid-transactions/sol.rb @@ -0,0 +1,48 @@ +# @param {String[]} transactions +# @return {String[]} +def invalid_transactions(transactions) + user_txns = {} + invalids = [] + + transactions.each do |txn| + vals = txn.split(",") + user_txns[vals[0]] ||= [] + user_txns[vals[0]] << vals + end + + user_txns.each do |user, txns| + txns.sort_by! { |x| x[1].to_i } + cities = {} + l = 0 + invalid_txn_within_window = Set.new + + txns.each_with_index do |txn, r| + cities[txn[3]] ||= 0 + cities[txn[3]] += 1 + while l < r && txns[r][1].to_i - txns[l][1].to_i > 60 + cities[txns[l][3]] -= 1 + if cities[txns[l][3]] == 0 + cities.delete(txns[l][3]) + end + if invalid_txn_within_window.include?(l) + invalid_txn_within_window.delete(l) + end + l += 1 + end + + if txns[r][2].to_i > 1000 + invalids << txns[r].join(",") + end + if cities.length > 1 + (l..r).each do |i| + if txns[i][2].to_i <= 1000 && !invalid_txn_within_window.include?(i) + invalids << txns[i].join(",") + invalid_txn_within_window.add(i) + end + end + end + end + end + + invalids +end diff --git a/tests/1001-1500/1169. invalid-transactions/sol.rs b/tests/1001-1500/1169. invalid-transactions/sol.rs new file mode 100644 index 00000000..5f647322 --- /dev/null +++ b/tests/1001-1500/1169. invalid-transactions/sol.rs @@ -0,0 +1,56 @@ +impl Solution { + pub fn invalid_transactions(transactions: Vec) -> Vec { + use std::collections::{HashMap, HashSet}; + + let mut user_txns: HashMap>> = HashMap::new(); + let mut invalids: Vec = Vec::new(); + + for txn in &transactions { + let vals: Vec = txn.split(',').map(|s| s.to_string()).collect(); + user_txns + .entry(vals[0].clone()) + .or_insert_with(Vec::new) + .push(vals); + } + + for (_, mut txns) in user_txns { + txns.sort_by_key(|x| x[1].parse::().unwrap()); + let mut cities: HashMap = HashMap::new(); + let mut l = 0; + let mut invalid_txn_within_window: HashSet = HashSet::new(); + + for r in 0..txns.len() { + *cities.entry(txns[r][3].clone()).or_insert(0) += 1; + while l < r { + let time_r: i32 = txns[r][1].parse().unwrap(); + let time_l: i32 = txns[l][1].parse().unwrap(); + if time_r - time_l <= 60 { + break; + } + *cities.get_mut(&txns[l][3]).unwrap() -= 1; + if cities[&txns[l][3]] == 0 { + cities.remove(&txns[l][3]); + } + invalid_txn_within_window.remove(&l); + l += 1; + } + + let amount: i32 = txns[r][2].parse().unwrap(); + if amount > 1000 { + invalids.push(txns[r].join(",")); + } + if cities.len() > 1 { + for i in l..=r { + let amt: i32 = txns[i][2].parse().unwrap(); + if amt <= 1000 && !invalid_txn_within_window.contains(&i) { + invalids.push(txns[i].join(",")); + invalid_txn_within_window.insert(i); + } + } + } + } + } + + invalids + } +} diff --git a/tests/1001-1500/1169. invalid-transactions/sol.swift b/tests/1001-1500/1169. invalid-transactions/sol.swift new file mode 100644 index 00000000..e57bde8f --- /dev/null +++ b/tests/1001-1500/1169. invalid-transactions/sol.swift @@ -0,0 +1,44 @@ +class Solution { + func invalidTransactions(_ transactions: [String]) -> [String] { + var userTxns = [String: [[String]]]() + var invalids = [String]() + + for txn in transactions { + let vals = txn.split(separator: ",").map(String.init) + userTxns[vals[0], default: []].append(vals) + } + + for (_, txns) in userTxns { + var sorted = txns.sorted { Int($0[1])! < Int($1[1])! } + var cities = [String: Int]() + var l = 0 + var invalidTxnWithinWindow = Set() + + for r in 0.. 60 { + cities[sorted[l][3]]! -= 1 + if cities[sorted[l][3]]! == 0 { + cities.removeValue(forKey: sorted[l][3]) + } + invalidTxnWithinWindow.remove(l) + l += 1 + } + + if Int(sorted[r][2])! > 1000 { + invalids.append(sorted[r].joined(separator: ",")) + } + if cities.count > 1 { + for i in l...r { + if Int(sorted[i][2])! <= 1000 && !invalidTxnWithinWindow.contains(i) { + invalids.append(sorted[i].joined(separator: ",")) + invalidTxnWithinWindow.insert(i) + } + } + } + } + } + + return invalids + } +} diff --git a/tests/1001-1500/1169. invalid-transactions/sol.ts b/tests/1001-1500/1169. invalid-transactions/sol.ts new file mode 100644 index 00000000..e02dc723 --- /dev/null +++ b/tests/1001-1500/1169. invalid-transactions/sol.ts @@ -0,0 +1,45 @@ +function invalidTransactions(transactions: string[]): string[] { + const userTxns: Map = new Map(); + const invalids: string[] = []; + + for (const txn of transactions) { + const vals = txn.split(","); + if (!userTxns.has(vals[0])) { + userTxns.set(vals[0], []); + } + userTxns.get(vals[0])!.push(vals); + } + + for (const [, txns] of userTxns) { + txns.sort((a, b) => parseInt(a[1]) - parseInt(b[1])); + const cities: Map = new Map(); + let l = 0; + const invalidTxnWithinWindow: Set = new Set(); + + for (let r = 0; r < txns.length; r++) { + cities.set(txns[r][3], (cities.get(txns[r][3]) || 0) + 1); + while (l < r && parseInt(txns[r][1]) - parseInt(txns[l][1]) > 60) { + cities.set(txns[l][3], cities.get(txns[l][3])! - 1); + if (cities.get(txns[l][3]) === 0) { + cities.delete(txns[l][3]); + } + invalidTxnWithinWindow.delete(l); + l++; + } + + if (parseInt(txns[r][2]) > 1000) { + invalids.push(txns[r].join(",")); + } + if (cities.size > 1) { + for (let i = l; i <= r; i++) { + if (parseInt(txns[i][2]) <= 1000 && !invalidTxnWithinWindow.has(i)) { + invalids.push(txns[i].join(",")); + invalidTxnWithinWindow.add(i); + } + } + } + } + } + + return invalids; +} diff --git a/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/manifest.yaml b/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/manifest.yaml new file mode 100644 index 00000000..e31b191f --- /dev/null +++ b/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/manifest.yaml @@ -0,0 +1,409 @@ +entry: + id: 1170 + title: "compare-strings-by-frequency-of-the-smallest-character" + params: + queries: + type: array + items: + type: string + words: + type: array + items: + type: string + call: + cpp: "Solution().numSmallerByFrequency({queries}, {words})" + rust: "Solution::num_smaller_by_frequency({queries}, {words})" + python3: "Solution().numSmallerByFrequency({queries}, {words})" + python2: "Solution().numSmallerByFrequency({queries}, {words})" + ruby: "num_smaller_by_frequency({queries}, {words})" + java: "new Solution().numSmallerByFrequency({queries}, {words})" + csharp: "new Solution().NumSmallerByFrequency({queries}, {words})" + kotlin: "Solution().numSmallerByFrequency({queries}, {words})" + go: "numSmallerByFrequency({queries}, {words})" + dart: "Solution().numSmallerByFrequency({queries}, {words})" + swift: "Solution().numSmallerByFrequency({queries}, {words})" + typescript: "numSmallerByFrequency({queries}, {words})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 300 + +oracle: + python3: + call: "Checker().numSmallerByFrequency(queries, words, {result})" + checker: | + class Checker: + def numSmallerByFrequency(self, queries, words, result): + if not isinstance(result, list) or len(result) != len(queries): + return False + def frequency(s): + smallest = min(s) + return sum(char == smallest for char in s) + counts = [0] * 11 + for word in words: + counts[frequency(word)] += 1 + greater_than = [0] * 11 + running = 0 + for value in range(10, -1, -1): + greater_than[value] = running + running += counts[value] + expected = [greater_than[frequency(query)] for query in queries] + return result == expected + +seed: 1170 + +tests: + - name: "example_1" + in: + queries: + - cbd + words: + - zaaaz + out: [1] + - name: "example_2" + in: + queries: ["bbb", "cc"] + words: ["a", "aa", "aaa", "aaaa"] + out: [1, 2] + - name: "single_equal_frequency" + in: + queries: ["a"] + words: ["b"] + out: [0] + - name: "single_strictly_smaller" + in: + queries: ["z"] + words: ["a", "bb", "ccc"] + out: [2] + - name: "maximum_frequency_query" + in: + queries: ["aaaaaaaaaa", "zzzzzzzzzz"] + words: ["b", "cc", "ddd", "eeeeeeeeee"] + out: [0, 0] + - name: "all_words_maximum_frequency" + in: + queries: ["a", "bb", "ccccccccc"] + words: ["aaaaaaaaaa", "bbbbbbbbbb", "cccccccccc"] + out: [3, 3, 3] + - name: "strict_thresholds_one_through_five" + in: + queries: ["x", "xx", "xxx", "xxxx", "xxxxx"] + words: ["a", "bb", "ccc", "dddd", "eeeee"] + out: [4, 3, 2, 1, 0] + - name: "duplicate_words_at_thresholds" + in: + queries: ["z", "zz", "zzz", "zzzz"] + words: ["a", "a", "bb", "bb", "bb", "ccc", "dddd"] + out: [5, 2, 1, 0] + - name: "duplicate_queries" + in: + queries: ["az", "az", "aaaa", "az"] + words: ["b", "cc", "ddd", "eeee"] + out: [3, 3, 0, 3] + - name: "minimum_character_not_first" + in: + queries: ["dcce", "edc", "bba"] + words: ["zaaaz", "zzzz", "abcabc", "ccccc"] + out: [3, 4, 4] + - name: "minimum_character_not_last" + in: + queries: ["abca", "babc", "zz"] + words: ["aa", "baab", "cabc", "deed", "fgh"] + out: [0, 3, 0] + - name: "late_minimum_with_mixed_counts" + in: + queries: ["xxa", "yyyb", "zzzzc"] + words: ["mama", "nono", "opopo", "qrrrr", "ststst"] + out: [4, 4, 4] + - name: "lexicographic_extremes" + in: + queries: ["zazaz", "yzyzy", "azaza", "zzzzz"] + words: ["z", "zz", "az", "aaz", "aaaaa", "yyyyy"] + out: [2, 2, 2, 0] + - name: "minimum_changes_inside_string" + in: + queries: ["caa", "bcc", "ddd"] + words: ["baa", "abbb", "caccc", "zzzz", "xy"] + out: [1, 2, 1] + - name: "same_frequency_does_not_count" + in: + queries: ["a", "aa", "aaa"] + words: ["a", "aa", "aaa"] + out: [2, 1, 0] + - name: "all_word_frequencies_one" + in: + queries: ["aa", "bbb", "cccc"] + words: ["abc", "bcd", "cde", "def", "efg"] + out: [0, 0, 0] + - name: "all_query_frequencies_one" + in: + queries: ["bcdef", "azbyc", "zyxwv"] + words: ["a", "bb", "ccc", "dddd", "eeeee", "ffffff"] + out: [5, 5, 5] + - name: "length_ten_boundaries" + in: + queries: ["z", "zzzzz", "abcdefghij", "aaaaaaaaaa"] + words: ["a", "bbbbbbbbbb", "cccccccccc", "dddd", "eeeeee"] + out: [4, 3, 4, 0] + - name: "mixed_frequencies_and_lengths" + in: + queries: ["aa", "ba", "zzz", "ccca"] + words: ["a", "bb", "ccc", "dddd", "eeeee"] + out: [3, 4, 2, 4] + - name: "nonminimum_repetitions_ignored" + in: + queries: ["qxxq", "rqrqr", "zzzz"] + words: ["aaa", "baaa", "ccccc", "dddddd", "xyzxyz"] + out: [4, 4, 2] + - name: "all_single_characters" + in: + queries: ["a", "b", "c", "z"] + words: ["a", "b", "c", "z"] + out: [0, 0, 0, 0] + - name: "two_word_boundaries" + in: + queries: ["a", "bb", "ccc", "dddd"] + words: ["x", "yyyy"] + out: [1, 1, 1, 0] + - name: "frequency_distribution_with_gaps" + in: + queries: ["a", "bb", "ccc", "dddd"] + words: ["x", "yy", "zzz", "wwww", "vvvvv", "uuuuuu", "ttttttt"] + out: [6, 5, 4, 3] + - name: "minimum_ties_across_letters" + in: + queries: ["ba", "cba", "dcba", "edcba"] + words: ["aa", "baa", "caa", "daaa", "eaaaa"] + out: [5, 5, 5, 5] + - name: "same_minimum_different_lengths" + in: + queries: ["mnop", "nmn", "opopop", "zzzzzz"] + words: ["m", "mm", "nmn", "oooo", "ppppp", "qqqqqq"] + out: [4, 4, 3, 0] + - name: "minimum_is_z" + in: + queries: ["z", "zz", "zzz", "zzzzzzzzzz"] + words: ["z", "zz", "zzz", "zzzz", "zzzzzzzzzz"] + out: [4, 3, 2, 0] + - name: "interior_alphabet_minimum" + in: + queries: ["mnop", "nnnn", "opq", "rrrrr"] + words: ["m", "mm", "nmn", "oooo", "ppppp", "qqqqqq"] + out: [4, 2, 4, 1] + - name: "repeated_minimum_after_larger_prefix" + in: + queries: ["baaa", "caba", "ddad"] + words: ["aaaa", "baaa", "ccac", "dddd", "edede"] + out: [2, 3, 4] + - name: "ten_distinct_frequency_levels" + in: + queries: + [ + "a", + "bb", + "ccc", + "dddd", + "eeeee", + "ffffff", + "ggggggg", + "hhhhhhhh", + "iiiiiiiii", + "jjjjjjjjjj", + ] + words: + [ + "a", + "bb", + "ccc", + "dddd", + "eeeee", + "ffffff", + "ggggggg", + "hhhhhhhh", + "iiiiiiiii", + "jjjjjjjjjj", + ] + out: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] + - name: "duplicate_frequency_buckets" + in: + queries: + [ + "z", + "zz", + "zzz", + "zzzz", + "zzzzz", + "zzzzzz", + "zzzzzzz", + "zzzzzzzz", + "zzzzzzzzz", + "zzzzzzzzzz", + ] + words: + [ + "a", + "aa", + "aa", + "aaa", + "aaa", + "aaa", + "bbbb", + "bbbb", + "ccccc", + "dddddd", + "eeeeeee", + "ffffffff", + "ggggggggg", + "hhhhhhhhhh", + ] + out: [13, 11, 8, 6, 5, 4, 3, 2, 1, 0] + - name: "minimum_frequency_one_among_long_strings" + in: + queries: ["abcdefghi", "jihgfedcba", "zxywvutsrq"] + words: ["zzzzzzzzzz", "yyyyyyyyyy", "xxxxxxxxxx", "wvvvvvvvvv"] + out: [4, 4, 4] + - name: "word_minimum_counts_with_noise" + in: + queries: ["k", "kk", "kkk", "kkkk"] + words: + ["azazazazaz", "baaaaaaaac", "cbbbbbdddd", "dccccccccc", "eeeeeeeeee"] + out: [5, 5, 5, 5] + - name: "strict_comparison_on_frequency_five" + in: + queries: ["aaaaa", "zzzzz"] + words: ["aaaaaaaaaa", "baaaaaaaac", "caaaaddddd", "dddddddddd"] + out: [3, 3] + - name: "different_smallest_characters_same_frequency" + in: + queries: ["abc", "bcd", "cde", "def"] + words: ["za", "yb", "xc", "wd", "veee"] + out: [1, 1, 1, 1] + - name: "stress_full_alphabet" + seed: 117001 + in: + queries: + gen: "array" + len: 2000 + of: + gen: "str" + len: 10 + alphabet: "abcdefghijklmnopqrstuvwxyz" + distinct: false + sorted: false + words: + gen: "array" + len: 2000 + of: + gen: "str" + len: 10 + alphabet: "abcdefghijklmnopqrstuvwxyz" + distinct: false + sorted: false + - name: "stress_low_alphabet" + seed: 117002 + in: + queries: + gen: "array" + len: 2000 + of: + gen: "str" + len: 10 + alphabet: "abc" + distinct: false + sorted: false + words: + gen: "array" + len: 2000 + of: + gen: "str" + len: 10 + alphabet: "abc" + distinct: false + sorted: false + - name: "stress_high_alphabet" + seed: 117003 + in: + queries: + gen: "array" + len: 2000 + of: + gen: "str" + len: 10 + alphabet: "xyz" + distinct: false + sorted: false + words: + gen: "array" + len: 2000 + of: + gen: "str" + len: 10 + alphabet: "xyz" + distinct: false + sorted: false + - name: "stress_vowels_and_consonants" + seed: 117004 + in: + queries: + gen: "array" + len: 2000 + of: + gen: "str" + len: 10 + alphabet: "aeiouz" + distinct: false + sorted: false + words: + gen: "array" + len: 2000 + of: + gen: "str" + len: 10 + alphabet: "aeiouz" + distinct: false + sorted: false + - name: "stress_middle_alphabet" + seed: 117005 + in: + queries: + gen: "array" + len: 2000 + of: + gen: "str" + len: 10 + alphabet: "jklmnop" + distinct: false + sorted: false + words: + gen: "array" + len: 2000 + of: + gen: "str" + len: 10 + alphabet: "jklmnop" + distinct: false + sorted: false + - name: "stress_skewed_endpoints" + seed: 117006 + in: + queries: + gen: "array" + len: 2000 + of: + gen: "str" + len: 10 + alphabet: "aaabz" + distinct: false + sorted: false + words: + gen: "array" + len: 2000 + of: + gen: "str" + len: 10 + alphabet: "aaabz" + distinct: false + sorted: false diff --git a/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.cpp b/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.cpp new file mode 100644 index 00000000..336ba0a2 --- /dev/null +++ b/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + vector numSmallerByFrequency(vector& queries, vector& words) { + auto f = [](const string& s) -> int { + char minChar = 'z'; + int count = 0; + for (char c : s) { + if (c < minChar) { + minChar = c; + count = 1; + } else if (c == minChar) { + count++; + } + } + return count; + }; + + vector buckets(12, 0); + for (const string& w : words) { + buckets[f(w)]++; + } + for (int i = 9; i >= 0; i--) { + buckets[i] += buckets[i + 1]; + } + + vector result; + for (const string& q : queries) { + result.push_back(buckets[f(q) + 1]); + } + return result; + } +}; diff --git a/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.cs b/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.cs new file mode 100644 index 00000000..ea7ceb9d --- /dev/null +++ b/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.cs @@ -0,0 +1,31 @@ +public class Solution { + public int[] NumSmallerByFrequency(string[] queries, string[] words) { + int F(string s) { + char minChar = 'z'; + int count = 0; + foreach (char c in s) { + if (c < minChar) { + minChar = c; + count = 1; + } else if (c == minChar) { + count++; + } + } + return count; + } + + int[] buckets = new int[12]; + foreach (string w in words) { + buckets[F(w)]++; + } + for (int i = 9; i >= 0; i--) { + buckets[i] += buckets[i + 1]; + } + + int[] result = new int[queries.Length]; + for (int i = 0; i < queries.Length; i++) { + result[i] = buckets[F(queries[i]) + 1]; + } + return result; + } +} diff --git a/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.dart b/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.dart new file mode 100644 index 00000000..5be71a4e --- /dev/null +++ b/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.dart @@ -0,0 +1,27 @@ +class Solution { + List numSmallerByFrequency(List queries, List words) { + int f(String s) { + String minChar = 'z'; + int count = 0; + for (int i = 0; i < s.length; i++) { + if (s[i].compareTo(minChar) < 0) { + minChar = s[i]; + count = 1; + } else if (s[i] == minChar) { + count++; + } + } + return count; + } + + List buckets = List.filled(12, 0); + for (String w in words) { + buckets[f(w)]++; + } + for (int i = 9; i >= 0; i--) { + buckets[i] += buckets[i + 1]; + } + + return queries.map((q) => buckets[f(q) + 1]).toList(); + } +} diff --git a/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.go b/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.go new file mode 100644 index 00000000..f3b765f9 --- /dev/null +++ b/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.go @@ -0,0 +1,29 @@ +func numSmallerByFrequency(queries []string, words []string) []int { + f := func(s string) int { + minChar := byte('z') + count := 0 + for i := 0; i < len(s); i++ { + if s[i] < minChar { + minChar = s[i] + count = 1 + } else if s[i] == minChar { + count++ + } + } + return count + } + + buckets := make([]int, 12) + for _, w := range words { + buckets[f(w)]++ + } + for i := 9; i >= 0; i-- { + buckets[i] += buckets[i+1] + } + + result := make([]int, len(queries)) + for i, q := range queries { + result[i] = buckets[f(q)+1] + } + return result +} diff --git a/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.java b/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.java new file mode 100644 index 00000000..cb4f1d1c --- /dev/null +++ b/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.java @@ -0,0 +1,30 @@ +class Solution { + public int[] numSmallerByFrequency(String[] queries, String[] words) { + int[] buckets = new int[12]; + for (String w : words) { + buckets[f(w)]++; + } + for (int i = 9; i >= 0; i--) { + buckets[i] += buckets[i + 1]; + } + int[] result = new int[queries.length]; + for (int i = 0; i < queries.length; i++) { + result[i] = buckets[f(queries[i]) + 1]; + } + return result; + } + + private int f(String s) { + char minChar = 'z'; + int count = 0; + for (char c : s.toCharArray()) { + if (c < minChar) { + minChar = c; + count = 1; + } else if (c == minChar) { + count++; + } + } + return count; + } +} diff --git a/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.kt b/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.kt new file mode 100644 index 00000000..aa9234ac --- /dev/null +++ b/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.kt @@ -0,0 +1,26 @@ +class Solution { + fun numSmallerByFrequency(queries: Array, words: Array): IntArray { + fun f(s: String): Int { + var minChar = 'z' + var count = 0 + for (c in s) { + if (c < minChar) { + minChar = c + count = 1 + } else if (c == minChar) { + count++ + } + } + return count + } + + val buckets = IntArray(12) + for (w in words) { + buckets[f(w)]++ + } + for (i in 9 downTo 0) { + buckets[i] += buckets[i + 1] + } + return queries.map { buckets[f(it) + 1] }.toIntArray() + } +} diff --git a/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.py b/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.py new file mode 100644 index 00000000..bc017049 --- /dev/null +++ b/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.py @@ -0,0 +1,32 @@ +import bisect + + +class Solution: + def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]: + # 1. The f(s) Kernel: Projection into the Frequency Manifold + def f(s: str) -> int: + # We identify the 'Infimum' (min char) and its Density + min_char = "z" + count = 0 + for char in s: + if char < min_char: + min_char = char + count = 1 + elif char == min_char: + count += 1 + return count + + # 2. Suffix-Sum Integration (Bucket Sorting) + # Since the max frequency is bounded (max length 10), + # we use a Fixed-Width Bucket to avoid the 'Sorting Dose'. + buckets = [0] * 12 + for w in words: + buckets[f(w)] += 1 + + # Transform buckets into a Suffix Sum (The Cumulative Density Function) + # suffix[i] = total words with frequency > i + for i in range(9, -1, -1): + buckets[i] += buckets[i + 1] + + # 3. O(1) Probing per Query + return [buckets[f(q) + 1] for q in queries] diff --git a/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.py2 b/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.py2 new file mode 100644 index 00000000..f9c93a90 --- /dev/null +++ b/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.py2 @@ -0,0 +1,26 @@ +class Solution(object): + def numSmallerByFrequency(self, queries, words): + """ + :type queries: List[str] + :type words: List[str] + :rtype: List[int] + """ + def f(s): + min_char = 'z' + count = 0 + for char in s: + if char < min_char: + min_char = char + count = 1 + elif char == min_char: + count += 1 + return count + + buckets = [0] * 12 + for w in words: + buckets[f(w)] += 1 + + for i in range(9, -1, -1): + buckets[i] += buckets[i+1] + + return [buckets[f(q) + 1] for q in queries] diff --git a/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.rb b/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.rb new file mode 100644 index 00000000..bd2f6e9e --- /dev/null +++ b/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.rb @@ -0,0 +1,29 @@ +# @param {String[]} queries +# @param {String[]} words +# @return {Integer[]} +def num_smaller_by_frequency(queries, words) + def f(s) + min_char = 'z' + count = 0 + s.each_char do |char| + if char < min_char + min_char = char + count = 1 + elsif char == min_char + count += 1 + end + end + count + end + + buckets = Array.new(12, 0) + words.each do |w| + buckets[f(w)] += 1 + end + + 9.downto(0) do |i| + buckets[i] += buckets[i+1] + end + + queries.map { |q| buckets[f(q) + 1] } +end diff --git a/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.rs b/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.rs new file mode 100644 index 00000000..8233d257 --- /dev/null +++ b/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.rs @@ -0,0 +1,27 @@ +impl Solution { + pub fn num_smaller_by_frequency(queries: Vec, words: Vec) -> Vec { + fn f(s: &str) -> usize { + let mut min_char = 'z'; + let mut count = 0; + for c in s.chars() { + if c < min_char { + min_char = c; + count = 1; + } else if c == min_char { + count += 1; + } + } + count + } + + let mut buckets = vec![0usize; 12]; + for w in &words { + buckets[f(w)] += 1; + } + for i in (0..=9).rev() { + buckets[i] += buckets[i + 1]; + } + + queries.iter().map(|q| buckets[f(q) + 1] as i32).collect() + } +} diff --git a/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.swift b/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.swift new file mode 100644 index 00000000..49c973fc --- /dev/null +++ b/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.swift @@ -0,0 +1,27 @@ +class Solution { + func numSmallerByFrequency(_ queries: [String], _ words: [String]) -> [Int] { + func f(_ s: String) -> Int { + var minChar: Character = "z" + var count = 0 + for char in s { + if char < minChar { + minChar = char + count = 1 + } else if char == minChar { + count += 1 + } + } + return count + } + + var buckets = [Int](repeating: 0, count: 12) + for w in words { + buckets[f(w)] += 1 + } + for i in stride(from: 9, through: 0, by: -1) { + buckets[i] += buckets[i + 1] + } + + return queries.map { buckets[f($0) + 1] } + } +} diff --git a/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.ts b/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.ts new file mode 100644 index 00000000..94ed8661 --- /dev/null +++ b/tests/1001-1500/1170. compare-strings-by-frequency-of-the-smallest-character/sol.ts @@ -0,0 +1,25 @@ +function numSmallerByFrequency(queries: string[], words: string[]): number[] { + const f = (s: string): number => { + let minChar = "z"; + let count = 0; + for (const char of s) { + if (char < minChar) { + minChar = char; + count = 1; + } else if (char === minChar) { + count++; + } + } + return count; + }; + + const buckets = new Array(12).fill(0); + for (const w of words) { + buckets[f(w)]++; + } + for (let i = 9; i >= 0; i--) { + buckets[i] += buckets[i + 1]; + } + + return queries.map((q) => buckets[f(q) + 1]); +} diff --git a/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/manifest.yaml b/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/manifest.yaml new file mode 100644 index 00000000..76941a17 --- /dev/null +++ b/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/manifest.yaml @@ -0,0 +1,260 @@ +entry: + id: 1171 + title: remove-zero-sum-consecutive-nodes-from-linked-list + params: + head: + type: list_node + call: + cpp: "listNodeToArray(Solution().removeZeroSumSublists({head}))" + rust: "ListNode::list_node_to_array(Solution::remove_zero_sum_sublists({head}))" + python3: "list_node_to_array(Solution().removeZeroSumSublists({head}))" + python2: "list_node_to_array(Solution().removeZeroSumSublists({head}))" + ruby: "list_node_to_array(remove_zero_sum_sublists({head}))" + java: "ListNode.listNodeToArray(new Solution().removeZeroSumSublists({head}))" + csharp: "ListNode.ListNodeToArray(new Solution().RemoveZeroSumSublists({head}))" + kotlin: "listNodeToArray(Solution().removeZeroSumSublists({head}))" + go: "listNodeToArray(removeZeroSumSublists({head}))" + dart: "list_node_to_array(Solution().removeZeroSumSublists({head}))" + swift: "list_node_to_array(Solution().removeZeroSumSublists({head}))" + typescript: "listNodeToArray(removeZeroSumSublists({head}))" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().removeZeroSumSublists(head, {result})" + checker: | + class Checker: + def removeZeroSumSublists(self, head, result): + if not isinstance(head, list) or not isinstance(result, list): + return False + if not 1 <= len(head) <= 1000: + return False + if any(isinstance(value, bool) or not isinstance(value, int) or value < -1000 or value > 1000 for value in head): + return False + if any(isinstance(value, bool) or not isinstance(value, int) for value in result): + return False + + # A final list cannot contain another removable zero-sum interval. + seen_sums = set([0]) + total = 0 + for value in result: + total += value + if total in seen_sums: + return False + seen_sums.add(total) + + # Every removed gap between retained nodes must sum to zero. Dynamic + # programming checks that some matching subsequence has that property. + prefix = [0] + for value in head: + prefix.append(prefix[-1] + value) + if not result: + return prefix[-1] == 0 + + previous = set() + for index, value in enumerate(head): + if value == result[0] and prefix[index] == 0: + previous.add(index) + if not previous: + return False + + for wanted in result[1:]: + current = set() + next_prefixes = dict() + for prior in previous: + total = prefix[prior + 1] + if total not in next_prefixes or prior < next_prefixes[total]: + next_prefixes[total] = prior + for index, value in enumerate(head): + if value == wanted and next_prefixes.get(prefix[index], index) < index: + current.add(index) + if not current: + return False + previous = current + + return any(prefix[index + 1] == prefix[-1] for index in previous) +seed: 1171 +tests: + - name: example_one_multiple_valid_finals + in: + head: [1, 2, -3, 3, 1] + - name: example_two_internal_pair + in: + head: [1, 2, 3, -3, 4] + - name: example_three_suffix_chain + in: + head: [1, 2, 3, -3, -2] + - name: single_zero + in: + head: [0] + - name: single_positive + in: + head: [7] + - name: single_negative + in: + head: [-7] + - name: adjacent_opposites + in: + head: [1, -1] + - name: all_zeroes + in: + head: [0, 0, 0, 0, 0] + - name: entire_list_cancels + in: + head: [4, -1, -3] + - name: zero_prefix + in: + head: [3, -3, 5, 6] + - name: zero_suffix + in: + head: [5, 6, 3, -3] + - name: nested_zero_span + in: + head: [2, 3, -3, -2] + - name: overlapping_removal_choices + in: + head: [1, 2, -2, -1, 3] + - name: repeated_prefix_sums + in: + head: [1, 3, -3, 2, -2, 4] + - name: strictly_positive_survives + in: + head: [1, 2, 3, 4, 5] + - name: strictly_negative_survives + in: + head: [-1, -2, -3, -4] + - name: alternating_pairs + in: + head: [5, -5, 6, -6, 7, -7] + - name: internal_single_zero + in: + head: [8, 0, -2] + - name: cascading_after_removal + in: + head: [1, 2, -3, 3, -3] + - name: enclosing_cancellation + in: + head: [2, 1, -1, -2, 9] + - name: duplicate_prefix_values + in: + head: [1, 2, -3, 1, -1, 2] + - name: maximum_value_pair + in: + head: [1000, -1000, 999] + - name: boundary_values_retained + in: + head: [-1000, 1, -1, 1000] + - name: two_disjoint_zero_runs + in: + head: [9, 4, -4, 8, -8, 7] + - name: zero_gap_between_survivors + in: + head: [6, 2, -2, 5] + - name: middle_removal_creates_new_zero_sum + in: + head: [1, 2, -2, -1, 4] + - name: prefix_and_suffix_removals + in: + head: [3, -3, 8, 4, -4] + - name: repeated_zero_prefixes + in: + head: [1, -1, 2, -2, 3] + - name: negative_positive_mixture + in: + head: [-4, 6, -2, -5, 5, 3] + - name: zero_pair_at_end + in: + head: [4, -2, 2] + - name: zero_pair_at_start + in: + head: [-2, 2, 4] + - name: preserved_duplicate_values + in: + head: [2, 2, -1, 3] + - name: long_static_mixed_intervals + in: + head: [10, -3, -7, 4, -4, 6, 1, -1, -6, 8, 9] + - name: large_magnitude_nonzero_total + in: + head: [1000, -999, -1, 998, -997, 4] + - name: stress_seed_101 + seed: 101 + in: + head: + gen: array + len: 1000 + of: + gen: int + min: -1000 + max: 1000 + distinct: false + sorted: false + elemType: int + - name: stress_seed_202 + seed: 202 + in: + head: + gen: array + len: 1000 + of: + gen: int + min: -1000 + max: 1000 + distinct: false + sorted: false + elemType: int + - name: stress_seed_303 + seed: 303 + in: + head: + gen: array + len: 1000 + of: + gen: int + min: -1000 + max: 1000 + distinct: false + sorted: false + elemType: int + - name: stress_seed_404 + seed: 404 + in: + head: + gen: array + len: 1000 + of: + gen: int + min: -1000 + max: 1000 + distinct: false + sorted: false + elemType: int + - name: stress_seed_505 + seed: 505 + in: + head: + gen: array + len: 1000 + of: + gen: int + min: -1000 + max: 1000 + distinct: false + sorted: false + elemType: int + - name: stress_seed_606 + seed: 606 + in: + head: + gen: array + len: 1000 + of: + gen: int + min: -1000 + max: 1000 + distinct: false + sorted: false + elemType: int diff --git a/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.cpp b/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.cpp new file mode 100644 index 00000000..e037128c --- /dev/null +++ b/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.cpp @@ -0,0 +1,36 @@ +/** + * 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* removeZeroSumSublists(ListNode* head) { + ListNode* dummy = new ListNode(0); + dummy->next = head; + int prefixSum = 0; + std::unordered_map seen; + + ListNode* curr = dummy; + while (curr) { + prefixSum += curr->val; + seen[prefixSum] = curr; + curr = curr->next; + } + + prefixSum = 0; + curr = dummy; + while (curr) { + prefixSum += curr->val; + curr->next = seen[prefixSum]->next; + curr = curr->next; + } + + return dummy->next; + } +}; diff --git a/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.cs b/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.cs new file mode 100644 index 00000000..44a9ffc9 --- /dev/null +++ b/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.cs @@ -0,0 +1,36 @@ +/** + * 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 RemoveZeroSumSublists(ListNode head) { + ListNode dummy = new ListNode(0); + dummy.next = head; + int prefixSum = 0; + Dictionary seen = new Dictionary(); + + ListNode curr = dummy; + while (curr != null) { + prefixSum += curr.val; + seen[prefixSum] = curr; + curr = curr.next; + } + + prefixSum = 0; + curr = dummy; + while (curr != null) { + prefixSum += curr.val; + curr.next = seen[prefixSum].next; + curr = curr.next; + } + + return dummy.next; + } +} diff --git a/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.dart b/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.dart new file mode 100644 index 00000000..ee36e88d --- /dev/null +++ b/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.dart @@ -0,0 +1,33 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * int val; + * ListNode? next; + * ListNode([this.val = 0, this.next]); + * } + */ +class Solution { + ListNode? removeZeroSumSublists(ListNode? head) { + ListNode dummy = ListNode(0); + dummy.next = head; + int prefixSum = 0; + Map seen = {}; + + ListNode? curr = dummy; + while (curr != null) { + prefixSum += curr.val; + seen[prefixSum] = curr; + curr = curr.next; + } + + prefixSum = 0; + curr = dummy; + while (curr != null) { + prefixSum += curr.val; + curr.next = seen[prefixSum]!.next; + curr = curr.next; + } + + return dummy.next; + } +} diff --git a/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.go b/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.go new file mode 100644 index 00000000..f88ca1b6 --- /dev/null +++ b/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.go @@ -0,0 +1,29 @@ +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func removeZeroSumSublists(head *ListNode) *ListNode { + dummy := &ListNode{Val: 0, Next: head} + prefixSum := 0 + seen := make(map[int]*ListNode) + + curr := dummy + for curr != nil { + prefixSum += curr.Val + seen[prefixSum] = curr + curr = curr.Next + } + + prefixSum = 0 + curr = dummy + for curr != nil { + prefixSum += curr.Val + curr.Next = seen[prefixSum].Next + curr = curr.Next + } + + return dummy.Next +} diff --git a/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.java b/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.java new file mode 100644 index 00000000..3e029e27 --- /dev/null +++ b/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.java @@ -0,0 +1,35 @@ +/** + * 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 removeZeroSumSublists(ListNode head) { + ListNode dummy = new ListNode(0); + dummy.next = head; + int prefixSum = 0; + java.util.Map seen = new java.util.HashMap<>(); + + ListNode curr = dummy; + while (curr != null) { + prefixSum += curr.val; + seen.put(prefixSum, curr); + curr = curr.next; + } + + prefixSum = 0; + curr = dummy; + while (curr != null) { + prefixSum += curr.val; + curr.next = seen.get(prefixSum).next; + curr = curr.next; + } + + return dummy.next; + } +} diff --git a/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.kt b/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.kt new file mode 100644 index 00000000..40108c3c --- /dev/null +++ b/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.kt @@ -0,0 +1,34 @@ +/** + * 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 removeZeroSumSublists(head: ListNode?): ListNode? { + val dummy = ListNode(0) + dummy.next = head + var prefixSum = 0 + val seen = mutableMapOf() + + var curr: ListNode? = dummy + while (curr != null) { + prefixSum += curr.`val` + seen[prefixSum] = curr + curr = curr.next + } + + prefixSum = 0 + curr = dummy + while (curr != null) { + prefixSum += curr.`val` + curr.next = seen[prefixSum]!!.next + curr = curr.next + } + + return dummy.next + } +} diff --git a/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.py b/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.py new file mode 100644 index 00000000..4f052ea3 --- /dev/null +++ b/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.py @@ -0,0 +1,30 @@ +# 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 removeZeroSumSublists(self, head): + """ + :type head: Optional[ListNode] + :rtype: Optional[ListNode] + """ + dummy = ListNode(0) + dummy.next = head + prefix_sum = 0 + seen = {} + + curr = dummy + while curr: + prefix_sum += curr.val + seen[prefix_sum] = curr + curr = curr.next + + prefix_sum = 0 + curr = dummy + while curr: + prefix_sum += curr.val + curr.next = seen[prefix_sum].next + curr = curr.next + + return dummy.next diff --git a/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.py2 b/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.py2 new file mode 100644 index 00000000..4f052ea3 --- /dev/null +++ b/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.py2 @@ -0,0 +1,30 @@ +# 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 removeZeroSumSublists(self, head): + """ + :type head: Optional[ListNode] + :rtype: Optional[ListNode] + """ + dummy = ListNode(0) + dummy.next = head + prefix_sum = 0 + seen = {} + + curr = dummy + while curr: + prefix_sum += curr.val + seen[prefix_sum] = curr + curr = curr.next + + prefix_sum = 0 + curr = dummy + while curr: + prefix_sum += curr.val + curr.next = seen[prefix_sum].next + curr = curr.next + + return dummy.next diff --git a/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.rb b/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.rb new file mode 100644 index 00000000..bf643f1b --- /dev/null +++ b/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.rb @@ -0,0 +1,33 @@ +# 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 +# @return {ListNode} +def remove_zero_sum_sublists(head) + dummy = ListNode.new(0) + dummy.next = head + prefix_sum = 0 + seen = {} + + curr = dummy + while curr + prefix_sum += curr.val + seen[prefix_sum] = curr + curr = curr.next + end + + prefix_sum = 0 + curr = dummy + while curr + prefix_sum += curr.val + curr.next = seen[prefix_sum].next + curr = curr.next + end + + dummy.next +end diff --git a/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.rs b/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.rs new file mode 100644 index 00000000..fca83353 --- /dev/null +++ b/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.rs @@ -0,0 +1,34 @@ +impl Solution { + pub fn remove_zero_sum_sublists(head: Option>) -> Option> { + let mut values = Vec::new(); + let mut current = head; + while let Some(mut node) = current { + values.push(node.val); + current = node.next.take(); + } + + loop { + let mut removed = false; + 'outer: for start in 0..values.len() { + let mut sum = 0; + for end in start..values.len() { + sum += values[end]; + if sum == 0 { + values.drain(start..=end); + removed = true; + break 'outer; + } + } + } + if !removed { break; } + } + + let mut result = None; + for value in values.into_iter().rev() { + let mut node = Box::new(ListNode::new(value)); + node.next = result; + result = Some(node); + } + result + } +} diff --git a/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.swift b/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.swift new file mode 100644 index 00000000..33f10169 --- /dev/null +++ b/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.swift @@ -0,0 +1,35 @@ +/** + * 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 removeZeroSumSublists(_ head: ListNode?) -> ListNode? { + let dummy = ListNode(0) + dummy.next = head + var prefixSum = 0 + var seen: [Int: ListNode] = [:] + + var curr: ListNode? = dummy + while curr != nil { + prefixSum += curr!.val + seen[prefixSum] = curr + curr = curr!.next + } + + prefixSum = 0 + curr = dummy + while curr != nil { + prefixSum += curr!.val + curr!.next = seen[prefixSum]!.next + curr = curr!.next + } + + return dummy.next + } +} diff --git a/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.ts b/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.ts new file mode 100644 index 00000000..611ee0ea --- /dev/null +++ b/tests/1001-1500/1171. remove-zero-sum-consecutive-nodes-from-linked-list/sol.ts @@ -0,0 +1,35 @@ +/** + * 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 removeZeroSumSublists(head: ListNode | null): ListNode | null { + const dummy = new ListNode(0); + dummy.next = head; + let prefixSum = 0; + const seen: Map = new Map(); + + let curr: ListNode | null = dummy; + while (curr !== null) { + prefixSum += curr.val; + seen.set(prefixSum, curr); + curr = curr.next; + } + + prefixSum = 0; + curr = dummy; + while (curr !== null) { + prefixSum += curr.val; + curr.next = seen.get(prefixSum)!.next; + curr = curr.next; + } + + return dummy.next; +} diff --git a/tests/1001-1500/1175. prime-arrangements/manifest.yaml b/tests/1001-1500/1175. prime-arrangements/manifest.yaml new file mode 100644 index 00000000..915d6939 --- /dev/null +++ b/tests/1001-1500/1175. prime-arrangements/manifest.yaml @@ -0,0 +1,224 @@ +entry: + id: 1175 + title: "prime-arrangements" + params: + n: + type: int + call: + cpp: "Solution().numPrimeArrangements({n})" + rust: "Solution::num_prime_arrangements({n})" + python3: "Solution().numPrimeArrangements({n})" + python2: "Solution().numPrimeArrangements({n})" + ruby: "num_prime_arrangements({n})" + java: "new Solution().numPrimeArrangements({n})" + csharp: "new Solution().NumPrimeArrangements({n})" + kotlin: "Solution().numPrimeArrangements({n})" + go: "numPrimeArrangements({n})" + dart: "Solution().numPrimeArrangements({n})" + swift: "Solution().numPrimeArrangements({n})" + typescript: "numPrimeArrangements({n})" +judge: + type: "exact" +limits: + time_ms: 300 + memory_mb: 300 +oracle: + python3: + call: "Checker().numPrimeArrangements(n, {result})" + checker: | + class Checker: + def numPrimeArrangements(self, n, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + is_prime = [False, False] + [True] * (n - 1) + for divisor in range(2, int(n ** 0.5) + 1): + if is_prime[divisor]: + for multiple in range(divisor * divisor, n + 1, divisor): + is_prime[multiple] = False + prime_count = sum(is_prime) + expected = 1 + for factor in range(2, prime_count + 1): + expected = expected * factor % 1000000007 + for factor in range(2, n - prime_count + 1): + expected = expected * factor % 1000000007 + return result == expected +seed: 1175 +tests: + - name: "minimum_n1" + in: + n: 1 + out: 1 + - name: "n2_first_prime" + in: + n: 2 + out: 1 + - name: "n3_second_prime" + in: + n: 3 + out: 2 + - name: "n4_first_composite" + in: + n: 4 + out: 4 + - name: "example_n5" + in: + n: 5 + out: 12 + - name: "n6" + in: + n: 6 + out: 36 + - name: "n7_prime_transition" + in: + n: 7 + out: 144 + - name: "n8" + in: + n: 8 + out: 576 + - name: "n9_square_composite" + in: + n: 9 + out: 2880 + - name: "n10" + in: + n: 10 + out: 17280 + - name: "n11_prime_transition" + in: + n: 11 + out: 86400 + - name: "n12" + in: + n: 12 + out: 604800 + - name: "n13_prime_transition" + in: + n: 13 + out: 3628800 + - name: "n14" + in: + n: 14 + out: 29030400 + - name: "n15" + in: + n: 15 + out: 261273600 + - name: "n16_square_composite_modulo" + in: + n: 16 + out: 612735986 + - name: "n17_prime_transition" + in: + n: 17 + out: 289151874 + - name: "n18" + in: + n: 18 + out: 180670593 + - name: "n19_prime_transition" + in: + n: 19 + out: 445364737 + - name: "n20" + in: + n: 20 + out: 344376809 + - name: "n21" + in: + n: 21 + out: 476898489 + - name: "n22" + in: + n: 22 + out: 676578804 + - name: "n23_prime_transition" + in: + n: 23 + out: 89209194 + - name: "n24" + in: + n: 24 + out: 338137903 + - name: "n25_square_composite" + in: + n: 25 + out: 410206413 + - name: "n30" + in: + n: 30 + out: 13697484 + - name: "n40" + in: + n: 40 + out: 965722612 + - name: "n50" + in: + n: 50 + out: 451768713 + - name: "n60" + in: + n: 60 + out: 125049738 + - name: "n70" + in: + n: 70 + out: 892906519 + - name: "n80" + in: + n: 80 + out: 405243354 + - name: "n90" + in: + n: 90 + out: 448961084 + - name: "n99_near_maximum" + in: + n: 99 + out: 75763854 + - name: "example_n100_maximum" + in: + n: 100 + out: 682289015 + - name: "generated_stress_95_100_a" + seed: 117501 + in: + n: + gen: "int" + min: 95 + max: 100 + - name: "generated_stress_95_100_b" + seed: 117502 + in: + n: + gen: "int" + min: 95 + max: 100 + - name: "generated_stress_95_100_c" + seed: 117503 + in: + n: + gen: "int" + min: 95 + max: 100 + - name: "generated_stress_95_100_d" + seed: 117504 + in: + n: + gen: "int" + min: 95 + max: 100 + - name: "generated_stress_95_100_e" + seed: 117505 + in: + n: + gen: "int" + min: 95 + max: 100 + - name: "generated_stress_95_100_f" + seed: 117506 + in: + n: + gen: "int" + min: 95 + max: 100 diff --git a/tests/1001-1500/1175. prime-arrangements/sol.cpp b/tests/1001-1500/1175. prime-arrangements/sol.cpp new file mode 100644 index 00000000..54cea6d6 --- /dev/null +++ b/tests/1001-1500/1175. prime-arrangements/sol.cpp @@ -0,0 +1,47 @@ +class Solution { +private: + static const int MOD = 1000000007; + static bool isPrime[101]; + static int prefixPrime[101]; + static bool initialized; + + static void init() { + if (initialized) return; + for (int i = 2; i <= 100; i++) { + isPrime[i] = true; + } + for (int i = 2; i * i <= 100; i++) { + if (isPrime[i]) { + for (int j = i * i; j <= 100; j += i) { + isPrime[j] = false; + } + } + } + for (int i = 2; i <= 100; i++) { + prefixPrime[i] = prefixPrime[i - 1] + (isPrime[i] ? 1 : 0); + } + initialized = true; + } + +public: + int numPrimeArrangements(int n) { + init(); + int x = prefixPrime[n]; + int y = n - x; + long long proX = 1; + long long proY = 1; + + for (int i = 2; i <= x; i++) { + proX = (proX * i) % MOD; + } + for (int i = 2; i <= y; i++) { + proY = (proY * i) % MOD; + } + + return (int)((proX * proY) % MOD); + } +}; + +bool Solution::isPrime[101]; +int Solution::prefixPrime[101]; +bool Solution::initialized = false; diff --git a/tests/1001-1500/1175. prime-arrangements/sol.cs b/tests/1001-1500/1175. prime-arrangements/sol.cs new file mode 100644 index 00000000..c13c54ed --- /dev/null +++ b/tests/1001-1500/1175. prime-arrangements/sol.cs @@ -0,0 +1,41 @@ +public class Solution { + private const int MOD = 1000000007; + private static bool[] isPrime = new bool[101]; + private static int[] prefixPrime = new int[101]; + private static bool initialized = false; + + private static void Init() { + if (initialized) return; + for (int i = 2; i <= 100; i++) { + isPrime[i] = true; + } + for (int i = 2; i * i <= 100; i++) { + if (isPrime[i]) { + for (int j = i * i; j <= 100; j += i) { + isPrime[j] = false; + } + } + } + for (int i = 2; i <= 100; i++) { + prefixPrime[i] = prefixPrime[i - 1] + (isPrime[i] ? 1 : 0); + } + initialized = true; + } + + public int NumPrimeArrangements(int n) { + Init(); + int x = prefixPrime[n]; + int y = n - x; + long proX = 1; + long proY = 1; + + for (int i = 2; i <= x; i++) { + proX = (proX * i) % MOD; + } + for (int i = 2; i <= y; i++) { + proY = (proY * i) % MOD; + } + + return (int)((proX * proY) % MOD); + } +} diff --git a/tests/1001-1500/1175. prime-arrangements/sol.dart b/tests/1001-1500/1175. prime-arrangements/sol.dart new file mode 100644 index 00000000..bfcce182 --- /dev/null +++ b/tests/1001-1500/1175. prime-arrangements/sol.dart @@ -0,0 +1,43 @@ +class Solution { + static const int MOD = 1000000007; + static final List isPrime = List.filled(101, true); + static final List prefixPrime = List.filled(101, 0); + + static void _init() { + isPrime[0] = false; + isPrime[1] = false; + for (int i = 2; i * i <= 100; i++) { + if (isPrime[i]) { + for (int j = i * i; j <= 100; j += i) { + isPrime[j] = false; + } + } + } + for (int i = 2; i <= 100; i++) { + prefixPrime[i] = prefixPrime[i - 1] + (isPrime[i] ? 1 : 0); + } + _initialized = true; + } + + static bool _initialized = false; + + int numPrimeArrangements(int n) { + if (!_initialized) { + _init(); + } + + int x = prefixPrime[n]; + int y = n - x; + int proX = 1; + int proY = 1; + + for (int i = 2; i <= x; i++) { + proX = (proX * i) % MOD; + } + for (int i = 2; i <= y; i++) { + proY = (proY * i) % MOD; + } + + return (proX * proY) % MOD; + } +} diff --git a/tests/1001-1500/1175. prime-arrangements/sol.go b/tests/1001-1500/1175. prime-arrangements/sol.go new file mode 100644 index 00000000..77c65fae --- /dev/null +++ b/tests/1001-1500/1175. prime-arrangements/sol.go @@ -0,0 +1,39 @@ +const MOD = 1000000007 + +var isPrime [101]bool +var prefixPrime [101]int + +func init() { + for i := 2; i <= 100; i++ { + isPrime[i] = true + } + for i := 2; i*i <= 100; i++ { + if isPrime[i] { + for j := i * i; j <= 100; j += i { + isPrime[j] = false + } + } + } + for i := 2; i <= 100; i++ { + prefixPrime[i] = prefixPrime[i-1] + if isPrime[i] { + prefixPrime[i]++ + } + } +} + +func numPrimeArrangements(n int) int { + x := prefixPrime[n] + y := n - x + proX := 1 + proY := 1 + + for i := 2; i <= x; i++ { + proX = (proX * i) % MOD + } + for i := 2; i <= y; i++ { + proY = (proY * i) % MOD + } + + return (proX * proY) % MOD +} diff --git a/tests/1001-1500/1175. prime-arrangements/sol.java b/tests/1001-1500/1175. prime-arrangements/sol.java new file mode 100644 index 00000000..1303b7a2 --- /dev/null +++ b/tests/1001-1500/1175. prime-arrangements/sol.java @@ -0,0 +1,37 @@ +class Solution { + private static final int MOD = 1000000007; + private static boolean[] isPrime = new boolean[101]; + private static int[] prefixPrime = new int[101]; + + static { + for (int i = 2; i <= 100; i++) { + isPrime[i] = true; + } + for (int i = 2; i * i <= 100; i++) { + if (isPrime[i]) { + for (int j = i * i; j <= 100; j += i) { + isPrime[j] = false; + } + } + } + for (int i = 2; i <= 100; i++) { + prefixPrime[i] = prefixPrime[i - 1] + (isPrime[i] ? 1 : 0); + } + } + + public int numPrimeArrangements(int n) { + int x = prefixPrime[n]; + int y = n - x; + long proX = 1; + long proY = 1; + + for (int i = 2; i <= x; i++) { + proX = (proX * i) % MOD; + } + for (int i = 2; i <= y; i++) { + proY = (proY * i) % MOD; + } + + return (int)((proX * proY) % MOD); + } +} diff --git a/tests/1001-1500/1175. prime-arrangements/sol.kt b/tests/1001-1500/1175. prime-arrangements/sol.kt new file mode 100644 index 00000000..56236a06 --- /dev/null +++ b/tests/1001-1500/1175. prime-arrangements/sol.kt @@ -0,0 +1,38 @@ +class Solution { + companion object { + private const val MOD = 1000000007L + private val isPrime = BooleanArray(101) { true } + private val prefixPrime = IntArray(101) + + init { + isPrime[0] = false + isPrime[1] = false + for (i in 2..100) { + if (i * i <= 100 && isPrime[i]) { + for (j in i * i..100 step i) { + isPrime[j] = false + } + } + } + for (i in 2..100) { + prefixPrime[i] = prefixPrime[i - 1] + (if (isPrime[i]) 1 else 0) + } + } + } + + fun numPrimeArrangements(n: Int): Int { + val x = prefixPrime[n] + val y = n - x + var proX = 1L + var proY = 1L + + for (i in 2..x) { + proX = (proX * i) % MOD + } + for (i in 2..y) { + proY = (proY * i) % MOD + } + + return ((proX * proY) % MOD).toInt() + } +} diff --git a/tests/1001-1500/1175. prime-arrangements/sol.py b/tests/1001-1500/1175. prime-arrangements/sol.py new file mode 100644 index 00000000..c7baadeb --- /dev/null +++ b/tests/1001-1500/1175. prime-arrangements/sol.py @@ -0,0 +1,32 @@ +class Solution: + MOD = 10**9 + 7 + + def sieve(): + prime = [False, False] + [True] * 99 + for i in range(2, int(100**0.5) + 1): + if prime[i]: + for j in range(i * i, 101, i): + prime[j] = False + return prime + + def build_prefix(prime): + prefix = [0] * 101 + for i in range(2, 101): + prefix[i] = prefix[i - 1] + (1 if prime[i] else 0) + return prefix + + is_prime = sieve() + prefix_prime = build_prefix(is_prime) + + @staticmethod + def numPrimeArrangements(n): + x = Solution.prefix_prime[n] + y = n - x + proX = proY = 1 + + for i in range(2, x + 1): + proX = (proX * i) % Solution.MOD + for i in range(2, y + 1): + proY = (proY * i) % Solution.MOD + + return (proX * proY) % Solution.MOD diff --git a/tests/1001-1500/1175. prime-arrangements/sol.py2 b/tests/1001-1500/1175. prime-arrangements/sol.py2 new file mode 100644 index 00000000..87828e11 --- /dev/null +++ b/tests/1001-1500/1175. prime-arrangements/sol.py2 @@ -0,0 +1,24 @@ +class Solution(object): + MOD = 10**9 + 7 + + _is_prime = [False, False] + [True] * 99 + for i in range(2, int(100**0.5) + 1): + if _is_prime[i]: + for j in range(i * i, 101, i): + _is_prime[j] = False + + _prefix_prime = [0] * 101 + for i in range(2, 101): + _prefix_prime[i] = _prefix_prime[i - 1] + (1 if _is_prime[i] else 0) + + def numPrimeArrangements(self, n): + x = Solution._prefix_prime[n] + y = n - x + proX = proY = 1 + + for i in range(2, x + 1): + proX = (proX * i) % Solution.MOD + for i in range(2, y + 1): + proY = (proY * i) % Solution.MOD + + return (proX * proY) % Solution.MOD diff --git a/tests/1001-1500/1175. prime-arrangements/sol.rb b/tests/1001-1500/1175. prime-arrangements/sol.rb new file mode 100644 index 00000000..94d97634 --- /dev/null +++ b/tests/1001-1500/1175. prime-arrangements/sol.rb @@ -0,0 +1,45 @@ +$MOD = 10**9 + 7 + +def sieve + prime = Array.new(101, true) + prime[0] = false + prime[1] = false + (2..Math.sqrt(100).to_i).each do |i| + if prime[i] + (i*i..100).step(i) do |j| + prime[j] = false + end + end + end + prime +end + +def build_prefix(prime) + prefix = Array.new(101, 0) + (2..100).each do |i| + prefix[i] = prefix[i-1] + (prime[i] ? 1 : 0) + end + prefix +end + +$is_prime = sieve +$prefix_prime = build_prefix($is_prime) + +# @param {Integer} n +# @return {Integer} +def num_prime_arrangements(n) + x = $prefix_prime[n] + y = n - x + pro_x = 1 + pro_y = 1 + + (2..x).each do |i| + pro_x = (pro_x * i) % $MOD + end + + (2..y).each do |i| + pro_y = (pro_y * i) % $MOD + end + + (pro_x * pro_y) % $MOD +end diff --git a/tests/1001-1500/1175. prime-arrangements/sol.rs b/tests/1001-1500/1175. prime-arrangements/sol.rs new file mode 100644 index 00000000..dc45c16b --- /dev/null +++ b/tests/1001-1500/1175. prime-arrangements/sol.rs @@ -0,0 +1,42 @@ +impl Solution { + pub fn num_prime_arrangements(n: i32) -> i32 { + const MOD: i64 = 1_000_000_007; + + let n = n as usize; + let mut is_prime = vec![true; 101]; + is_prime[0] = false; + is_prime[1] = false; + + for i in 2..=100 { + if i * i > 100 { + break; + } + if is_prime[i] { + let mut j = i * i; + while j <= 100 { + is_prime[j] = false; + j += i; + } + } + } + + let mut prefix_prime = vec![0; 101]; + for i in 2..=100 { + prefix_prime[i] = prefix_prime[i - 1] + if is_prime[i] { 1 } else { 0 }; + } + + let x = prefix_prime[n]; + let y = n - x; + let mut pro_x: i64 = 1; + let mut pro_y: i64 = 1; + + for i in 2..=x { + pro_x = (pro_x * i as i64) % MOD; + } + for i in 2..=y { + pro_y = (pro_y * i as i64) % MOD; + } + + ((pro_x * pro_y) % MOD) as i32 + } +} diff --git a/tests/1001-1500/1175. prime-arrangements/sol.swift b/tests/1001-1500/1175. prime-arrangements/sol.swift new file mode 100644 index 00000000..d2df4542 --- /dev/null +++ b/tests/1001-1500/1175. prime-arrangements/sol.swift @@ -0,0 +1,52 @@ +class Solution { + private static let MOD = 1000000007 + private static var isPrime: [Bool] = [] + private static var prefixPrime: [Int] = [] + private static var initialized = false + + private static func setup() { + if initialized { return } + isPrime = Array(repeating: true, count: 101) + prefixPrime = Array(repeating: 0, count: 101) + isPrime[0] = false + isPrime[1] = false + + var i = 2 + while i * i <= 100 { + if isPrime[i] { + var j = i * i + while j <= 100 { + isPrime[j] = false + j += i + } + } + i += 1 + } + + for i in 2...100 { + prefixPrime[i] = prefixPrime[i - 1] + (isPrime[i] ? 1 : 0) + } + initialized = true + } + + func numPrimeArrangements(_ n: Int) -> Int { + Solution.setup() + let x = Solution.prefixPrime[n] + let y = n - x + var proX = 1 + var proY = 1 + + if x >= 2 { + for i in 2...x { + proX = (proX * i) % Solution.MOD + } + } + if y >= 2 { + for i in 2...y { + proY = (proY * i) % Solution.MOD + } + } + + return (proX * proY) % Solution.MOD + } +} diff --git a/tests/1001-1500/1175. prime-arrangements/sol.ts b/tests/1001-1500/1175. prime-arrangements/sol.ts new file mode 100644 index 00000000..9d1ea9eb --- /dev/null +++ b/tests/1001-1500/1175. prime-arrangements/sol.ts @@ -0,0 +1,32 @@ +const MOD = 1000000007n; +const isPrime: boolean[] = new Array(101).fill(true); +const prefixPrime: number[] = new Array(101).fill(0); + +isPrime[0] = false; +isPrime[1] = false; +for (let i = 2; i * i <= 100; i++) { + if (isPrime[i]) { + for (let j = i * i; j <= 100; j += i) { + isPrime[j] = false; + } + } +} +for (let i = 2; i <= 100; i++) { + prefixPrime[i] = prefixPrime[i - 1] + (isPrime[i] ? 1 : 0); +} + +function numPrimeArrangements(n: number): number { + const x = prefixPrime[n]; + const y = n - x; + let proX = 1n; + let proY = 1n; + + for (let i = 2; i <= x; i++) { + proX = (proX * BigInt(i)) % MOD; + } + for (let i = 2; i <= y; i++) { + proY = (proY * BigInt(i)) % MOD; + } + + return Number((proX * proY) % MOD); +} diff --git a/tests/1001-1500/1177. can-make-palindrome-from-substring/manifest.yaml b/tests/1001-1500/1177. can-make-palindrome-from-substring/manifest.yaml new file mode 100644 index 00000000..8d69ea70 --- /dev/null +++ b/tests/1001-1500/1177. can-make-palindrome-from-substring/manifest.yaml @@ -0,0 +1,504 @@ +entry: + id: 1177 + title: "can-make-palindrome-from-substring" + params: + s: + type: string + queries: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().canMakePaliQueries({s}, {queries})" + rust: "Solution::can_make_pali_queries({s}, {queries})" + python3: "Solution().canMakePaliQueries({s}, {queries})" + python2: "Solution().canMakePaliQueries({s}, {queries})" + ruby: "can_make_pali_queries({s}, {queries})" + java: "new Solution().canMakePaliQueries({s}, {queries})" + csharp: "new Solution().CanMakePaliQueries({s}, {queries})" + kotlin: "Solution().canMakePaliQueries({s}, {queries})" + go: "canMakePaliQueries({s}, {queries})" + dart: "Solution().canMakePaliQueries({s}, {queries})" + swift: "Solution().canMakePaliQueries({s}, {queries})" + typescript: "canMakePaliQueries({s}, {queries})" + +judge: + type: "exact" + +limits: + time_ms: 700 + memory_mb: 300 + +oracle: + python3: + call: "Checker().canMakePaliQueries(s, queries, {result})" + checker: | + class Checker: + def canMakePaliQueries(self, s, queries, result): + if not isinstance(result, list) or len(result) != len(queries): + return False + expected = [] + for query in queries: + if not isinstance(query, list) or len(query) != 3: + return False + left, right, k = query + if left < 0 or right >= len(s) or left > right or k < 0: + return False + counts = [0] * 26 + for ch in s[left:right + 1]: + counts[ord(ch) - ord('a')] += 1 + odd = sum(count % 2 for count in counts) + expected.append(odd // 2 <= k) + return result == expected + +seed: 117700 + +tests: + - name: "example_one" + in: + s: "abcda" + queries: + elemType: "int" + value: + - [3, 3, 0] + - [1, 2, 0] + - [0, 3, 1] + - [0, 3, 2] + - [0, 4, 1] + out: [true, false, false, true, true] + - name: "example_two" + in: + s: "lyb" + queries: + elemType: "int" + value: + - [0, 1, 0] + - [2, 2, 1] + out: [false, true] + - name: "single_character" + in: + s: "a" + queries: + elemType: "int" + value: + - [0, 0, 0] + out: [true] + - name: "two_equal" + in: + s: "aa" + queries: + elemType: "int" + value: + - [0, 1, 0] + - [0, 0, 0] + out: [true, true] + - name: "two_different_thresholds" + in: + s: "ab" + queries: + elemType: "int" + value: + - [0, 1, 0] + - [0, 1, 1] + out: [false, true] + - name: "all_same" + in: + s: "aaaaaa" + queries: + elemType: "int" + value: + - [0, 5, 0] + - [1, 4, 0] + - [2, 2, 0] + out: [true, true, true] + - name: "all_distinct" + in: + s: "abcdef" + queries: + elemType: "int" + value: + - [0, 5, 0] + - [0, 5, 2] + - [1, 4, 2] + - [2, 3, 1] + out: [false, false, true, true] + - name: "odd_count_one" + in: + s: "aab" + queries: + elemType: "int" + value: + - [0, 2, 0] + - [0, 2, 1] + out: [true, true] + - name: "odd_count_three" + in: + s: "abc" + queries: + elemType: "int" + value: + - [0, 2, 0] + - [0, 2, 1] + out: [false, true] + - name: "alternating" + in: + s: "abababab" + queries: + elemType: "int" + value: + - [0, 7, 0] + - [0, 6, 0] + - [1, 6, 1] + - [2, 5, 0] + out: [true, true, true, true] + - name: "palindrome_substrings" + in: + s: "racecar" + queries: + elemType: "int" + value: + - [0, 6, 0] + - [1, 5, 0] + - [0, 5, 1] + - [2, 4, 0] + out: [true, true, true, true] + - name: "mixed_repeated" + in: + s: "aabbccddeeff" + queries: + elemType: "int" + value: + - [0, 11, 0] + - [0, 10, 0] + - [1, 10, 2] + - [3, 8, 1] + out: [true, true, true, true] + - name: "range_boundaries" + in: + s: "xyzxyz" + queries: + elemType: "int" + value: + - [0, 0, 0] + - [5, 5, 0] + - [0, 1, 1] + - [4, 5, 0] + out: [true, true, true, false] + - name: "nested_ranges" + in: + s: "abacabadabacaba" + queries: + elemType: "int" + value: + - [0, 14, 0] + - [0, 14, 2] + - [1, 13, 1] + - [4, 10, 1] + - [5, 9, 0] + out: [true, true, true, true, true] + - name: "k_zero_focus" + in: + s: "aabbc" + queries: + elemType: "int" + value: + - [0, 1, 0] + - [0, 3, 0] + - [0, 4, 0] + - [2, 4, 0] + out: [true, true, true, true] + - name: "large_k_focus" + in: + s: "abcdefghij" + queries: + elemType: "int" + value: + - [0, 9, 5] + - [0, 8, 4] + - [1, 7, 3] + - [2, 6, 2] + out: [true, true, true, true] + - name: "overlapping_queries" + in: + s: "mississippi" + queries: + elemType: "int" + value: + - [0, 10, 0] + - [1, 9, 1] + - [2, 8, 0] + - [3, 7, 1] + - [4, 6, 0] + out: [true, true, true, true, true] + - name: "near_palindrome" + in: + s: "abccbx" + queries: + elemType: "int" + value: + - [0, 4, 0] + - [0, 5, 0] + - [0, 5, 1] + - [1, 4, 0] + out: [true, false, true, true] + - name: "disjoint_alphabet" + in: + s: "mnopqr" + queries: + elemType: "int" + value: + - [0, 2, 1] + - [3, 5, 1] + - [0, 5, 2] + out: [true, true, false] + - name: "repeated_triplets" + in: + s: "aaabbbccc" + queries: + elemType: "int" + value: + - [0, 8, 0] + - [0, 5, 1] + - [2, 6, 1] + - [3, 8, 1] + out: [false, true, true, true] + - name: "even_odd_windows" + in: + s: "abcdefghijk" + queries: + elemType: "int" + value: + - [0, 10, 5] + - [0, 9, 4] + - [1, 9, 4] + - [1, 10, 5] + out: [true, false, true, true] + - name: "palindrome_with_center" + in: + s: "abbac" + queries: + elemType: "int" + value: + - [0, 3, 0] + - [0, 4, 0] + - [1, 3, 0] + - [1, 4, 1] + out: [true, true, true, true] + - name: "many_singletons" + in: + s: "qwerty" + queries: + elemType: "int" + value: + - [0, 0, 0] + - [1, 1, 0] + - [2, 2, 0] + - [3, 3, 0] + - [4, 4, 0] + - [5, 5, 0] + out: [true, true, true, true, true, true] + - name: "edge_k_equals_length" + in: + s: "abcdefg" + queries: + elemType: "int" + value: + - [0, 6, 7] + - [2, 5, 4] + out: [true, true] + - name: "two_pairs_and_single" + in: + s: "aabbcdd" + queries: + elemType: "int" + value: + - [0, 6, 0] + - [0, 4, 1] + - [2, 6, 1] + - [4, 4, 0] + out: [true, true, true, true] + - name: "mirror_pattern" + in: + s: "abccbaabccba" + queries: + elemType: "int" + value: + - [0, 5, 0] + - [6, 11, 0] + - [0, 11, 0] + - [2, 9, 1] + out: [true, true, true, true] + - name: "different_case_lengths" + in: + s: "zzxyzzxy" + queries: + elemType: "int" + value: + - [0, 7, 0] + - [0, 3, 0] + - [2, 5, 0] + - [1, 6, 1] + out: [true, false, false, true] + - name: "threshold_exact_half" + in: + s: "abcdabcd" + queries: + elemType: "int" + value: + - [0, 7, 2] + - [0, 7, 1] + - [0, 5, 1] + - [2, 7, 2] + out: [true, true, true, true] + - name: "long_repetition" + in: + s: "abcabcabcabcabcabc" + queries: + elemType: "int" + value: + - [0, 17, 5] + - [0, 17, 6] + - [1, 16, 4] + - [3, 14, 3] + out: [true, true, true, true] + - name: "alternating_three_letters" + in: + s: "abcabcabc" + queries: + elemType: "int" + value: + - [0, 8, 1] + - [0, 7, 1] + - [1, 8, 1] + - [2, 6, 1] + out: [true, true, true, true] + - name: "almost_all_same" + in: + s: "aaaaabaaaa" + queries: + elemType: "int" + value: + - [0, 9, 0] + - [0, 9, 1] + - [4, 6, 0] + - [0, 4, 0] + out: [false, true, true, true] + - name: "full_alphabet_twice" + in: + s: "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" + queries: + elemType: "int" + value: + - [0, 51, 13] + - [0, 50, 13] + - [1, 26, 12] + - [25, 51, 12] + out: [true, true, false, true] + - name: "full_alphabet_threshold" + in: + s: "abcdefghijklmnopqrstuvwxyz" + queries: + elemType: "int" + value: + - [0, 25, 12] + - [0, 25, 13] + - [0, 24, 12] + - [1, 25, 11] + out: [false, true, true, false] + - name: "paired_alphabet_boundaries" + in: + s: "aabbccddeeffgghhiijjkkllmm" + queries: + elemType: "int" + value: + - [0, 25, 0] + - [1, 24, 0] + - [1, 24, 1] + - [0, 1, 0] + - [24, 25, 0] + out: [true, false, true, true, true] + - name: "stress_full_range_random" + seed: 117701 + in: + s: + gen: "str" + len: 100000 + alphabet: "abcdefghijklmnopqrstuvwxyz" + queries: + elemType: "int" + value: + - [0, 99999, 0] + - [0, 99999, 13] + - [0, 99999, 100000] + - name: "stress_prefix_suffix_random" + seed: 117702 + in: + s: + gen: "str" + len: 100000 + alphabet: "abcdefghijklmnopqrstuvwxyz" + queries: + elemType: "int" + value: + - [0, 0, 0] + - [0, 99998, 12] + - [1, 99999, 12] + - [50000, 99999, 100000] + - name: "stress_middle_windows_random" + seed: 117703 + in: + s: + gen: "str" + len: 100000 + alphabet: "abcdefghijklm" + queries: + elemType: "int" + value: + - [12345, 87654, 0] + - [12345, 87654, 6] + - [49999, 50000, 1] + - [25000, 74999, 100000] + - name: "stress_binary_alphabet_random" + seed: 117704 + in: + s: + gen: "str" + len: 100000 + alphabet: "az" + queries: + elemType: "int" + value: + - [0, 99999, 0] + - [11111, 88888, 0] + - [11111, 88888, 1] + - [99999, 99999, 0] + - name: "stress_skewed_alphabet_random" + seed: 117705 + in: + s: + gen: "str" + len: 100000 + alphabet: "aaaaabcd" + queries: + elemType: "int" + value: + - [0, 99999, 0] + - [1000, 99000, 1] + - [40000, 60000, 2] + - [0, 49999, 100000] + - name: "stress_all_letters_random" + seed: 117706 + in: + s: + gen: "str" + len: 100000 + alphabet: "abcdefghijklmnopqrstuvwxyz" + queries: + elemType: "int" + value: + - [0, 99999, 12] + - [1, 99998, 13] + - [33333, 66666, 13] + - [0, 99999, 100000] diff --git a/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.cpp b/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.cpp new file mode 100644 index 00000000..ba224990 --- /dev/null +++ b/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + vector canMakePaliQueries(string s, vector>& queries) { + int n = s.size(); + vector prefix(n + 1, 0); + + for (int i = 0; i < n; i++) { + int bit = 1 << (s[i] - 'a'); + prefix[i + 1] = prefix[i] ^ bit; + } + + vector res; + + for (auto& query : queries) { + int left = query[0]; + int right = query[1]; + int ki = query[2]; + + int mask = prefix[right + 1] ^ prefix[left]; + int oddCount = __builtin_popcount(mask); + + if (oddCount <= 1 || ki >= oddCount / 2) { + res.push_back(true); + } else { + res.push_back(false); + } + } + + return res; + } +}; diff --git a/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.cs b/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.cs new file mode 100644 index 00000000..f9a803e5 --- /dev/null +++ b/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.cs @@ -0,0 +1,34 @@ +public class Solution { + public IList CanMakePaliQueries(string s, int[][] queries) { + int n = s.Length; + int[] prefix = new int[n + 1]; + + for (int i = 0; i < n; i++) { + int bit = 1 << (s[i] - 'a'); + prefix[i + 1] = prefix[i] ^ bit; + } + + IList res = new List(); + + foreach (var query in queries) { + int left = query[0]; + int right = query[1]; + int ki = query[2]; + + int mask = prefix[right + 1] ^ prefix[left]; + int oddCount = 0; + while (mask != 0) { + oddCount += mask & 1; + mask >>= 1; + } + + if (oddCount <= 1 || ki >= oddCount / 2) { + res.Add(true); + } else { + res.Add(false); + } + } + + return res; + } +} diff --git a/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.dart b/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.dart new file mode 100644 index 00000000..c563fc20 --- /dev/null +++ b/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.dart @@ -0,0 +1,30 @@ +class Solution { + List canMakePaliQueries(String s, List> queries) { + int n = s.length; + List prefix = List.filled(n + 1, 0); + + for (int i = 0; i < n; i++) { + int bit = 1 << (s.codeUnitAt(i) - 'a'.codeUnitAt(0)); + prefix[i + 1] = prefix[i] ^ bit; + } + + List res = []; + + for (var query in queries) { + int left = query[0]; + int right = query[1]; + int ki = query[2]; + + int mask = prefix[right + 1] ^ prefix[left]; + int oddCount = mask.toRadixString(2).split('').where((c) => c == '1').length; + + if (oddCount <= 1 || ki >= oddCount ~/ 2) { + res.add(true); + } else { + res.add(false); + } + } + + return res; + } +} diff --git a/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.go b/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.go new file mode 100644 index 00000000..1270444e --- /dev/null +++ b/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.go @@ -0,0 +1,32 @@ +func canMakePaliQueries(s string, queries [][]int) []bool { + n := len(s) + prefix := make([]int, n+1) + + for i := 0; i < n; i++ { + bit := 1 << (s[i] - 'a') + prefix[i+1] = prefix[i] ^ bit + } + + res := make([]bool, len(queries)) + + for idx, query := range queries { + left := query[0] + right := query[1] + ki := query[2] + + mask := prefix[right+1] ^ prefix[left] + oddCount := 0 + for mask > 0 { + oddCount += mask & 1 + mask >>= 1 + } + + if oddCount <= 1 || ki >= oddCount/2 { + res[idx] = true + } else { + res[idx] = false + } + } + + return res +} diff --git a/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.java b/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.java new file mode 100644 index 00000000..72cbcdd5 --- /dev/null +++ b/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.java @@ -0,0 +1,30 @@ +class Solution { + public List canMakePaliQueries(String s, int[][] queries) { + int n = s.length(); + int[] prefix = new int[n + 1]; + + for (int i = 0; i < n; i++) { + int bit = 1 << (s.charAt(i) - 'a'); + prefix[i + 1] = prefix[i] ^ bit; + } + + List res = new ArrayList<>(); + + for (int[] query : queries) { + int left = query[0]; + int right = query[1]; + int ki = query[2]; + + int mask = prefix[right + 1] ^ prefix[left]; + int oddCount = Integer.bitCount(mask); + + if (oddCount <= 1 || ki >= oddCount / 2) { + res.add(true); + } else { + res.add(false); + } + } + + return res; + } +} diff --git a/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.kt b/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.kt new file mode 100644 index 00000000..696105e0 --- /dev/null +++ b/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.kt @@ -0,0 +1,26 @@ +class Solution { + fun canMakePaliQueries(s: String, queries: Array): List { + val n = s.length + val prefix = IntArray(n + 1) + + for (i in 0 until n) { + val bit = 1 shl (s[i] - 'a') + prefix[i + 1] = prefix[i] xor bit + } + + val res = mutableListOf() + + for ((left, right, ki) in queries) { + val mask = prefix[right + 1] xor prefix[left] + val oddCount = Integer.bitCount(mask) + + if (oddCount <= 1 || ki >= oddCount / 2) { + res.add(true) + } else { + res.add(false) + } + } + + return res + } +} diff --git a/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.py b/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.py new file mode 100644 index 00000000..af4227aa --- /dev/null +++ b/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.py @@ -0,0 +1,21 @@ +class Solution: + def canMakePaliQueries(self, s: str, queries: List[List[int]]) -> List[bool]: + n = len(s) + prefix = [0] * (n + 1) + + for i in range(n): + bit = 1 << (ord(s[i]) - ord("a")) + prefix[i + 1] = prefix[i] ^ bit + + res = [] + + for left, right, ki in queries: + mask = prefix[right + 1] ^ prefix[left] + odd_count = bin(mask).count("1") + + if odd_count <= 1 or ki >= odd_count // 2: + res.append(True) + else: + res.append(False) + + return res diff --git a/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.py2 b/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.py2 new file mode 100644 index 00000000..b4b42733 --- /dev/null +++ b/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.py2 @@ -0,0 +1,26 @@ +class Solution(object): + def canMakePaliQueries(self, s, queries): + """ + :type s: str + :type queries: List[List[int]] + :rtype: List[bool] + """ + n = len(s) + prefix = [0] * (n + 1) + + for i in range(n): + bit = 1 << (ord(s[i]) - ord('a')) + prefix[i + 1] = prefix[i] ^ bit + + res = [] + + for left, right, ki in queries: + mask = prefix[right + 1] ^ prefix[left] + odd_count = bin(mask).count('1') + + if odd_count <= 1 or ki >= odd_count // 2: + res.append(True) + else: + res.append(False) + + return res diff --git a/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.rb b/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.rb new file mode 100644 index 00000000..058f9896 --- /dev/null +++ b/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.rb @@ -0,0 +1,27 @@ +# @param {String} s +# @param {Integer[][]} queries +# @return {Boolean[]} +def can_make_pali_queries(s, queries) + n = s.length + prefix = Array.new(n + 1, 0) + + (0...n).each do |i| + bit = 1 << (s[i].ord - 'a'.ord) + prefix[i + 1] = prefix[i] ^ bit + end + + res = [] + + queries.each do |left, right, ki| + mask = prefix[right + 1] ^ prefix[left] + odd_count = mask.to_s(2).count('1') + + if odd_count <= 1 || ki >= odd_count / 2 + res << true + else + res << false + end + end + + res +end diff --git a/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.rs b/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.rs new file mode 100644 index 00000000..ece6434f --- /dev/null +++ b/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.rs @@ -0,0 +1,31 @@ +impl Solution { + pub fn can_make_pali_queries(s: String, queries: Vec>) -> Vec { + let n = s.len(); + let mut prefix: Vec = vec![0; n + 1]; + let s_bytes = s.as_bytes(); + + for i in 0..n { + let bit: u32 = 1 << (s_bytes[i] - b'a'); + prefix[i + 1] = prefix[i] ^ bit; + } + + let mut res = Vec::with_capacity(queries.len()); + + for query in queries { + let left = query[0] as usize; + let right = query[1] as usize; + let ki = query[2]; + + let mask = prefix[right + 1] ^ prefix[left]; + let odd_count = mask.count_ones() as i32; + + if odd_count <= 1 || ki >= odd_count / 2 { + res.push(true); + } else { + res.push(false); + } + } + + res + } +} diff --git a/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.swift b/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.swift new file mode 100644 index 00000000..b12e0d07 --- /dev/null +++ b/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.swift @@ -0,0 +1,31 @@ +class Solution { + func canMakePaliQueries(_ s: String, _ queries: [[Int]]) -> [Bool] { + let n = s.count + var prefix = [Int](repeating: 0, count: n + 1) + let chars = Array(s) + + for i in 0..= oddCount / 2 { + res.append(true) + } else { + res.append(false) + } + } + + return res + } +} diff --git a/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.ts b/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.ts new file mode 100644 index 00000000..8afbc78f --- /dev/null +++ b/tests/1001-1500/1177. can-make-palindrome-from-substring/sol.ts @@ -0,0 +1,24 @@ +function canMakePaliQueries(s: string, queries: number[][]): boolean[] { + const n = s.length; + const prefix: number[] = new Array(n + 1).fill(0); + + for (let i = 0; i < n; i++) { + const bit = 1 << (s.charCodeAt(i) - "a".charCodeAt(0)); + prefix[i + 1] = prefix[i] ^ bit; + } + + const res: boolean[] = []; + + for (const [left, right, ki] of queries) { + const mask = prefix[right + 1] ^ prefix[left]; + const oddCount = mask.toString(2).split("0").join("").length; + + if (oddCount <= 1 || ki >= Math.floor(oddCount / 2)) { + res.push(true); + } else { + res.push(false); + } + } + + return res; +} diff --git a/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/manifest.yaml b/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/manifest.yaml new file mode 100644 index 00000000..8d562c06 --- /dev/null +++ b/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/manifest.yaml @@ -0,0 +1,330 @@ +entry: + id: 1178 + title: "number-of-valid-words-for-each-puzzle" + params: + words: + type: array + items: + type: string + puzzles: + type: array + items: + type: string + call: + cpp: "Solution().findNumOfValidWords({words}, {puzzles})" + rust: "Solution::find_num_of_valid_words({words}, {puzzles})" + python3: "Solution().findNumOfValidWords({words}, {puzzles})" + python2: "Solution().findNumOfValidWords({words}, {puzzles})" + ruby: "find_num_of_valid_words({words}, {puzzles})" + java: "new Solution().findNumOfValidWords({words}, {puzzles})" + csharp: "new Solution().FindNumOfValidWords({words}, {puzzles})" + kotlin: "Solution().findNumOfValidWords({words}, {puzzles})" + go: "findNumOfValidWords({words}, {puzzles})" + dart: "Solution().findNumOfValidWords({words}, {puzzles})" + swift: "Solution().findNumOfValidWords({words}, {puzzles})" + typescript: "findNumOfValidWords({words}, {puzzles})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().findNumOfValidWords(words, puzzles, {result})" + checker: | + class Checker: + def findNumOfValidWords(self, words, puzzles, result): + expected = [] + for puzzle in puzzles: + allowed = set(puzzle) + first = puzzle[0] + expected.append(sum( + first in word and set(word) <= allowed + for word in words + )) + return result == expected + +seed: 1178 + +tests: + - name: "example-one" + in: + words: ["aaaa", "asas", "able", "ability", "actt", "actor", "access"] + puzzles: + ["aboveyz", "abrodyz", "abslute", "absoryz", "actresz", "gaswxyz"] + out: [1, 1, 3, 2, 4, 0] + - name: "example-two" + in: + words: ["apple", "pleas", "please"] + puzzles: ["aelwxyz", "aelpxyz", "aelpsxy", "saelpxy", "xaelpsy"] + out: [0, 1, 3, 2, 0] + - name: "one-word-match" + in: + words: ["abcd"] + puzzles: ["abcdefg"] + out: [1] + - name: "one-word-missing-first" + in: + words: ["bcde"] + puzzles: ["abcdefg"] + out: [0] + - name: "one-word-extra-letter" + in: + words: ["abcx"] + puzzles: ["abcdefg"] + out: [0] + - name: "first-letter-varies" + in: + words: ["abcd", "bcde", "cdef", "defg"] + puzzles: ["abcdefg", "bcdefgh", "cdefghi", "defghij"] + out: [1, 1, 1, 1] + - name: "repeated-word-counts" + in: + words: ["aaaa", "aaaa", "aaaa", "aaab"] + puzzles: ["abcdefg", "bacdefg"] + out: [4, 1] + - name: "repeated-word-letters" + in: + words: ["aabbcc", "abcabc", "abccdd", "bbbb"] + puzzles: ["abcdefg", "bcdefgh"] + out: [3, 1] + - name: "no-valid-words" + in: + words: ["hijk", "ijkl", "mnop", "qrst"] + puzzles: ["abcdefg", "bcdefgh"] + out: [0, 0] + - name: "all-valid-subsets" + in: + words: ["abcde", "abcf", "acdg", "efg", "abcdefg"] + puzzles: ["abcdefg"] + out: [4] + - name: "single-puzzle-many-words" + in: + words: ["face", "cafe", "fade", "bead", "bag", "gaga", "hace"] + puzzles: ["abcdefg"] + out: [6] + - name: "different-first-letters" + in: + words: ["abcd", "bcda", "cdef", "defg", "efga"] + puzzles: ["abcdefg", "bcdefga", "cdefgab", "defgabc"] + out: [3, 2, 3, 4] + - name: "minimum-word-length" + in: + words: ["abcd", "efgh", "ijkl", "mnop"] + puzzles: ["abcdefg", "efghabc"] + out: [1, 1] + - name: "maximum-word-length" + in: + words: + [ + "abcdefghijklmnopqrstuvwxyz", + "abcdefghijklmnopqrstuvwxy", + "bcdefghijklmnopqrstuvwx", + ] + puzzles: ["abcdefg", "tuvwxyz", "bcdefgh"] + out: [0, 0, 0] + - name: "same-letter-set-different-order" + in: + words: ["face", "ecaf", "cafe", "abcd"] + puzzles: ["abcdefg", "bcdefga"] + out: [4, 1] + - name: "first-letter-required" + in: + words: ["bcde", "cdef", "defg", "efga"] + puzzles: ["abcdefg", "bcdefga", "cdefgab", "defgabc"] + out: [1, 1, 2, 3] + - name: "extra-character-rejection" + in: + words: ["abcde", "abcdefh", "abcdefg", "abcfgh"] + puzzles: ["abcdefg"] + out: [2] + - name: "overlapping-puzzles" + in: + words: ["abcd", "abef", "acfg", "bcde", "cdefg"] + puzzles: ["abcdefg", "abchijk", "bcdefgh"] + out: [3, 0, 1] + - name: "disjoint-puzzles" + in: + words: ["abcd", "efgh", "ijkl", "mnop", "qrstuv"] + puzzles: ["abcdefg", "hijklmn", "opqrstu"] + out: [1, 0, 0] + - name: "duplicate-character-heavy" + in: + words: ["aaaaab", "bbbbbc", "cccccd", "ddddde", "fffffg"] + puzzles: ["abcdefg", "bcdefgh", "cdefghi"] + out: [1, 1, 1] + - name: "all-first-letter-present" + in: + words: ["aabb", "aacc", "aadd", "aaee", "aaff", "aagg"] + puzzles: ["abcdefg"] + out: [6] + - name: "rotated-alphabet" + in: + words: ["wxyz", "xyza", "yzab", "zabc", "abcd"] + puzzles: ["wxyzabc", "xyzabcd", "yzabcde", "zabcdef", "abcdefg"] + out: [1, 1, 1, 1, 1] + - name: "short-subsets" + in: + words: ["abcd", "abce", "abcf", "abcg", "abch"] + puzzles: ["abcdefg", "bcdefgh"] + out: [4, 0] + - name: "late-first-letter" + in: + words: ["tuvw", "tuvx", "tuwy", "txyz", "uvwx"] + puzzles: ["tuvwxyz", "uvwxyzab", "vwxyzab"] + out: [4, 1, 0] + - name: "word-per-puzzle" + in: + words: ["abcd", "efgh", "ijkl", "mnop", "qrst", "uvwx"] + puzzles: + ["abcdefg", "efghabc", "ijklmno", "mnopqrs", "qrstuvw", "uvwxyzab"] + out: [1, 1, 1, 1, 1, 1] + - name: "near-complete-sets" + in: + words: ["abcdef", "bcdefg", "cdefgh", "defghi", "efghij"] + puzzles: ["abcdefg", "bcdefgh", "cdefghi", "defghij"] + out: [1, 1, 1, 1] + - name: "many-invalid" + in: + words: ["abch", "abci", "abcj", "abck", "abcl", "abcm", "abcd"] + puzzles: ["abcdefg"] + out: [1] + - name: "palindromic-words" + in: + words: ["abcba", "abccba", "abcdcba", "abddba"] + puzzles: ["abcdefg", "bcdefga"] + out: [4, 4] + - name: "puzzle-order-output" + in: + words: ["abcd", "bcde", "cdef", "defg"] + puzzles: ["defgabc", "abcdefg", "cdefgab", "bcdefga"] + out: [4, 1, 3, 2] + - name: "large-static-word-list" + in: + words: + [ + "aaaa", + "aaab", + "aabb", + "abbb", + "bbbb", + "bbbc", + "bbcc", + "bccc", + "cccc", + "cccd", + "ccdd", + "cddd", + "dddd", + "ddde", + "ddee", + "deee", + "eeee", + ] + puzzles: ["abcdefg", "bcdefgh", "cdefghi", "defghij"] + out: [4, 4, 4, 4] + - name: "alphabet-boundary" + in: + words: ["wxyz", "xyza", "yzab", "zabc", "azzz", "zzzz"] + puzzles: ["wxyzabc", "xyzabcd", "yzabcde", "zabcdef"] + out: [1, 1, 1, 3] + - name: "seven-letter-combinations" + in: + words: ["abde", "acdf", "bceg", "defg", "aefg", "abcd", "bcfg"] + puzzles: ["abcdefg", "bcdefgh", "cdefgab"] + out: [4, 2, 4] + - name: "all-word-sets-fit" + in: + words: ["abcd", "abce", "abcf", "abde", "abdf", "abef"] + puzzles: ["abcdefg", "abcdefg"] + out: [6, 6] + - name: "first-letter-only-failure" + in: + words: ["bcde", "cdef", "defg", "efgh", "fgab"] + puzzles: ["abcdefg", "bcdefga", "cdefgab", "defgabc", "efgabcd"] + out: [1, 2, 2, 3, 3] + - name: "first-letter-present-but-extra" + in: + words: ["axxx", "abch", "abcd", "aefg"] + puzzles: ["abcdefg"] + out: [2] + - name: "fifty-character-words" + in: + words: + [ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde", + "abcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefg", + "bcdefgbcdefgbcdefgbcdefgbcdefgbcdefgbcdefgbcdefg", + ] + puzzles: ["abcdefg", "bcdefgh"] + out: [3, 1] + - name: "duplicate-mask-frequency" + in: + words: + [ + "abca", + "abca", + "abca", + "abca", + "abca", + "abbd", + "abbd", + "abbd", + "abbd", + "bcde", + "bcde", + "bcde", + "acef", + "acef", + "defg", + ] + puzzles: ["abcdefg", "bcdefgh", "cdefgab", "defgabc"] + out: [11, 3, 10, 8] + - name: "dense-seven-letter-subsets" + in: + words: ["abcdefg", "abcdef", "abcefg", "acdefg", "bcdefg", "aaaa"] + puzzles: ["abcdefg", "bcdefgh"] + out: [5, 1] + - name: "alphabet-rotation-corpus" + in: + words: + [ + "abcd", + "bcde", + "cdef", + "defg", + "efgh", + "fghi", + "ghij", + "hijk", + "ijkl", + "jklm", + "klmn", + "lmno", + "mnop", + "nopq", + "opqr", + "pqrs", + "qrst", + "rstu", + "stuv", + "tuvw", + "uvwx", + "vwxy", + "wxyz", + "xyza", + "yzab", + "zabc", + ] + puzzles: ["abcdefg", "ghijklm", "tuvwxyz", "zabcdef"] + out: [1, 1, 1, 1] + - name: "repeated-puzzles-preserve-order" + in: + words: ["aaaa", "aaab", "abbb", "bbbb", "bcde", "cdef", "defg", "efga"] + puzzles: + ["abcdefg", "abcdefg", "bcdefgh", "bcdefgh", "cdefgab", "defgabc"] + out: [4, 4, 2, 2, 2, 3] diff --git a/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.cpp b/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.cpp new file mode 100644 index 00000000..0085b83e --- /dev/null +++ b/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + vector findNumOfValidWords(vector& words, vector& puzzles) { + auto getMask = [](const string& s) { + int mask = 0; + for (char c : s) { + mask |= 1 << (c - 'a'); + } + return mask; + }; + + unordered_map wordCount; + for (const string& w : words) { + int mask = getMask(w); + wordCount[mask]++; + } + + vector result; + for (const string& p : puzzles) { + int firstMask = 1 << (p[0] - 'a'); + int puzzleMask = getMask(p); + int sub = puzzleMask; + int count = 0; + while (true) { + if ((sub & firstMask) != 0) { + count += wordCount[sub]; + } + if (sub == 0) break; + sub = (sub - 1) & puzzleMask; + } + result.push_back(count); + } + return result; + } +}; diff --git a/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.cs b/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.cs new file mode 100644 index 00000000..4c73feda --- /dev/null +++ b/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.cs @@ -0,0 +1,38 @@ +public class Solution { + public IList FindNumOfValidWords(string[] words, string[] puzzles) { + int GetMask(string s) { + int mask = 0; + foreach (char c in s) { + mask |= 1 << (c - 'a'); + } + return mask; + } + + Dictionary wordCount = new Dictionary(); + foreach (string w in words) { + int mask = GetMask(w); + if (wordCount.ContainsKey(mask)) { + wordCount[mask]++; + } else { + wordCount[mask] = 1; + } + } + + List result = new List(); + foreach (string p in puzzles) { + int firstMask = 1 << (p[0] - 'a'); + int puzzleMask = GetMask(p); + int sub = puzzleMask; + int count = 0; + while (true) { + if ((sub & firstMask) != 0 && wordCount.ContainsKey(sub)) { + count += wordCount[sub]; + } + if (sub == 0) break; + sub = (sub - 1) & puzzleMask; + } + result.Add(count); + } + return result; + } +} diff --git a/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.dart b/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.dart new file mode 100644 index 00000000..8b03f1eb --- /dev/null +++ b/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.dart @@ -0,0 +1,34 @@ +class Solution { + List findNumOfValidWords(List words, List puzzles) { + int getMask(String s) { + int mask = 0; + for (int i = 0; i < s.length; i++) { + mask |= 1 << (s.codeUnitAt(i) - 97); + } + return mask; + } + + Map wordCount = {}; + for (var w in words) { + int mask = getMask(w); + wordCount[mask] = (wordCount[mask] ?? 0) + 1; + } + + List result = []; + for (var p in puzzles) { + int firstMask = 1 << (p.codeUnitAt(0) - 97); + int puzzleMask = getMask(p); + int sub = puzzleMask; + int count = 0; + while (true) { + if ((sub & firstMask) != 0) { + count += wordCount[sub] ?? 0; + } + if (sub == 0) break; + sub = (sub - 1) & puzzleMask; + } + result.add(count); + } + return result; + } +} diff --git a/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.go b/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.go new file mode 100644 index 00000000..e864d58c --- /dev/null +++ b/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.go @@ -0,0 +1,34 @@ +func findNumOfValidWords(words []string, puzzles []string) []int { + getMask := func(s string) int { + mask := 0 + for _, ch := range s { + mask |= 1 << (ch - 'a') + } + return mask + } + + wordCount := make(map[int]int) + for _, w := range words { + mask := getMask(w) + wordCount[mask]++ + } + + result := make([]int, len(puzzles)) + for i, p := range puzzles { + firstMask := 1 << (p[0] - 'a') + puzzleMask := getMask(p) + sub := puzzleMask + count := 0 + for { + if sub & firstMask != 0 { + count += wordCount[sub] + } + if sub == 0 { + break + } + sub = (sub - 1) & puzzleMask + } + result[i] = count + } + return result +} diff --git a/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.java b/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.java new file mode 100644 index 00000000..b9fa88c4 --- /dev/null +++ b/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.java @@ -0,0 +1,34 @@ +class Solution { + public List findNumOfValidWords(String[] words, String[] puzzles) { + Map wordCount = new HashMap<>(); + for (String w : words) { + int mask = getMask(w); + wordCount.put(mask, wordCount.getOrDefault(mask, 0) + 1); + } + + List result = new ArrayList<>(); + for (String p : puzzles) { + int firstMask = 1 << (p.charAt(0) - 'a'); + int puzzleMask = getMask(p); + int sub = puzzleMask; + int count = 0; + while (true) { + if ((sub & firstMask) != 0) { + count += wordCount.getOrDefault(sub, 0); + } + if (sub == 0) break; + sub = (sub - 1) & puzzleMask; + } + result.add(count); + } + return result; + } + + private int getMask(String s) { + int mask = 0; + for (int i = 0; i < s.length(); i++) { + mask |= 1 << (s.charAt(i) - 'a'); + } + return mask; + } +} diff --git a/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.kt b/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.kt new file mode 100644 index 00000000..19d959d0 --- /dev/null +++ b/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.kt @@ -0,0 +1,34 @@ +class Solution { + fun findNumOfValidWords(words: Array, puzzles: Array): List { + fun getMask(s: String): Int { + var mask = 0 + for (ch in s) { + mask = mask or (1 shl (ch - 'a')) + } + return mask + } + + val wordCount = mutableMapOf() + for (w in words) { + val mask = getMask(w) + wordCount[mask] = (wordCount[mask] ?: 0) + 1 + } + + val result = mutableListOf() + for (p in puzzles) { + val firstMask = 1 shl (p[0] - 'a') + val puzzleMask = getMask(p) + var sub = puzzleMask + var count = 0 + while (true) { + if ((sub and firstMask) != 0) { + count += wordCount[sub] ?: 0 + } + if (sub == 0) break + sub = (sub - 1) and puzzleMask + } + result.add(count) + } + return result + } +} diff --git a/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.py b/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.py new file mode 100644 index 00000000..3540e0fa --- /dev/null +++ b/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.py @@ -0,0 +1,41 @@ +class Solution: + def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]: + words = [sorted(set(w)) for w in words] + puzzles = [(p[0], set(p)) for p in puzzles] + trees = [Trie() for _ in range(26)] + for w in words: + for char in w: + trees[ord(char) - 97].insert(w) + return [trees[ord(f) - 97].puzzle_match(p) for f, p in puzzles] + + +class Node(object): + def __init__(self, val): + self.val = val + self.children = {} + self.tail = 0 + + +class Trie(object): + def __init__(self): + self.root = Node(None) + + def insert(self, word): + curr = self.root + for char in word: + if char not in curr.children: + curr.children[char] = Node(char) + curr = curr.children[char] + curr.tail += 1 + + def puzzle_match(self, puzzle): + def helper(node): + nonlocal res + res += node.tail + for child in node.children: + if child in puzzle: + helper(node.children[child]) + + res = 0 + helper(self.root) + return res diff --git a/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.py2 b/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.py2 new file mode 100644 index 00000000..eb1b59c0 --- /dev/null +++ b/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.py2 @@ -0,0 +1,27 @@ +class Solution(object): + def findNumOfValidWords(self, words, puzzles): + def get_mask(s): + mask = 0 + for ch in s: + mask |= 1 << (ord(ch) - 97) + return mask + + word_count = {} + for w in words: + mask = get_mask(w) + word_count[mask] = word_count.get(mask, 0) + 1 + + res = [] + for p in puzzles: + first_mask = 1 << (ord(p[0]) - 97) + puzzle_mask = get_mask(p) + sub = puzzle_mask + count = 0 + while True: + if sub & first_mask: + count += word_count.get(sub, 0) + if sub == 0: + break + sub = (sub - 1) & puzzle_mask + res.append(count) + return res diff --git a/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.rb b/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.rb new file mode 100644 index 00000000..e121d267 --- /dev/null +++ b/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.rb @@ -0,0 +1,33 @@ +# @param {String[]} words +# @param {String[]} puzzles +# @return {Integer[]} +def find_num_of_valid_words(words, puzzles) + def get_mask(s) + mask = 0 + s.each_byte { |b| mask |= 1 << (b - 97) } + mask + end + + word_count = Hash.new(0) + words.each do |w| + mask = get_mask(w) + word_count[mask] += 1 + end + + result = [] + puzzles.each do |p| + first_mask = 1 << (p[0].ord - 97) + puzzle_mask = get_mask(p) + sub = puzzle_mask + count = 0 + loop do + if sub & first_mask != 0 + count += word_count[sub] + end + break if sub == 0 + sub = (sub - 1) & puzzle_mask + end + result << count + end + result +end diff --git a/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.rs b/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.rs new file mode 100644 index 00000000..e9801cdf --- /dev/null +++ b/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.rs @@ -0,0 +1,36 @@ +impl Solution { + pub fn find_num_of_valid_words(words: Vec, puzzles: Vec) -> Vec { + use std::collections::HashMap; + + fn get_mask(s: &str) -> i32 { + let mut mask = 0i32; + for &b in s.as_bytes() { + mask |= 1 << (b - b'a') as i32; + } + mask + } + + let mut word_count: HashMap = HashMap::new(); + for w in &words { + let mask = get_mask(w); + *word_count.entry(mask).or_insert(0) += 1; + } + + let mut result = Vec::new(); + for p in &puzzles { + let first_mask = 1 << (p.as_bytes()[0] - b'a') as i32; + let puzzle_mask = get_mask(p); + let mut sub = puzzle_mask; + let mut count = 0; + loop { + if (sub & first_mask) != 0 { + count += word_count.get(&sub).unwrap_or(&0); + } + if sub == 0 { break; } + sub = (sub - 1) & puzzle_mask; + } + result.push(count); + } + result + } +} diff --git a/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.swift b/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.swift new file mode 100644 index 00000000..644af10a --- /dev/null +++ b/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.swift @@ -0,0 +1,34 @@ +class Solution { + func findNumOfValidWords(_ words: [String], _ puzzles: [String]) -> [Int] { + func getMask(_ s: String) -> Int { + var mask = 0 + for ch in s { + mask |= 1 << (Int(ch.asciiValue!) - 97) + } + return mask + } + + var wordCount = [Int: Int]() + for w in words { + let mask = getMask(w) + wordCount[mask, default: 0] += 1 + } + + var result = [Int]() + for p in puzzles { + let firstMask = 1 << (Int(p.first!.asciiValue!) - 97) + let puzzleMask = getMask(p) + var sub = puzzleMask + var count = 0 + while true { + if (sub & firstMask) != 0 { + count += wordCount[sub, default: 0] + } + if sub == 0 { break } + sub = (sub - 1) & puzzleMask + } + result.append(count) + } + return result + } +} diff --git a/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.ts b/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.ts new file mode 100644 index 00000000..81055850 --- /dev/null +++ b/tests/1001-1500/1178. number-of-valid-words-for-each-puzzle/sol.ts @@ -0,0 +1,32 @@ +function findNumOfValidWords(words: string[], puzzles: string[]): number[] { + const getMask = (s: string): number => { + let mask = 0; + for (let i = 0; i < s.length; i++) { + mask |= 1 << (s.charCodeAt(i) - 97); + } + return mask; + }; + + const wordCount = new Map(); + for (const w of words) { + const mask = getMask(w); + wordCount.set(mask, (wordCount.get(mask) || 0) + 1); + } + + const result: number[] = []; + for (const p of puzzles) { + const firstMask = 1 << (p.charCodeAt(0) - 97); + const puzzleMask = getMask(p); + let sub = puzzleMask; + let count = 0; + while (true) { + if ((sub & firstMask) !== 0) { + count += wordCount.get(sub) || 0; + } + if (sub === 0) break; + sub = (sub - 1) & puzzleMask; + } + result.push(count); + } + return result; +} diff --git a/tests/1001-1500/1184. distance-between-bus-stops/manifest.yaml b/tests/1001-1500/1184. distance-between-bus-stops/manifest.yaml new file mode 100644 index 00000000..9301a9dc --- /dev/null +++ b/tests/1001-1500/1184. distance-between-bus-stops/manifest.yaml @@ -0,0 +1,355 @@ +entry: + id: 1184 + title: "distance-between-bus-stops" + params: + distance: + type: array + items: + type: int + destination: + type: int + start_value: + type: int + call: + cpp: "Solution().distanceBetweenBusStops({distance}, {start_value}, {destination})" + rust: "Solution::distance_between_bus_stops({distance}, {start_value}, {destination})" + python3: "Solution().distanceBetweenBusStops({distance}, {start_value}, {destination})" + python2: "Solution().distanceBetweenBusStops({distance}, {start_value}, {destination})" + ruby: "distance_between_bus_stops({distance}, {start_value}, {destination})" + java: "new Solution().distanceBetweenBusStops({distance}, {start_value}, {destination})" + csharp: "new Solution().DistanceBetweenBusStops({distance}, {start_value}, {destination})" + kotlin: "Solution().distanceBetweenBusStops({distance}, {start_value}, {destination})" + go: "distanceBetweenBusStops({distance}, {start_value}, {destination})" + dart: "Solution().distanceBetweenBusStops({distance}, {start_value}, {destination})" + swift: "Solution().distanceBetweenBusStops({distance}, {start_value}, {destination})" + typescript: "distanceBetweenBusStops({distance}, {start_value}, {destination})" +judge: + type: exact +limits: + time_ms: 300 + memory_mb: 300 +oracle: + python3: + call: "Checker().distanceBetweenBusStops(distance, start_value, destination, {result})" + checker: | + class Checker: + def distanceBetweenBusStops(self, distance, start_value, destination, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + lo, hi = sorted((start_value, destination)) + direct = sum(distance[lo:hi]) + return result == min(direct, sum(distance) - direct) +seed: 1184 +tests: + - name: example_adjacent + in: + distance: [1, 2, 3, 4] + start_value: 0 + destination: 1 + out: 1 + - name: example_two_edges + in: + distance: [1, 2, 3, 4] + start_value: 0 + destination: 2 + out: 3 + - name: example_wrap_shorter + in: + distance: [1, 2, 3, 4] + start_value: 0 + destination: 3 + out: 4 + - name: minimum_two_stop_zero_edge + in: + distance: [0, 10000] + start_value: 0 + destination: 1 + out: 0 + - name: short_direct_path_in_larger_ring + in: + distance: [3, 1, 4, 1, 5] + start_value: 1 + destination: 3 + out: 5 + - name: all_zero_edges + in: + distance: [0, 0, 0, 0] + start_value: 1 + destination: 3 + out: 0 + - name: zero_on_direct_path + in: + distance: [5, 0, 0, 9] + start_value: 1 + destination: 3 + out: 0 + - name: zero_on_wrap_path + in: + distance: [0, 8, 7, 0] + start_value: 1 + destination: 3 + out: 0 + - name: two_stops_first_direction + in: + distance: [7, 11] + start_value: 0 + destination: 1 + out: 7 + - name: two_stops_reverse_order + in: + distance: [7, 11] + start_value: 1 + destination: 0 + out: 7 + - name: two_stops_equal_routes + in: + distance: [9, 9] + start_value: 0 + destination: 1 + out: 9 + - name: reverse_order_non_adjacent + in: + distance: [3, 1, 4, 1, 5, 9] + start_value: 5 + destination: 1 + out: 11 + - name: forward_non_adjacent + in: + distance: [3, 1, 4, 1, 5, 9] + start_value: 1 + destination: 5 + out: 11 + - name: adjacent_direct_is_longer + in: + distance: [100, 1, 1, 1] + start_value: 0 + destination: 1 + out: 3 + - name: last_to_first_uses_wrap_edge + in: + distance: [6, 7, 8, 2] + start_value: 3 + destination: 0 + out: 2 + - name: endpoint_pair_uses_wrap + in: + distance: [9, 8, 7, 6, 5, 4] + start_value: 0 + destination: 5 + out: 4 + - name: equal_half_circle + in: + distance: [2, 2, 2, 2] + start_value: 0 + destination: 2 + out: 4 + - name: odd_uniform_ring + in: + distance: [1, 1, 1, 1, 1, 1, 1] + start_value: 1 + destination: 4 + out: 3 + - name: alternating_weights_direct + in: + distance: [1, 50, 2, 50, 3] + start_value: 1 + destination: 4 + out: 4 + - name: alternating_weights_wrap + in: + distance: [1, 50, 2, 50, 3] + start_value: 0 + destination: 3 + out: 53 + - name: high_values_direct + in: + distance: [10000, 10000, 1, 10000] + start_value: 0 + destination: 2 + out: 10001 + - name: high_values_wrap + in: + distance: [10000, 1, 10000, 1, 10000] + start_value: 1 + destination: 4 + out: 10002 + - name: direct_path_one_edge + in: + distance: [9, 8, 7, 6, 5, 4] + start_value: 2 + destination: 3 + out: 7 + - name: direct_path_three_edges + in: + distance: [5, 10, 15, 20, 25, 30] + start_value: 1 + destination: 4 + out: 45 + - name: wrap_path_three_edges + in: + distance: [5, 10, 15, 20, 25, 30] + start_value: 2 + destination: 5 + out: 45 + - name: asymmetric_reverse_order + in: + distance: [7, 3, 8, 2, 6, 4, 5] + start_value: 6 + destination: 2 + out: 15 + - name: asymmetric_forward_order + in: + distance: [7, 3, 8, 2, 6, 4, 5] + start_value: 2 + destination: 6 + out: 15 + - name: shortest_route_contains_several_edges + in: + distance: [40, 1, 1, 1, 40, 40] + start_value: 1 + destination: 4 + out: 3 + - name: direct_route_contains_several_edges + in: + distance: [40, 1, 1, 1, 40, 40] + start_value: 4 + destination: 1 + out: 3 + - name: leading_and_trailing_zeroes + in: + distance: [0, 4, 6, 0, 10] + start_value: 4 + destination: 2 + out: 6 + - name: maximum_sum_with_equal_routes + in: + distance: [10000, 10000, 10000, 10000] + start_value: 0 + destination: 2 + out: 20000 + - name: minimum_nonzero_total + in: + distance: [1, 0, 0] + start_value: 0 + destination: 2 + out: 0 + - name: start_after_destination_wrap_shorter + in: + distance: [4, 6, 8, 10, 12] + start_value: 4 + destination: 1 + out: 16 + - name: start_after_destination_direct_shorter + in: + distance: [11, 2, 9, 4, 7, 3] + start_value: 4 + destination: 0 + out: 10 + - name: generated_maximum_length_a + seed: 118401 + in: + distance: + gen: array + len: 10000 + of: + gen: int + min: 0 + max: 10000 + start_value: + gen: int + min: 0 + max: 9999 + destination: + gen: int + min: 0 + max: 9999 + - name: generated_maximum_length_b + seed: 118402 + in: + distance: + gen: array + len: 10000 + of: + gen: int + min: 0 + max: 10000 + start_value: + gen: int + min: 0 + max: 9999 + destination: + gen: int + min: 0 + max: 9999 + - name: generated_maximum_length_c + seed: 118403 + in: + distance: + gen: array + len: 10000 + of: + gen: int + min: 0 + max: 10000 + start_value: + gen: int + min: 0 + max: 9999 + destination: + gen: int + min: 0 + max: 9999 + - name: generated_maximum_length_d + seed: 118404 + in: + distance: + gen: array + len: 10000 + of: + gen: int + min: 0 + max: 10000 + start_value: + gen: int + min: 0 + max: 9999 + destination: + gen: int + min: 0 + max: 9999 + - name: generated_maximum_length_e + seed: 118405 + in: + distance: + gen: array + len: 10000 + of: + gen: int + min: 0 + max: 10000 + start_value: + gen: int + min: 0 + max: 9999 + destination: + gen: int + min: 0 + max: 9999 + - name: generated_maximum_length_f + seed: 118406 + in: + distance: + gen: array + len: 10000 + of: + gen: int + min: 0 + max: 10000 + start_value: + gen: int + min: 0 + max: 9999 + destination: + gen: int + min: 0 + max: 9999 diff --git a/tests/1001-1500/1184. distance-between-bus-stops/sol.cpp b/tests/1001-1500/1184. distance-between-bus-stops/sol.cpp new file mode 100644 index 00000000..ec85805c --- /dev/null +++ b/tests/1001-1500/1184. distance-between-bus-stops/sol.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int distanceBetweenBusStops(vector& distance, int start, int destination) { + if (destination < start) { + swap(start, destination); + } + int s = 0; + for (int i = start; i < destination; i++) { + s += distance[i]; + } + int total = 0; + for (int d : distance) { + total += d; + } + return min(s, total - s); + } +}; diff --git a/tests/1001-1500/1184. distance-between-bus-stops/sol.cs b/tests/1001-1500/1184. distance-between-bus-stops/sol.cs new file mode 100644 index 00000000..a36b717b --- /dev/null +++ b/tests/1001-1500/1184. distance-between-bus-stops/sol.cs @@ -0,0 +1,18 @@ +public class Solution { + public int DistanceBetweenBusStops(int[] distance, int start, int destination) { + if (destination < start) { + int temp = start; + start = destination; + destination = temp; + } + int s = 0; + for (int i = start; i < destination; i++) { + s += distance[i]; + } + int total = 0; + foreach (int d in distance) { + total += d; + } + return Math.Min(s, total - s); + } +} diff --git a/tests/1001-1500/1184. distance-between-bus-stops/sol.dart b/tests/1001-1500/1184. distance-between-bus-stops/sol.dart new file mode 100644 index 00000000..3d47439a --- /dev/null +++ b/tests/1001-1500/1184. distance-between-bus-stops/sol.dart @@ -0,0 +1,21 @@ +class Solution { + int distanceBetweenBusStops(List distance, int start_value, int destination) { + if (start_value > destination) { + int temp = start_value; + start_value = destination; + destination = temp; + } + + int direct = 0; + int total = 0; + for (int i = 0; i < distance.length; i++) { + total += distance[i]; + if (i >= start_value && i < destination) { + direct += distance[i]; + } + } + + int wrap = total - direct; + return direct < wrap ? direct : wrap; + } +} diff --git a/tests/1001-1500/1184. distance-between-bus-stops/sol.go b/tests/1001-1500/1184. distance-between-bus-stops/sol.go new file mode 100644 index 00000000..e761ab7f --- /dev/null +++ b/tests/1001-1500/1184. distance-between-bus-stops/sol.go @@ -0,0 +1,17 @@ +func distanceBetweenBusStops(distance []int, start int, destination int) int { + if destination < start { + start, destination = destination, start + } + s := 0 + for i := start; i < destination; i++ { + s += distance[i] + } + total := 0 + for _, d := range distance { + total += d + } + if s < total-s { + return s + } + return total - s +} diff --git a/tests/1001-1500/1184. distance-between-bus-stops/sol.java b/tests/1001-1500/1184. distance-between-bus-stops/sol.java new file mode 100644 index 00000000..d2a196c0 --- /dev/null +++ b/tests/1001-1500/1184. distance-between-bus-stops/sol.java @@ -0,0 +1,18 @@ +class Solution { + public int distanceBetweenBusStops(int[] distance, int start, int destination) { + if (destination < start) { + int temp = start; + start = destination; + destination = temp; + } + int s = 0; + for (int i = start; i < destination; i++) { + s += distance[i]; + } + int total = 0; + for (int d : distance) { + total += d; + } + return Math.min(s, total - s); + } +} diff --git a/tests/1001-1500/1184. distance-between-bus-stops/sol.kt b/tests/1001-1500/1184. distance-between-bus-stops/sol.kt new file mode 100644 index 00000000..f6cb2597 --- /dev/null +++ b/tests/1001-1500/1184. distance-between-bus-stops/sol.kt @@ -0,0 +1,12 @@ +class Solution { + fun distanceBetweenBusStops(distance: IntArray, start: Int, destination: Int): Int { + var s = start + var d = destination + if (d < s) { + s = d.also { d = s } + } + val clockwise = (s until d).sumOf { distance[it] } + val total = distance.sum() + return minOf(clockwise, total - clockwise) + } +} diff --git a/tests/1001-1500/1184. distance-between-bus-stops/sol.py b/tests/1001-1500/1184. distance-between-bus-stops/sol.py new file mode 100644 index 00000000..cb02f36b --- /dev/null +++ b/tests/1001-1500/1184. distance-between-bus-stops/sol.py @@ -0,0 +1,10 @@ +class Solution: + def distanceBetweenBusStops( + self, distance: List[int], start: int, destination: int + ) -> int: + if destination < start: + start, destination = destination, start + return min( + sum(distance[start:destination]), + sum(distance) - sum(distance[start:destination]), + ) diff --git a/tests/1001-1500/1184. distance-between-bus-stops/sol.py2 b/tests/1001-1500/1184. distance-between-bus-stops/sol.py2 new file mode 100644 index 00000000..746f9028 --- /dev/null +++ b/tests/1001-1500/1184. distance-between-bus-stops/sol.py2 @@ -0,0 +1,12 @@ +class Solution(object): + def distanceBetweenBusStops(self, distance, start, destination): + """ + :type distance: List[int] + :type start: int + :type destination: int + :rtype: int + """ + if destination < start: + start, destination = destination, start + s = sum(distance[start:destination]) + return min(s, sum(distance) - s) diff --git a/tests/1001-1500/1184. distance-between-bus-stops/sol.rb b/tests/1001-1500/1184. distance-between-bus-stops/sol.rb new file mode 100644 index 00000000..768b8e1e --- /dev/null +++ b/tests/1001-1500/1184. distance-between-bus-stops/sol.rb @@ -0,0 +1,11 @@ +# @param {Integer[]} distance +# @param {Integer} start +# @param {Integer} destination +# @return {Integer} +def distance_between_bus_stops(distance, start, destination) + if destination < start + start, destination = destination, start + end + s = distance[start...destination].sum + [s, distance.sum - s].min +end diff --git a/tests/1001-1500/1184. distance-between-bus-stops/sol.rs b/tests/1001-1500/1184. distance-between-bus-stops/sol.rs new file mode 100644 index 00000000..5abb1244 --- /dev/null +++ b/tests/1001-1500/1184. distance-between-bus-stops/sol.rs @@ -0,0 +1,11 @@ +impl Solution { + pub fn distance_between_bus_stops(distance: Vec, start: i32, destination: i32) -> i32 { + let (mut s, mut d) = (start as usize, destination as usize); + if d < s { + std::mem::swap(&mut s, &mut d); + } + let clockwise: i32 = distance[s..d].iter().sum(); + let total: i32 = distance.iter().sum(); + clockwise.min(total - clockwise) + } +} diff --git a/tests/1001-1500/1184. distance-between-bus-stops/sol.swift b/tests/1001-1500/1184. distance-between-bus-stops/sol.swift new file mode 100644 index 00000000..36111bf0 --- /dev/null +++ b/tests/1001-1500/1184. distance-between-bus-stops/sol.swift @@ -0,0 +1,12 @@ +class Solution { + func distanceBetweenBusStops(_ distance: [Int], _ start: Int, _ destination: Int) -> Int { + var s = start + var d = destination + if d < s { + (s, d) = (d, s) + } + let clockwise = distance[s.. a + b, 0); + return Math.min(s, total - s); +} diff --git a/tests/1001-1500/1185. day-of-the-week/manifest.yaml b/tests/1001-1500/1185. day-of-the-week/manifest.yaml new file mode 100644 index 00000000..6c737a59 --- /dev/null +++ b/tests/1001-1500/1185. day-of-the-week/manifest.yaml @@ -0,0 +1,307 @@ +entry: + id: 1185 + title: day-of-the-week + params: + day: + type: int + month: + type: int + year: + type: int + call: + cpp: "Solution().dayOfTheWeek({day}, {month}, {year})" + rust: "Solution::day_of_the_week({day}, {month}, {year})" + python3: "Solution().dayOfTheWeek({day}, {month}, {year})" + python2: "Solution().dayOfTheWeek({day}, {month}, {year})" + ruby: "day_of_the_week({day}, {month}, {year})" + java: "new Solution().dayOfTheWeek({day}, {month}, {year})" + csharp: "new Solution().DayOfTheWeek({day}, {month}, {year})" + kotlin: "Solution().dayOfTheWeek({day}, {month}, {year})" + go: "dayOfTheWeek({day}, {month}, {year})" + dart: "Solution().dayOfTheWeek({day}, {month}, {year})" + swift: "Solution().dayOfTheWeek({day}, {month}, {year})" + typescript: "dayOfTheWeek({day}, {month}, {year})" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().dayOfTheWeek(day, month, year, {result})" + checker: | + class Checker: + def dayOfTheWeek(self, day, month, year, result): + names = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] + if not isinstance(result, str) or not (1971 <= year <= 2100): + return False + month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + leap = year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) + if leap: + month_days[1] = 29 + if not (1 <= month <= 12 and 1 <= day <= month_days[month - 1]): + return False + days_since_epoch = day - 1 + sum(month_days[:month - 1]) + for current_year in range(1971, year): + if current_year % 4 == 0 and (current_year % 100 != 0 or current_year % 400 == 0): + days_since_epoch += 366 + else: + days_since_epoch += 365 + return result == names[(4 + days_since_epoch) % 7] +seed: 1185 +tests: + - name: prompt-example-one + in: + day: 31 + month: 8 + year: 2019 + out: Saturday + - name: prompt-example-two + in: + day: 18 + month: 7 + year: 1999 + out: Sunday + - name: prompt-example-three + in: + day: 15 + month: 8 + year: 1993 + out: Sunday + - name: epoch-start + in: + day: 1 + month: 1 + year: 1971 + out: Friday + - name: first-year-end + in: + day: 31 + month: 12 + year: 1971 + out: Friday + - name: lower-year-midyear + in: + day: 4 + month: 7 + year: 1971 + out: Sunday + - name: upper-year-start + in: + day: 1 + month: 1 + year: 2100 + out: Friday + - name: upper-year-end + in: + day: 31 + month: 12 + year: 2100 + out: Friday + - name: january-first + in: + day: 1 + month: 1 + year: 2000 + out: Saturday + - name: generated-january-valid-years + in: + day: 15 + month: 1 + year: + gen: int + min: 1971 + max: 2100 + seed: 118501 + - name: february-first + in: + day: 1 + month: 2 + year: 2019 + out: Friday + - name: february-last-common + in: + day: 28 + month: 2 + year: 2019 + out: Thursday + - name: february-leap-day + in: + day: 29 + month: 2 + year: 2020 + out: Saturday + - name: february-after-leap + in: + day: 1 + month: 3 + year: 2020 + out: Sunday + - name: february-after-common + in: + day: 1 + month: 3 + year: 2019 + out: Friday + - name: generated-march-valid-years + in: + day: 31 + month: 3 + year: + gen: int + min: 1971 + max: 2100 + seed: 118502 + - name: april-first + in: + day: 1 + month: 4 + year: 2004 + out: Thursday + - name: generated-april-valid-years + in: + day: 30 + month: 4 + year: + gen: int + min: 1971 + max: 2100 + seed: 118503 + - name: may-first + in: + day: 1 + month: 5 + year: 2012 + out: Tuesday + - name: generated-june-valid-years + in: + day: 30 + month: 6 + year: + gen: int + min: 1971 + max: 2100 + seed: 118504 + - name: july-first + in: + day: 1 + month: 7 + year: 2016 + out: Friday + - name: august-end + in: + day: 31 + month: 8 + year: 2008 + out: Sunday + - name: september-first + in: + day: 1 + month: 9 + year: 2008 + out: Monday + - name: generated-september-valid-years + in: + day: 30 + month: 9 + year: + gen: int + min: 1971 + max: 2100 + seed: 118505 + - name: october-first + in: + day: 1 + month: 10 + year: 2010 + out: Friday + - name: october-end + in: + day: 31 + month: 10 + year: 1992 + out: Saturday + - name: november-first + in: + day: 1 + month: 11 + year: 1992 + out: Sunday + - name: november-end + in: + day: 30 + month: 11 + year: 2024 + out: Saturday + - name: december-first + in: + day: 1 + month: 12 + year: 2024 + out: Sunday + - name: leap-1996 + in: + day: 29 + month: 2 + year: 1996 + out: Thursday + - name: leap-2000-march + in: + day: 1 + month: 3 + year: 2000 + out: Wednesday + - name: century-2100 + in: + day: 28 + month: 2 + year: 2100 + out: Sunday + - name: recent-leap + in: + day: 29 + month: 2 + year: 2016 + out: Monday + - name: year-1980-end + in: + day: 31 + month: 12 + year: 1980 + out: Wednesday + - name: year-2050-mid + in: + day: 15 + month: 6 + year: 2050 + out: Wednesday + - name: first-leap-eve + in: + day: 28 + month: 2 + year: 1972 + out: Monday + - name: first-leap-day + in: + day: 29 + month: 2 + year: 1972 + out: Tuesday + - name: first-leap-march + in: + day: 1 + month: 3 + year: 1972 + out: Wednesday + - name: penultimate-year-end + in: + day: 31 + month: 12 + year: 2099 + out: Thursday + - name: century-march-first + in: + day: 1 + month: 3 + year: 2100 + out: Monday diff --git a/tests/1001-1500/1185. day-of-the-week/sol.cpp b/tests/1001-1500/1185. day-of-the-week/sol.cpp new file mode 100644 index 00000000..60dffea1 --- /dev/null +++ b/tests/1001-1500/1185. day-of-the-week/sol.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + string dayOfTheWeek(int day, int month, int year) { + string days[] = {"Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday"}; + + set leapYears; + for (int i = 1960; i < 2100; i += 4) { + leapYears.insert(i); + } + + unordered_map yearsDays; + for (int i = 1960; i <= 2100; i++) { + yearsDays[i] = leapYears.count(i) ? 366 : 365; + } + + int monthsDays[] = {0, 31, leapYears.count(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + + int resultDays = 0; + for (int y = 1971; y < year; y++) { + resultDays += yearsDays[y]; + } + for (int m = 1; m < month; m++) { + resultDays += monthsDays[m]; + } + resultDays += day; + + return days[resultDays % 7]; + } +}; diff --git a/tests/1001-1500/1185. day-of-the-week/sol.cs b/tests/1001-1500/1185. day-of-the-week/sol.cs new file mode 100644 index 00000000..fa1f5cb8 --- /dev/null +++ b/tests/1001-1500/1185. day-of-the-week/sol.cs @@ -0,0 +1,40 @@ +public class Solution { + public string DayOfTheWeek(int day, int month, int year) { + string[] days = {"Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday"}; + + HashSet leapYears = new HashSet(); + for (int i = 1960; i < 2100; i += 4) { + leapYears.Add(i); + } + + Dictionary yearsDays = new Dictionary(); + for (int i = 1960; i <= 2100; i++) { + yearsDays[i] = leapYears.Contains(i) ? 366 : 365; + } + + int[] monthsDays = new int[13]; + monthsDays[1] = 31; + monthsDays[2] = leapYears.Contains(year) ? 29 : 28; + monthsDays[3] = 31; + monthsDays[4] = 30; + monthsDays[5] = 31; + monthsDays[6] = 30; + monthsDays[7] = 31; + monthsDays[8] = 31; + monthsDays[9] = 30; + monthsDays[10] = 31; + monthsDays[11] = 30; + monthsDays[12] = 31; + + int resultDays = 0; + for (int y = 1971; y < year; y++) { + resultDays += yearsDays[y]; + } + for (int m = 1; m < month; m++) { + resultDays += monthsDays[m]; + } + resultDays += day; + + return days[resultDays % 7]; + } +} diff --git a/tests/1001-1500/1185. day-of-the-week/sol.dart b/tests/1001-1500/1185. day-of-the-week/sol.dart new file mode 100644 index 00000000..8d5a5976 --- /dev/null +++ b/tests/1001-1500/1185. day-of-the-week/sol.dart @@ -0,0 +1,28 @@ +class Solution { + String dayOfTheWeek(int day, int month, int year) { + List days = ["Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday"]; + + Set leapYears = {}; + for (int i = 1960; i < 2100; i += 4) { + leapYears.add(i); + } + + Map yearsDays = {}; + for (int i = 1960; i <= 2100; i++) { + yearsDays[i] = leapYears.contains(i) ? 366 : 365; + } + + List monthsDays = [0, 31, leapYears.contains(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + + int resultDays = 0; + for (int y = 1971; y < year; y++) { + resultDays += yearsDays[y]!; + } + for (int m = 1; m < month; m++) { + resultDays += monthsDays[m]; + } + resultDays += day; + + return days[resultDays % 7]; + } +} diff --git a/tests/1001-1500/1185. day-of-the-week/sol.go b/tests/1001-1500/1185. day-of-the-week/sol.go new file mode 100644 index 00000000..fc349476 --- /dev/null +++ b/tests/1001-1500/1185. day-of-the-week/sol.go @@ -0,0 +1,33 @@ +func dayOfTheWeek(day int, month int, year int) string { + days := []string{"Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday"} + + leapYears := make(map[int]bool) + for i := 1960; i < 2100; i += 4 { + leapYears[i] = true + } + + yearsDays := make(map[int]int) + for i := 1960; i <= 2100; i++ { + if leapYears[i] { + yearsDays[i] = 366 + } else { + yearsDays[i] = 365 + } + } + + monthsDays := []int{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} + if leapYears[year] { + monthsDays[2] = 29 + } + + resultDays := 0 + for y := 1971; y < year; y++ { + resultDays += yearsDays[y] + } + for m := 1; m < month; m++ { + resultDays += monthsDays[m] + } + resultDays += day + + return days[resultDays % 7] +} diff --git a/tests/1001-1500/1185. day-of-the-week/sol.java b/tests/1001-1500/1185. day-of-the-week/sol.java new file mode 100644 index 00000000..d3c817c6 --- /dev/null +++ b/tests/1001-1500/1185. day-of-the-week/sol.java @@ -0,0 +1,40 @@ +class Solution { + public String dayOfTheWeek(int day, int month, int year) { + String[] days = {"Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday"}; + + java.util.Set leapYears = new java.util.HashSet<>(); + for (int i = 1960; i < 2100; i += 4) { + leapYears.add(i); + } + + int[] yearsDays = new int[2101]; + for (int i = 1960; i <= 2100; i++) { + yearsDays[i] = leapYears.contains(i) ? 366 : 365; + } + + int[] monthsDays = new int[13]; + monthsDays[1] = 31; + monthsDays[2] = leapYears.contains(year) ? 29 : 28; + monthsDays[3] = 31; + monthsDays[4] = 30; + monthsDays[5] = 31; + monthsDays[6] = 30; + monthsDays[7] = 31; + monthsDays[8] = 31; + monthsDays[9] = 30; + monthsDays[10] = 31; + monthsDays[11] = 30; + monthsDays[12] = 31; + + int resultDays = 0; + for (int y = 1971; y < year; y++) { + resultDays += yearsDays[y]; + } + for (int m = 1; m < month; m++) { + resultDays += monthsDays[m]; + } + resultDays += day; + + return days[resultDays % 7]; + } +} diff --git a/tests/1001-1500/1185. day-of-the-week/sol.kt b/tests/1001-1500/1185. day-of-the-week/sol.kt new file mode 100644 index 00000000..1a06d12d --- /dev/null +++ b/tests/1001-1500/1185. day-of-the-week/sol.kt @@ -0,0 +1,31 @@ +class Solution { + fun dayOfTheWeek(day: Int, month: Int, year: Int): String { + val days = arrayOf("Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday") + + val leapYears = mutableSetOf() + for (i in 1960 until 2100 step 4) { + leapYears.add(i) + } + + val yearsDays = mutableMapOf() + for (i in 1960..2100) { + yearsDays[i] = if (i in leapYears) 366 else 365 + } + + val monthsDays = intArrayOf( + 0, 31, if (year in leapYears) 29 else 28, 31, 30, 31, 30, + 31, 31, 30, 31, 30, 31 + ) + + var resultDays = 0 + for (y in 1971 until year) { + resultDays += yearsDays[y]!! + } + for (m in 1 until month) { + resultDays += monthsDays[m] + } + resultDays += day + + return days[resultDays % 7] + } +} diff --git a/tests/1001-1500/1185. day-of-the-week/sol.py b/tests/1001-1500/1185. day-of-the-week/sol.py new file mode 100644 index 00000000..0fe92525 --- /dev/null +++ b/tests/1001-1500/1185. day-of-the-week/sol.py @@ -0,0 +1,39 @@ +class Solution: + def dayOfTheWeek(self, day: int, month: int, year: int) -> str: + days = { + # 01.01.1971 is Friday + 1: "Friday", + 2: "Saturday", + 3: "Sunday", + 4: "Monday", + 5: "Tuesday", + 6: "Wednesday", + 0: "Thursday", + } + + leap_years = set([i for i in range(1960, 2100, 4)]) + years_days = {i: 365 if i not in leap_years else 366 for i in range(1960, 2101)} + months_days = { + 1: 31, + 2: 28 if year not in leap_years else 29, + 3: 31, + 4: 30, + 5: 31, + 6: 30, + 7: 31, + 8: 31, + 9: 30, + 10: 31, + 11: 30, + 12: 31, + } + + result_days = 0 + for y in range(1971, year): + result_days += years_days[y] + + for m in range(1, month): + result_days += months_days[m] + result_days += day + + return days[result_days % 7] diff --git a/tests/1001-1500/1185. day-of-the-week/sol.py2 b/tests/1001-1500/1185. day-of-the-week/sol.py2 new file mode 100644 index 00000000..b07cb05e --- /dev/null +++ b/tests/1001-1500/1185. day-of-the-week/sol.py2 @@ -0,0 +1,44 @@ +class Solution(object): + def dayOfTheWeek(self, day, month, year): + """ + :type day: int + :type month: int + :type year: int + :rtype: str + """ + days = { + 1: "Friday", + 2: "Saturday", + 3: "Sunday", + 4: "Monday", + 5: "Tuesday", + 6: "Wednesday", + 0: "Thursday", + } + + leap_years = set([i for i in range(1960, 2100, 4)]) + years_days = {i: 365 if i not in leap_years else 366 for i in range(1960, 2101)} + months_days = { + 1: 31, + 2: 28 if year not in leap_years else 29, + 3: 31, + 4: 30, + 5: 31, + 6: 30, + 7: 31, + 8: 31, + 9: 30, + 10: 31, + 11: 30, + 12: 31 + } + + result_days = 0 + for y in range(1971, year): + result_days += years_days[y] + + for m in range(1, month): + result_days += months_days[m] + result_days += day + + return days[result_days % 7] diff --git a/tests/1001-1500/1185. day-of-the-week/sol.rb b/tests/1001-1500/1185. day-of-the-week/sol.rb new file mode 100644 index 00000000..6d422fe0 --- /dev/null +++ b/tests/1001-1500/1185. day-of-the-week/sol.rb @@ -0,0 +1,39 @@ +# @param {Integer} day +# @param {Integer} month +# @param {Integer} year +# @return {String} +def day_of_the_week(day, month, year) + days = { + 1 => "Friday", + 2 => "Saturday", + 3 => "Sunday", + 4 => "Monday", + 5 => "Tuesday", + 6 => "Wednesday", + 0 => "Thursday", + } + + leap_years = (1960...2100).step(4).to_set + years_days = (1960..2100).map { |i| [i, leap_years.include?(i) ? 366 : 365] }.to_h + months_days = { + 1 => 31, + 2 => leap_years.include?(year) ? 29 : 28, + 3 => 31, + 4 => 30, + 5 => 31, + 6 => 30, + 7 => 31, + 8 => 31, + 9 => 30, + 10 => 31, + 11 => 30, + 12 => 31 + } + + result_days = 0 + (1971...year).each { |y| result_days += years_days[y] } + (1...month).each { |m| result_days += months_days[m] } + result_days += day + + days[result_days % 7] +end diff --git a/tests/1001-1500/1185. day-of-the-week/sol.rs b/tests/1001-1500/1185. day-of-the-week/sol.rs new file mode 100644 index 00000000..fa4c2e13 --- /dev/null +++ b/tests/1001-1500/1185. day-of-the-week/sol.rs @@ -0,0 +1,30 @@ +impl Solution { + pub fn day_of_the_week(day: i32, month: i32, year: i32) -> String { + let days = ["Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday"]; + + let mut leap_years = std::collections::HashSet::new(); + let mut i = 1960; + while i < 2100 { + leap_years.insert(i); + i += 4; + } + + let mut years_days = std::collections::HashMap::new(); + for i in 1960..=2100 { + years_days.insert(i, if leap_years.contains(&i) { 366 } else { 365 }); + } + + let mut months_days = vec![0, 31, if leap_years.contains(&year) { 29 } else { 28 }, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + + let mut result_days = 0; + for y in 1971..year { + result_days += years_days[&y]; + } + for m in 1..month { + result_days += months_days[m as usize]; + } + result_days += day; + + days[(result_days % 7) as usize].to_string() + } +} diff --git a/tests/1001-1500/1185. day-of-the-week/sol.swift b/tests/1001-1500/1185. day-of-the-week/sol.swift new file mode 100644 index 00000000..3fb2aecd --- /dev/null +++ b/tests/1001-1500/1185. day-of-the-week/sol.swift @@ -0,0 +1,28 @@ +class Solution { + func dayOfTheWeek(_ day: Int, _ month: Int, _ year: Int) -> String { + let days = ["Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday"] + + var leapYears = Set() + for i in stride(from: 1960, to: 2100, by: 4) { + leapYears.insert(i) + } + + var yearsDays = [Int: Int]() + for i in 1960...2100 { + yearsDays[i] = leapYears.contains(i) ? 366 : 365 + } + + var monthsDays = [0, 31, leapYears.contains(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + + var resultDays = 0 + for y in 1971.. = new Set(); + for (let i = 1960; i < 2100; i += 4) { + leapYears.add(i); + } + + const yearsDays: { [key: number]: number } = {}; + for (let i = 1960; i <= 2100; i++) { + yearsDays[i] = leapYears.has(i) ? 366 : 365; + } + + const monthsDays: number[] = [ + 0, + 31, + leapYears.has(year) ? 29 : 28, + 31, + 30, + 31, + 30, + 31, + 31, + 30, + 31, + 30, + 31, + ]; + + let resultDays = 0; + for (let y = 1971; y < year; y++) { + resultDays += yearsDays[y]; + } + for (let m = 1; m < month; m++) { + resultDays += monthsDays[m]; + } + resultDays += day; + + return days[resultDays % 7]; +} diff --git a/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/manifest.yaml b/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/manifest.yaml new file mode 100644 index 00000000..da90e043 --- /dev/null +++ b/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/manifest.yaml @@ -0,0 +1,271 @@ +entry: + id: 1186 + title: "maximum-subarray-sum-with-one-deletion" + params: + arr: + type: array + items: + type: int + call: + cpp: "Solution().maximumSum({arr})" + rust: "Solution::maximum_sum({arr})" + python3: "Solution().maximumSum({arr})" + python2: "Solution().maximumSum({arr})" + ruby: "maximum_sum({arr})" + java: "new Solution().maximumSum({arr})" + csharp: "new Solution().MaximumSum({arr})" + kotlin: "Solution().maximumSum({arr})" + go: "maximumSum({arr})" + dart: "Solution().maximumSum({arr})" + swift: "Solution().maximumSum({arr})" + typescript: "maximumSum({arr})" + +judge: + type: "exact" + +limits: + time_ms: 700 + memory_mb: 300 + +oracle: + python3: + call: "Checker().maximumSum(arr, {result})" + checker: | + class Checker: + def maximumSum(self, arr, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + size = len(arr) + if size == 0: + return False + if size == 1: + return result == arr[0] + + # Best non-empty subarray ending at each position. + left = [0] * size + left[0] = arr[0] + for index in range(1, size): + left[index] = max(arr[index], left[index - 1] + arr[index]) + + # Best non-empty subarray starting at each position. + right = [0] * size + right[-1] = arr[-1] + for index in range(size - 2, -1, -1): + right[index] = max(arr[index], arr[index] + right[index + 1]) + + best = max(left) + for deleted_index in range(1, size - 1): + best = max(best, left[deleted_index - 1] + right[deleted_index + 1]) + return result == best + +seed: 118600 + +tests: + - name: "example_one" + in: + arr: [1, -2, 0, 3] + out: 4 + - name: "example_two" + in: + arr: [1, -2, -2, 3] + out: 3 + - name: "example_three" + in: + arr: [-1, -1, -1, -1] + out: -1 + - name: "single_positive" + in: + arr: [5] + out: 5 + - name: "single_negative" + in: + arr: [-5] + out: -5 + - name: "two_positive_values" + in: + arr: [4, 9] + out: 13 + - name: "two_negative_values" + in: + arr: [-4, -9] + out: -4 + - name: "increasing_positive" + in: + arr: [1, 2, 3] + out: 6 + - name: "delete_single_middle_loss" + in: + arr: [1, -5, 3] + out: 4 + - name: "bridge_best_segments" + in: + arr: [8, -1, 2, -10, 4] + out: 13 + - name: "delete_internal_dip" + in: + arr: [1, -4, 3, -2, 3] + out: 6 + - name: "all_negative_varied" + in: + arr: [-10, -2, -3] + out: -2 + - name: "all_zero" + in: + arr: [0, 0, 0] + out: 0 + - name: "positive_negative_positive" + in: + arr: [10, -10, 10] + out: 20 + - name: "optional_deletion_only_hurts" + in: + arr: [2, 5, 1] + out: 8 + - name: "two_loss_gap" + in: + arr: [3, -2, -2, 3] + out: 4 + - name: "minimum_and_maximum" + in: + arr: [-10000, 10000, -10000] + out: 10000 + - name: "maximum_values" + in: + arr: [10000, -10000, 10000] + out: 20000 + - name: "alternating_ones" + in: + arr: [1, -1, 1, -1, 1] + out: 2 + - name: "two_negatives_between" + in: + arr: [2, -1, -1, 2] + out: 3 + - name: "positive_block" + in: + arr: [-5, 1, 1, 1, -5] + out: 3 + - name: "prefix_and_suffix_join" + in: + arr: [7, -3, 4, -10, 6] + out: 14 + - name: "single_positive_center" + in: + arr: [-2, -2, 5, -2] + out: 5 + - name: "zero_gap" + in: + arr: [0, -1, 0, 0] + out: 0 + - name: "one_of_two_equal_losses" + in: + arr: [6, -5, -5, 6] + out: 7 + - name: "four_edges" + in: + arr: [4, -1, -1, -1, 4] + out: 6 + - name: "alternating_three" + in: + arr: [-3, 2, -3, 2, -3] + out: 4 + - name: "large_alternating" + in: + arr: [9, -8, 9, -8, 9] + out: 19 + - name: "late_large_positive" + in: + arr: [-10, 1, -10, 1, 10] + out: 12 + - name: "sparse_positive" + in: + arr: [1, -10, 2, -10, 3] + out: 5 + - name: "equal_edges_positive" + in: + arr: [5, -4, -4, -4, 5] + out: 5 + - name: "mixed_tail" + in: + arr: [-7, -6, 10, -1, -2] + out: 10 + - name: "two_positive_pairs" + in: + arr: [2, 2, -10, 2, 2] + out: 8 + - name: "maximum_boundary_pair" + in: + arr: [10000, -9999, -9999, 10000] + out: 10001 + - name: "generated_large_mixed_ten_thousand" + seed: 118601 + in: + arr: + gen: "array" + len: 10000 + of: + gen: "int" + min: -10000 + max: 10000 + distinct: false + sorted: false + - name: "generated_large_mixed_twenty_five_thousand" + seed: 118602 + in: + arr: + gen: "array" + len: 25000 + of: + gen: "int" + min: -10000 + max: 10000 + distinct: false + sorted: false + - name: "generated_large_all_negative" + seed: 118603 + in: + arr: + gen: "array" + len: 50000 + of: + gen: "int" + min: -10000 + max: -1 + distinct: false + sorted: false + - name: "generated_near_limit_mixed" + seed: 118604 + in: + arr: + gen: "array" + len: 99999 + of: + gen: "int" + min: -10000 + max: 10000 + distinct: false + sorted: false + - name: "generated_maximum_all_nonnegative" + seed: 118605 + in: + arr: + gen: "array" + len: 100000 + of: + gen: "int" + min: 0 + max: 10000 + distinct: false + sorted: false + - name: "generated_maximum_alternating_domain" + seed: 118606 + in: + arr: + gen: "array" + len: 100000 + of: + gen: "int" + min: -10000 + max: 10000 + distinct: false + sorted: false diff --git a/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.cpp b/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.cpp new file mode 100644 index 00000000..6d022234 --- /dev/null +++ b/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int maximumSum(vector& arr) { + int n = arr.size(); + if (n == 1) { + return arr[0]; + } + + int maxNoDelete = arr[0]; + int maxOneDelete = arr[0]; + int result = arr[0]; + + for (int i = 1; i < n; i++) { + int prevNoDelete = maxNoDelete; + maxNoDelete = max(maxNoDelete + arr[i], arr[i]); + maxOneDelete = max(maxOneDelete + arr[i], prevNoDelete); + result = max(result, max(maxNoDelete, maxOneDelete)); + } + + return result; + } +}; diff --git a/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.cs b/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.cs new file mode 100644 index 00000000..6938b963 --- /dev/null +++ b/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.cs @@ -0,0 +1,21 @@ +public class Solution { + public int MaximumSum(int[] arr) { + int n = arr.Length; + if (n == 1) { + return arr[0]; + } + + int maxNoDelete = arr[0]; + int maxOneDelete = arr[0]; + int result = arr[0]; + + for (int i = 1; i < n; i++) { + int prevNoDelete = maxNoDelete; + maxNoDelete = Math.Max(maxNoDelete + arr[i], arr[i]); + maxOneDelete = Math.Max(maxOneDelete + arr[i], prevNoDelete); + result = Math.Max(result, Math.Max(maxNoDelete, maxOneDelete)); + } + + return result; + } +} diff --git a/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.dart b/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.dart new file mode 100644 index 00000000..0b463925 --- /dev/null +++ b/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.dart @@ -0,0 +1,22 @@ +class Solution { + int maximumSum(List arr) { + int n = arr.length; + if (n == 1) { + return arr[0]; + } + + int maxNoDelete = arr[0]; + int maxOneDelete = arr[0]; + int result = arr[0]; + + for (int i = 1; i < n; i++) { + int prevNoDelete = maxNoDelete; + maxNoDelete = (maxNoDelete + arr[i] > arr[i]) ? maxNoDelete + arr[i] : arr[i]; + maxOneDelete = (maxOneDelete + arr[i] > prevNoDelete) ? maxOneDelete + arr[i] : prevNoDelete; + int tempMax = (maxNoDelete > maxOneDelete) ? maxNoDelete : maxOneDelete; + result = (result > tempMax) ? result : tempMax; + } + + return result; + } +} diff --git a/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.go b/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.go new file mode 100644 index 00000000..6023ec8f --- /dev/null +++ b/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.go @@ -0,0 +1,26 @@ +func maximumSum(arr []int) int { + n := len(arr) + if n == 1 { + return arr[0] + } + + maxNoDelete := arr[0] + maxOneDelete := arr[0] + result := arr[0] + + for i := 1; i < n; i++ { + prevNoDelete := maxNoDelete + maxNoDelete = max(maxNoDelete + arr[i], arr[i]) + maxOneDelete = max(maxOneDelete + arr[i], prevNoDelete) + result = max(result, max(maxNoDelete, maxOneDelete)) + } + + return result +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} diff --git a/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.java b/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.java new file mode 100644 index 00000000..780d3ff6 --- /dev/null +++ b/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.java @@ -0,0 +1,21 @@ +class Solution { + public int maximumSum(int[] arr) { + int n = arr.length; + if (n == 1) { + return arr[0]; + } + + int maxNoDelete = arr[0]; + int maxOneDelete = arr[0]; + int result = arr[0]; + + for (int i = 1; i < n; i++) { + int prevNoDelete = maxNoDelete; + maxNoDelete = Math.max(maxNoDelete + arr[i], arr[i]); + maxOneDelete = Math.max(maxOneDelete + arr[i], prevNoDelete); + result = Math.max(result, Math.max(maxNoDelete, maxOneDelete)); + } + + return result; + } +} diff --git a/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.kt b/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.kt new file mode 100644 index 00000000..895d5684 --- /dev/null +++ b/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.kt @@ -0,0 +1,21 @@ +class Solution { + fun maximumSum(arr: IntArray): Int { + val n = arr.size + if (n == 1) { + return arr[0] + } + + var maxNoDelete = arr[0] + var maxOneDelete = arr[0] + var result = arr[0] + + for (i in 1 until n) { + val prevNoDelete = maxNoDelete + maxNoDelete = maxOf(maxNoDelete + arr[i], arr[i]) + maxOneDelete = maxOf(maxOneDelete + arr[i], prevNoDelete) + result = maxOf(result, maxNoDelete, maxOneDelete) + } + + return result + } +} diff --git a/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.py b/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.py new file mode 100644 index 00000000..f5238d44 --- /dev/null +++ b/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.py @@ -0,0 +1,27 @@ +class Solution: + def maximumSum(self, arr: list[int]) -> int: + n = len(arr) + if n == 1: + return arr[0] + + # max_no_delete: Max sum ending at i without any deletions (Kadane's). + max_no_delete = arr[0] + + # max_one_delete: Max sum ending at i with exactly one deletion. + max_one_delete = arr[0] + result = arr[0] + + for i in range(1, n): + prev_no_delete = max_no_delete + + # Standard Kadane: extend previous or start new. + max_no_delete = max(max_no_delete + arr[i], arr[i]) + + # One-deletion logic: + # 1. Use existing deletion and keep current element. + # 2. Skip current element (use prev_no_delete). + max_one_delete = max(max_one_delete + arr[i], prev_no_delete) + + result = max(result, max_no_delete, max_one_delete) + + return result diff --git a/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.py2 b/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.py2 new file mode 100644 index 00000000..ba9efefa --- /dev/null +++ b/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.py2 @@ -0,0 +1,21 @@ +class Solution(object): + def maximumSum(self, arr): + """ + :type arr: List[int] + :rtype: int + """ + n = len(arr) + if n == 1: + return arr[0] + + max_no_delete = arr[0] + max_one_delete = arr[0] + result = arr[0] + + for i in range(1, n): + prev_no_delete = max_no_delete + max_no_delete = max(max_no_delete + arr[i], arr[i]) + max_one_delete = max(max_one_delete + arr[i], prev_no_delete) + result = max(result, max_no_delete, max_one_delete) + + return result diff --git a/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.rb b/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.rb new file mode 100644 index 00000000..c831ac53 --- /dev/null +++ b/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.rb @@ -0,0 +1,19 @@ +# @param {Integer[]} arr +# @return {Integer} +def maximum_sum(arr) + n = arr.length + return arr[0] if n == 1 + + max_no_delete = arr[0] + max_one_delete = arr[0] + result = arr[0] + + (1...n).each do |i| + prev_no_delete = max_no_delete + max_no_delete = [max_no_delete + arr[i], arr[i]].max + max_one_delete = [max_one_delete + arr[i], prev_no_delete].max + result = [result, max_no_delete, max_one_delete].max + end + + result +end diff --git a/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.rs b/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.rs new file mode 100644 index 00000000..ed8cff1a --- /dev/null +++ b/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.rs @@ -0,0 +1,21 @@ +impl Solution { + pub fn maximum_sum(arr: Vec) -> i32 { + let n = arr.len(); + if n == 1 { + return arr[0]; + } + + let mut max_no_delete = arr[0]; + let mut max_one_delete = arr[0]; + let mut result = arr[0]; + + for i in 1..n { + let prev_no_delete = max_no_delete; + max_no_delete = std::cmp::max(max_no_delete + arr[i], arr[i]); + max_one_delete = std::cmp::max(max_one_delete + arr[i], prev_no_delete); + result = std::cmp::max(result, std::cmp::max(max_no_delete, max_one_delete)); + } + + result + } +} diff --git a/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.swift b/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.swift new file mode 100644 index 00000000..fd4198e5 --- /dev/null +++ b/tests/1001-1500/1186. maximum-subarray-sum-with-one-deletion/sol.swift @@ -0,0 +1,21 @@ +class Solution { + func maximumSum(_ arr: [Int]) -> Int { + let n = arr.count + if n == 1 { + return arr[0] + } + + var maxNoDelete = arr[0] + var maxOneDelete = arr[0] + var result = arr[0] + + for i in 1.. previous: + old = next_states.get(value) + if old is None or operations < old: + next_states[value] = operations + replacement_index = bisect_right(replacements, previous) + if replacement_index < len(replacements): + replacement = replacements[replacement_index] + candidate = operations + 1 + old = next_states.get(replacement) + if old is None or candidate < old: + next_states[replacement] = candidate + states = next_states + if not states: + break + + expected = min(states.values()) if states else -1 + return result == expected + +seed: 1187 + +tests: + - name: "example_one" + in: + arr1: [1, 5, 3, 6, 7] + arr2: [1, 3, 2, 4] + out: 1 + - name: "example_two" + in: + arr1: [1, 5, 3, 6, 7] + arr2: [4, 3, 1] + out: 2 + - name: "example_three" + in: + arr1: [1, 5, 3, 6, 7] + arr2: [1, 6, 3, 3] + out: -1 + - name: "single_element" + in: + arr1: [1000000000] + arr2: [0] + - name: "already_strict_with_duplicates_in_pool" + in: + arr1: [0, 2, 4, 7] + arr2: [1, 1, 3, 5] + - name: "two_equal_values" + in: + arr1: [4, 4] + arr2: [3, 5] + - name: "all_equal_requires_full_rebuild" + in: + arr1: [4, 4, 4] + arr2: [1, 2, 3, 5] + - name: "descending_can_be_rebuilt" + in: + arr1: [5, 4, 3, 2, 1] + arr2: [1, 2, 3, 4, 5] + - name: "descending_impossible_with_one_pool_value" + in: + arr1: [3, 2, 1] + arr2: [2, 2, 2] + - name: "zero_boundary" + in: + arr1: [0, 0, 1] + arr2: [0, 1, 2, 3] + - name: "maximum_value_boundary" + in: + arr1: [1000000000, 0, 1000000000] + arr2: [1, 2, 999999999] + - name: "must_replace_middle_with_smaller_value" + in: + arr1: [1, 5, 3] + arr2: [2, 2, 4] + - name: "no_replacement_is_usable" + in: + arr1: [1, 2, 1, 2] + arr2: [0] + - name: "all_positions_can_be_replaced" + in: + arr1: [10, 10, 10] + arr2: [1, 2, 3, 4] + - name: "preserve_later_anchor" + in: + arr1: [1, 10, 2, 9, 3] + arr2: [4, 5, 6, 7, 8] + - name: "one_inversion_with_multiple_choices" + in: + arr1: [1, 2, 10, 4, 5] + arr2: [3, 6, 7, 8, 9] + - name: "many_equal_first_values" + in: + arr1: [2, 2, 2, 2] + arr2: [1, 3, 4, 5] + - name: "replacement_must_fit_both_neighbors" + in: + arr1: [1, 100, 2] + arr2: [3] + - name: "zero_before_large_drop" + in: + arr1: [0, 100, 2, 3] + arr2: [1, 2, 4] + - name: "repeated_pivots" + in: + arr1: [1, 3, 2, 4, 3, 5, 4, 6] + arr2: [2, 3, 4, 5] + - name: "pool_below_all_original_values" + in: + arr1: [5, 6, 7] + arr2: [1, 2, 3, 4] + - name: "pool_above_all_original_values" + in: + arr1: [1, 2, 3] + arr2: [4, 5, 6] + - name: "alternating_extremes" + in: + arr1: [100, 1, 100, 1, 100] + arr2: [2, 3, 4, 5] + - name: "duplicate_pool_values" + in: + arr1: [5, 1, 5, 1] + arr2: [2, 2, 3, 3] + - name: "minimal_increasing_prefix" + in: + arr1: [0, 1] + arr2: [0, 0] + - name: "long_interleaved_decisions" + in: + arr1: [1, 9, 2, 8, 3, 7, 4, 6, 5] + arr2: [2, 3, 4, 5, 6, 7, 8] + - name: "high_boundary_gap" + in: + arr1: [999999998, 0, 999999999] + arr2: [1, 999999998] + - name: "replace_prefix_to_keep_suffix" + in: + arr1: [8, 9, 1, 10] + arr2: [2, 3, 4, 5, 6, 7] + - name: "replace_suffix_after_peak" + in: + arr1: [1, 8, 2, 3] + arr2: [4, 5, 6, 7] + - name: "duplicate_original_and_duplicate_pool" + in: + arr1: [0, 2, 2, 5, 5] + arr2: [1, 1, 3, 3, 4, 6] + - name: "requires_non_greedy_early_replacement" + in: + arr1: [4, 9, 3, 10] + arr2: [1, 5, 6, 7, 8] + - name: "impossible_after_maximum" + in: + arr1: [0, 1000000000, 1] + arr2: [2, 3, 4] + - name: "replacement_would_create_equality" + in: + arr1: [1, 3, 2] + arr2: [2] + - name: "keep_last_original_anchor" + in: + arr1: [6, 5, 4] + arr2: [1, 2, 3, 7] + - name: "generated_dense_duplicate_stress" + seed: 118701 + in: + arr1: + gen: "array" + len: 850 + of: + gen: "int" + min: 0 + max: 100 + arr2: + gen: "array" + len: 850 + of: + gen: "int" + min: 0 + max: 120 + - name: "generated_wide_value_stress" + seed: 118702 + in: + arr1: + gen: "array" + len: 900 + of: + gen: "int" + min: 0 + max: 1000000000 + arr2: + gen: "array" + len: 900 + of: + gen: "int" + min: 0 + max: 1000000000 + - name: "generated_medium_domain_stress" + seed: 118703 + in: + arr1: + gen: "array" + len: 875 + of: + gen: "int" + min: 0 + max: 5000 + arr2: + gen: "array" + len: 875 + of: + gen: "int" + min: 0 + max: 5000 + - name: "generated_zero_heavy_stress" + seed: 118704 + in: + arr1: + gen: "array" + len: 800 + of: + gen: "int" + min: 0 + max: 12 + arr2: + gen: "array" + len: 800 + of: + gen: "int" + min: 0 + max: 20 + - name: "generated_asymmetric_pool_stress" + seed: 118705 + in: + arr1: + gen: "array" + len: 900 + of: + gen: "int" + min: 0 + max: 1000000 + arr2: + gen: "array" + len: 700 + of: + gen: "int" + min: 0 + max: 1000000 + - name: "generated_near_recursion_limit_stress" + seed: 118706 + in: + arr1: + gen: "array" + len: 950 + of: + gen: "int" + min: 0 + max: 1000000000 + arr2: + gen: "array" + len: 950 + of: + gen: "int" + min: 0 + max: 1000000000 diff --git a/tests/1001-1500/1187. make-array-strictly-increasing/sol.cpp b/tests/1001-1500/1187. make-array-strictly-increasing/sol.cpp new file mode 100644 index 00000000..f17dbf2b --- /dev/null +++ b/tests/1001-1500/1187. make-array-strictly-increasing/sol.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + int makeArrayIncreasing(vector& arr1, vector& arr2) { + sort(arr2.begin(), arr2.end()); + arr2.erase(unique(arr2.begin(), arr2.end()), arr2.end()); + map, int> memo; + + function dfs = [&](int i, long long prevMax) -> int { + if (i == arr1.size()) return 0; + + auto key = make_pair(i, prevMax); + if (memo.count(key)) return memo[key]; + + int j = upper_bound(arr2.begin(), arr2.end(), prevMax) - arr2.begin(); + + int ans = INT_MAX / 2; + if (arr1[i] > prevMax) { + ans = min(ans, dfs(i + 1, arr1[i])); + } + if (j < arr2.size()) { + ans = min(ans, dfs(i + 1, arr2[j]) + 1); + } + + return memo[key] = ans; + }; + + int ops = dfs(0, LLONG_MIN); + return ops >= INT_MAX / 2 ? -1 : ops; + } +}; diff --git a/tests/1001-1500/1187. make-array-strictly-increasing/sol.cs b/tests/1001-1500/1187. make-array-strictly-increasing/sol.cs new file mode 100644 index 00000000..618470a2 --- /dev/null +++ b/tests/1001-1500/1187. make-array-strictly-increasing/sol.cs @@ -0,0 +1,42 @@ +public class Solution { + public int MakeArrayIncreasing(int[] arr1, int[] arr2) { + Array.Sort(arr2); + var memo = new Dictionary<(int, long), int>(); + + int Dfs(int i, long prevMax) { + if (i == arr1.Length) return 0; + + var key = (i, prevMax); + if (memo.ContainsKey(key)) return memo[key]; + + int j = BisectRight(arr2, prevMax); + + int ans = int.MaxValue / 2; + if (arr1[i] > prevMax) { + ans = Math.Min(ans, Dfs(i + 1, arr1[i])); + } + if (j < arr2.Length) { + ans = Math.Min(ans, Dfs(i + 1, arr2[j]) + 1); + } + + memo[key] = ans; + return ans; + } + + int ops = Dfs(0, long.MinValue); + return ops >= int.MaxValue / 2 ? -1 : ops; + } + + private int BisectRight(int[] arr, long target) { + int lo = 0, 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/1001-1500/1187. make-array-strictly-increasing/sol.dart b/tests/1001-1500/1187. make-array-strictly-increasing/sol.dart new file mode 100644 index 00000000..9caf8381 --- /dev/null +++ b/tests/1001-1500/1187. make-array-strictly-increasing/sol.dart @@ -0,0 +1,42 @@ +class Solution { + int makeArrayIncreasing(List arr1, List arr2) { + arr2.sort(); + var memo = {}; + + int dfs(int i, int prevMax) { + if (i == arr1.length) return 0; + + final key = '$i,$prevMax'; + if (memo.containsKey(key)) return memo[key]!; + + int j = bisectRight(arr2, prevMax); + + int ans = 1 << 60; + if (arr1[i] > prevMax) { + ans = min(ans, dfs(i + 1, arr1[i])); + } + if (j < arr2.length) { + ans = min(ans, dfs(i + 1, arr2[j]) + 1); + } + + memo[key] = ans; + return ans; + } + + int ops = dfs(0, -1 << 60); + return ops >= (1 << 60) ? -1 : ops; + } + + int bisectRight(List arr, int target) { + int lo = 0, 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/1001-1500/1187. make-array-strictly-increasing/sol.go b/tests/1001-1500/1187. make-array-strictly-increasing/sol.go new file mode 100644 index 00000000..d96f0d33 --- /dev/null +++ b/tests/1001-1500/1187. make-array-strictly-increasing/sol.go @@ -0,0 +1,47 @@ +func makeArrayIncreasing(arr1 []int, arr2 []int) int { + sort.Ints(arr2) + memo := make(map[[2]int]int) + + var dfs func(int, int) int + dfs = func(i int, prevMax int) int { + if i == len(arr1) { + return 0 + } + key := [2]int{i, prevMax} + if v, ok := memo[key]; ok { + return v + } + + j := bisectRight(arr2, prevMax) + + ans := math.MaxInt32 / 2 + if arr1[i] > prevMax { + ans = min(ans, dfs(i+1, arr1[i])) + } + if j < len(arr2) { + ans = min(ans, dfs(i+1, arr2[j])+1) + } + + memo[key] = ans + return ans + } + + ops := dfs(0, math.MinInt32) + if ops >= math.MaxInt32/2 { + return -1 + } + return ops +} + +func bisectRight(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/1001-1500/1187. make-array-strictly-increasing/sol.java b/tests/1001-1500/1187. make-array-strictly-increasing/sol.java new file mode 100644 index 00000000..fcd3561b --- /dev/null +++ b/tests/1001-1500/1187. make-array-strictly-increasing/sol.java @@ -0,0 +1,43 @@ +class Solution { + public int makeArrayIncreasing(int[] arr1, int[] arr2) { + Arrays.sort(arr2); + int n = arr1.length; + Map memo = new HashMap<>(); + + int answer = dfs(0, Integer.MIN_VALUE, arr1, arr2, memo); + return answer >= Integer.MAX_VALUE / 2 ? -1 : answer; + } + + private int dfs(int i, int prevMax, int[] arr1, int[] arr2, Map memo) { + if (i == arr1.length) return 0; + + String key = i + "," + prevMax; + if (memo.containsKey(key)) return memo.get(key); + + int j = bisectRight(arr2, prevMax); + + int ans = Integer.MAX_VALUE / 2; + if (arr1[i] > prevMax) { + ans = Math.min(ans, dfs(i + 1, arr1[i], arr1, arr2, memo)); + } + if (j < arr2.length) { + ans = Math.min(ans, dfs(i + 1, arr2[j], arr1, arr2, memo) + 1); + } + + memo.put(key, ans); + return ans; + } + + private int bisectRight(int[] arr, int target) { + int lo = 0, 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/1001-1500/1187. make-array-strictly-increasing/sol.kt b/tests/1001-1500/1187. make-array-strictly-increasing/sol.kt new file mode 100644 index 00000000..72ba1d31 --- /dev/null +++ b/tests/1001-1500/1187. make-array-strictly-increasing/sol.kt @@ -0,0 +1,43 @@ +class Solution { + fun makeArrayIncreasing(arr1: IntArray, arr2: IntArray): Int { + arr2.sort() + val memo = HashMap() + + fun dfs(i: Int, prevMax: Int): Int { + if (i == arr1.size) return 0 + + val key = "$i,$prevMax" + memo[key]?.let { return it } + + val j = bisectRight(arr2, prevMax) + + var ans = Int.MAX_VALUE / 2 + if (arr1[i] > prevMax) { + ans = minOf(ans, dfs(i + 1, arr1[i])) + } + if (j < arr2.size) { + ans = minOf(ans, dfs(i + 1, arr2[j]) + 1) + } + + memo[key] = ans + return ans + } + + val ops = dfs(0, Int.MIN_VALUE) + return if (ops >= Int.MAX_VALUE / 2) -1 else ops + } + + private fun bisectRight(arr: IntArray, target: Int): Int { + var lo = 0 + var hi = arr.size + while (lo < hi) { + val mid = lo + (hi - lo) / 2 + if (arr[mid] <= target) { + lo = mid + 1 + } else { + hi = mid + } + } + return lo + } +} diff --git a/tests/1001-1500/1187. make-array-strictly-increasing/sol.py b/tests/1001-1500/1187. make-array-strictly-increasing/sol.py new file mode 100644 index 00000000..2bb670e2 --- /dev/null +++ b/tests/1001-1500/1187. make-array-strictly-increasing/sol.py @@ -0,0 +1,23 @@ +from bisect import bisect_right +from functools import cache +from sys import maxsize +from typing import List + + +class Solution: + def makeArrayIncreasing(self, first: List[int], second: List[int]) -> int: + @cache + def dp(i: int, prev_max: int) -> int: + if i == len(first): + return 0 + + j = bisect_right(second, prev_max) + + return min( + dp(i + 1, first[i]) if first[i] > prev_max else maxsize, + dp(i + 1, second[j]) + 1 if j < len(second) else maxsize, + ) + + second.sort() + operations = dp(0, -maxsize) + return operations if operations != maxsize else -1 diff --git a/tests/1001-1500/1187. make-array-strictly-increasing/sol.py2 b/tests/1001-1500/1187. make-array-strictly-increasing/sol.py2 new file mode 100644 index 00000000..d0101010 --- /dev/null +++ b/tests/1001-1500/1187. make-array-strictly-increasing/sol.py2 @@ -0,0 +1,32 @@ +class Solution(object): + def makeArrayIncreasing(self, arr1, arr2): + """ + :type arr1: List[int] + :type arr2: List[int] + :rtype: int + """ + import bisect + arr2.sort() + max_int = float('inf') + memo = {} + + def dp(i, prev_max): + if i == len(arr1): + return 0 + key = (i, prev_max) + if key in memo: + return memo[key] + + j = bisect.bisect_right(arr2, prev_max) + + ans = max_int + if arr1[i] > prev_max: + ans = min(ans, dp(i + 1, arr1[i])) + if j < len(arr2): + ans = min(ans, dp(i + 1, arr2[j]) + 1) + + memo[key] = ans + return ans + + ops = dp(0, -max_int) + return ops if ops != max_int else -1 diff --git a/tests/1001-1500/1187. make-array-strictly-increasing/sol.rb b/tests/1001-1500/1187. make-array-strictly-increasing/sol.rb new file mode 100644 index 00000000..9964a388 --- /dev/null +++ b/tests/1001-1500/1187. make-array-strictly-increasing/sol.rb @@ -0,0 +1,32 @@ +# @param {Integer[]} arr1 +# @param {Integer[]} arr2 +# @return {Integer} +def make_array_increasing(arr1, arr2) + arr2.sort! + max_int = Float::INFINITY + memo = {} + + dp = lambda do |i, prev_max| + return 0 if i == arr1.length + + key = [i, prev_max] + return memo[key] if memo.key?(key) + + j = arr2.bsearch_index { |x| x > prev_max } + j = arr2.length if j.nil? + + ans = max_int + if arr1[i] > prev_max + ans = [ans, dp.call(i + 1, arr1[i])].min + end + if j < arr2.length + ans = [ans, dp.call(i + 1, arr2[j]) + 1].min + end + + memo[key] = ans + ans + end + + ops = dp.call(0, -Float::INFINITY) + ops == max_int ? -1 : ops +end diff --git a/tests/1001-1500/1187. make-array-strictly-increasing/sol.rs b/tests/1001-1500/1187. make-array-strictly-increasing/sol.rs new file mode 100644 index 00000000..4282937f --- /dev/null +++ b/tests/1001-1500/1187. make-array-strictly-increasing/sol.rs @@ -0,0 +1,56 @@ +impl Solution { + pub fn make_array_increasing(arr1: Vec, arr2: Vec) -> i32 { + use std::collections::HashMap; + + let mut arr2 = arr2; + arr2.sort(); + arr2.dedup(); + let mut memo: HashMap<(usize, i64), i32> = HashMap::new(); + + fn bisect_right(arr: &[i32], target: i64) -> usize { + let mut lo = 0; + let mut hi = arr.len(); + while lo < hi { + let mid = lo + (hi - lo) / 2; + if (arr[mid] as i64) <= target { + lo = mid + 1; + } else { + hi = mid; + } + } + lo + } + + fn dfs( + i: usize, + prev_max: i64, + arr1: &[i32], + arr2: &[i32], + memo: &mut HashMap<(usize, i64), i32> + ) -> i32 { + if i == arr1.len() { + return 0; + } + + if let Some(&ans) = memo.get(&(i, prev_max)) { + return ans; + } + + let j = bisect_right(arr2, prev_max); + + let mut ans = i32::MAX / 2; + if (arr1[i] as i64) > prev_max { + ans = ans.min(dfs(i + 1, arr1[i] as i64, arr1, arr2, memo)); + } + if j < arr2.len() { + ans = ans.min(dfs(i + 1, arr2[j] as i64, arr1, arr2, memo) + 1); + } + + memo.insert((i, prev_max), ans); + ans + } + + let ops = dfs(0, i64::MIN, &arr1, &arr2, &mut memo); + if ops >= i32::MAX / 2 { -1 } else { ops } + } +} diff --git a/tests/1001-1500/1187. make-array-strictly-increasing/sol.swift b/tests/1001-1500/1187. make-array-strictly-increasing/sol.swift new file mode 100644 index 00000000..49a24f25 --- /dev/null +++ b/tests/1001-1500/1187. make-array-strictly-increasing/sol.swift @@ -0,0 +1,42 @@ +class Solution { + func makeArrayIncreasing(_ arr1: [Int], _ arr2: [Int]) -> Int { + var arr2 = arr2.sorted() + var memo = [String: Int]() + + func dfs(_ i: Int, _ prevMax: Int) -> Int { + if i == arr1.count { return 0 } + + let key = "\(i),\(prevMax)" + if let val = memo[key] { return val } + + let j = bisectRight(arr2, prevMax) + + var ans = Int.max / 2 + if arr1[i] > prevMax { + ans = min(ans, dfs(i + 1, arr1[i])) + } + if j < arr2.count { + ans = min(ans, dfs(i + 1, arr2[j]) + 1) + } + + memo[key] = ans + return ans + } + + let ops = dfs(0, Int.min) + return ops >= Int.max / 2 ? -1 : ops + } + + private func bisectRight(_ 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/1001-1500/1187. make-array-strictly-increasing/sol.ts b/tests/1001-1500/1187. make-array-strictly-increasing/sol.ts new file mode 100644 index 00000000..c6805397 --- /dev/null +++ b/tests/1001-1500/1187. make-array-strictly-increasing/sol.ts @@ -0,0 +1,41 @@ +function makeArrayIncreasing(arr1: number[], arr2: number[]): number { + arr2.sort((a, b) => a - b); + const memo = new Map(); + + function bisectRight(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; + } + + function dfs(i: number, prevMax: number): number { + if (i === arr1.length) return 0; + + const key = `${i},${prevMax}`; + if (memo.has(key)) return memo.get(key)!; + + const j = bisectRight(arr2, prevMax); + + let ans = Number.MAX_SAFE_INTEGER; + if (arr1[i] > prevMax) { + ans = Math.min(ans, dfs(i + 1, arr1[i])); + } + if (j < arr2.length) { + ans = Math.min(ans, dfs(i + 1, arr2[j]) + 1); + } + + memo.set(key, ans); + return ans; + } + + const ops = dfs(0, -Number.MAX_SAFE_INTEGER); + return ops >= Number.MAX_SAFE_INTEGER ? -1 : ops; +} diff --git a/tests/1001-1500/1189. maximum-number-of-balloons/manifest.yaml b/tests/1001-1500/1189. maximum-number-of-balloons/manifest.yaml new file mode 100644 index 00000000..cb25181e --- /dev/null +++ b/tests/1001-1500/1189. maximum-number-of-balloons/manifest.yaml @@ -0,0 +1,216 @@ +entry: + id: 1189 + title: "maximum-number-of-balloons" + params: + text: + type: string + call: + cpp: "Solution().maxNumberOfBalloons({text})" + rust: "Solution::max_number_of_balloons({text})" + python3: "Solution().maxNumberOfBalloons({text})" + python2: "Solution().maxNumberOfBalloons({text})" + ruby: "max_number_of_balloons({text})" + java: "new Solution().maxNumberOfBalloons({text})" + csharp: "new Solution().MaxNumberOfBalloons({text})" + kotlin: "Solution().maxNumberOfBalloons({text})" + go: "maxNumberOfBalloons({text})" + dart: "Solution().maxNumberOfBalloons({text})" + swift: "Solution().maxNumberOfBalloons({text})" + typescript: "maxNumberOfBalloons({text})" +judge: + type: exact +limits: + time_ms: 300 + memory_mb: 300 +oracle: + python3: + call: "Checker().maxNumberOfBalloons(text, {result})" + checker: | + class Checker: + def maxNumberOfBalloons(self, text, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + return result == min( + text.count('b'), text.count('a'), text.count('l') // 2, + text.count('o') // 2, text.count('n') + ) +seed: 1189 +tests: + - name: example_one + in: + text: "nlaebolko" + out: 1 + - name: example_two + in: + text: "loonbalxballpoon" + out: 2 + - name: example_three + in: + text: "leetcode" + out: 0 + - name: exact_single_word + in: + text: "balloon" + out: 1 + - name: reverse_order_word + in: + text: "noollab" + out: 1 + - name: minimum_length_nonmatching + in: + text: "a" + out: 0 + - name: no_b + in: + text: "alloon" + out: 0 + - name: no_a + in: + text: "blloon" + out: 0 + - name: no_l + in: + text: "baoon" + out: 0 + - name: one_l_only + in: + text: "baloon" + out: 0 + - name: no_o + in: + text: "balln" + out: 0 + - name: one_o_only + in: + text: "ballon" + out: 0 + - name: no_n + in: + text: "balloo" + out: 0 + - name: b_is_bottleneck + in: + text: "baalllloooonn" + out: 1 + - name: a_is_bottleneck + in: + text: "bballlloooonn" + out: 1 + - name: l_is_bottleneck + in: + text: "bbaalloooonn" + out: 1 + - name: o_is_bottleneck + in: + text: "bbaalllloonn" + out: 1 + - name: n_is_bottleneck + in: + text: "bbaalllloooo" + out: 0 + - name: balanced_two_grouped + in: + text: "bbaalllloooonn" + out: 2 + - name: balanced_three_grouped + in: + text: "bbbaaalllllloooooonnn" + out: 3 + - name: balanced_many_reordered + in: + text: "nnoobbaallllooon" + out: 2 + - name: surplus_target_characters + in: + text: "bbbbbaaaaaallllooooonnnn" + out: 2 + - name: surplus_noise + in: + text: "xyzxyzballoonqqqq" + out: 1 + - name: pangram_without_balloon_letters + in: + text: "cdefghijkmpqrstuvwxyz" + out: 0 + - name: repeated_l_and_o_surplus + in: + text: "ballllllllllllooooooon" + out: 1 + - name: trailing_partial_word + in: + text: "balloonballoo" + out: 1 + - name: leading_partial_word + in: + text: "ballballoon" + out: 1 + - name: five_complete_words + in: + text: "balloonballoonballoonballoonballoon" + out: 5 + - name: separated_characters + in: + text: "bxaylzlwowonq" + out: 1 + - name: l_floor_division + in: + text: "bbaallllloooonn" + out: 2 + - name: o_floor_division + in: + text: "bbaallllooooonn" + out: 2 + - name: n_limits_large_pool + in: + text: "bbbbbaaaaallllllllllloooooooooonn" + out: 2 + - name: only_one_required_character + in: + text: "llllllllll" + out: 0 + - name: all_lowercase_noise + in: + text: "qwertyuiopasdfghjkzxcv" + out: 0 + - name: stress_target_letters + seed: 118901 + in: + text: + gen: "str" + len: 10000 + alphabet: "balon" + - name: stress_full_alphabet + seed: 118902 + in: + text: + gen: "str" + len: 10000 + alphabet: "abcdefghijklmnopqrstuvwxyz" + - name: stress_missing_n + seed: 118903 + in: + text: + gen: "str" + len: 10000 + alphabet: "abloxyz" + - name: stress_limited_l + seed: 118904 + in: + text: + gen: "str" + len: 10000 + alphabet: "ablxyz" + - name: stress_limited_o + seed: 118905 + in: + text: + gen: "str" + len: 10000 + alphabet: "abnoxyz" + - name: stress_irrelevant_letters + seed: 118906 + in: + text: + gen: "str" + len: 10000 + alphabet: "cdefghijkmpqrstuvwxyz" diff --git a/tests/1001-1500/1189. maximum-number-of-balloons/sol.cpp b/tests/1001-1500/1189. maximum-number-of-balloons/sol.cpp new file mode 100644 index 00000000..327eadc7 --- /dev/null +++ b/tests/1001-1500/1189. maximum-number-of-balloons/sol.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + int maxNumberOfBalloons(string text) { + unordered_map f; + for (char c : text) { + f[c]++; + } + return min({f['b'], f['a'], f['l'] / 2, f['o'] / 2, f['n']}); + } +}; diff --git a/tests/1001-1500/1189. maximum-number-of-balloons/sol.cs b/tests/1001-1500/1189. maximum-number-of-balloons/sol.cs new file mode 100644 index 00000000..43c8f13b --- /dev/null +++ b/tests/1001-1500/1189. maximum-number-of-balloons/sol.cs @@ -0,0 +1,11 @@ +public class Solution { + public int MaxNumberOfBalloons(string text) { + var f = new Dictionary(); + foreach (char c in text) { + if (f.ContainsKey(c)) f[c]++; + else f[c] = 1; + } + int get(char c) => f.ContainsKey(c) ? f[c] : 0; + return Math.Min(Math.Min(Math.Min(get('b'), get('a')), Math.Min(get('l') / 2, get('o') / 2)), get('n')); + } +} diff --git a/tests/1001-1500/1189. maximum-number-of-balloons/sol.dart b/tests/1001-1500/1189. maximum-number-of-balloons/sol.dart new file mode 100644 index 00000000..784b4d23 --- /dev/null +++ b/tests/1001-1500/1189. maximum-number-of-balloons/sol.dart @@ -0,0 +1,9 @@ +class Solution { + int maxNumberOfBalloons(String text) { + var f = {}; + for (var c in text.split('')) { + f[c] = (f[c] ?? 0) + 1; + } + return [f['b'] ?? 0, f['a'] ?? 0, (f['l'] ?? 0) ~/ 2, (f['o'] ?? 0) ~/ 2, f['n'] ?? 0].reduce((a, b) => a < b ? a : b); + } +} diff --git a/tests/1001-1500/1189. maximum-number-of-balloons/sol.go b/tests/1001-1500/1189. maximum-number-of-balloons/sol.go new file mode 100644 index 00000000..a879ff47 --- /dev/null +++ b/tests/1001-1500/1189. maximum-number-of-balloons/sol.go @@ -0,0 +1,7 @@ +func maxNumberOfBalloons(text string) int { + f := make(map[rune]int) + for _, c := range text { + f[c]++ + } + return min(f['b'], f['a'], f['l']/2, f['o']/2, f['n']) +} diff --git a/tests/1001-1500/1189. maximum-number-of-balloons/sol.java b/tests/1001-1500/1189. maximum-number-of-balloons/sol.java new file mode 100644 index 00000000..68c49e52 --- /dev/null +++ b/tests/1001-1500/1189. maximum-number-of-balloons/sol.java @@ -0,0 +1,9 @@ +class Solution { + public int maxNumberOfBalloons(String text) { + int[] f = new int[26]; + for (char c : text.toCharArray()) { + f[c - 'a']++; + } + return Math.min(Math.min(Math.min(f['b' - 'a'], f['a' - 'a']), Math.min(f['l' - 'a'] / 2, f['o' - 'a'] / 2)), f['n' - 'a']); + } +} diff --git a/tests/1001-1500/1189. maximum-number-of-balloons/sol.kt b/tests/1001-1500/1189. maximum-number-of-balloons/sol.kt new file mode 100644 index 00000000..54237556 --- /dev/null +++ b/tests/1001-1500/1189. maximum-number-of-balloons/sol.kt @@ -0,0 +1,9 @@ +class Solution { + fun maxNumberOfBalloons(text: String): Int { + val f = IntArray(26) + for (c in text) { + f[c - 'a']++ + } + return minOf(f['b' - 'a'], f['a' - 'a'], f['l' - 'a'] / 2, f['o' - 'a'] / 2, f['n' - 'a']) + } +} diff --git a/tests/1001-1500/1189. maximum-number-of-balloons/sol.py b/tests/1001-1500/1189. maximum-number-of-balloons/sol.py new file mode 100644 index 00000000..2b3ab75b --- /dev/null +++ b/tests/1001-1500/1189. maximum-number-of-balloons/sol.py @@ -0,0 +1,4 @@ +class Solution: + def maxNumberOfBalloons(self, text: str) -> int: + f = Counter(text) + return min(f["b"], f["a"], f["l"] >> 1, f["o"] >> 1, f["n"]) diff --git a/tests/1001-1500/1189. maximum-number-of-balloons/sol.py2 b/tests/1001-1500/1189. maximum-number-of-balloons/sol.py2 new file mode 100644 index 00000000..45948c40 --- /dev/null +++ b/tests/1001-1500/1189. maximum-number-of-balloons/sol.py2 @@ -0,0 +1,10 @@ +class Solution(object): + def maxNumberOfBalloons(self, text): + """ + :type text: str + :rtype: int + """ + f = {} + for c in text: + f[c] = f.get(c, 0) + 1 + return min(f.get("b", 0), f.get("a", 0), f.get("l", 0) // 2, f.get("o", 0) // 2, f.get("n", 0)) diff --git a/tests/1001-1500/1189. maximum-number-of-balloons/sol.rb b/tests/1001-1500/1189. maximum-number-of-balloons/sol.rb new file mode 100644 index 00000000..8eb4218e --- /dev/null +++ b/tests/1001-1500/1189. maximum-number-of-balloons/sol.rb @@ -0,0 +1,7 @@ +# @param {String} text +# @return {Integer} +def max_number_of_balloons(text) + f = Hash.new(0) + text.each_char { |c| f[c] += 1 } + [f["b"], f["a"], f["l"] / 2, f["o"] / 2, f["n"]].min +end diff --git a/tests/1001-1500/1189. maximum-number-of-balloons/sol.rs b/tests/1001-1500/1189. maximum-number-of-balloons/sol.rs new file mode 100644 index 00000000..a2bafaaa --- /dev/null +++ b/tests/1001-1500/1189. maximum-number-of-balloons/sol.rs @@ -0,0 +1,10 @@ +impl Solution { + pub fn max_number_of_balloons(text: String) -> i32 { + let mut f = std::collections::HashMap::new(); + for c in text.chars() { + *f.entry(c).or_insert(0) += 1; + } + let get = |c| *f.get(&c).unwrap_or(&0); + *[get('b'), get('a'), get('l') / 2, get('o') / 2, get('n')].iter().min().unwrap() + } +} diff --git a/tests/1001-1500/1189. maximum-number-of-balloons/sol.swift b/tests/1001-1500/1189. maximum-number-of-balloons/sol.swift new file mode 100644 index 00000000..985a5e9c --- /dev/null +++ b/tests/1001-1500/1189. maximum-number-of-balloons/sol.swift @@ -0,0 +1,9 @@ +class Solution { + func maxNumberOfBalloons(_ text: String) -> Int { + var f: [Character: Int] = [:] + for c in text { + f[c, default: 0] += 1 + } + return min(f["b"] ?? 0, f["a"] ?? 0, (f["l"] ?? 0) / 2, (f["o"] ?? 0) / 2, f["n"] ?? 0) + } +} diff --git a/tests/1001-1500/1189. maximum-number-of-balloons/sol.ts b/tests/1001-1500/1189. maximum-number-of-balloons/sol.ts new file mode 100644 index 00000000..a50ec44c --- /dev/null +++ b/tests/1001-1500/1189. maximum-number-of-balloons/sol.ts @@ -0,0 +1,13 @@ +function maxNumberOfBalloons(text: string): number { + const f: Record = {}; + for (const c of text) { + f[c] = (f[c] || 0) + 1; + } + return Math.min( + f["b"] || 0, + f["a"] || 0, + (f["l"] || 0) >> 1, + (f["o"] || 0) >> 1, + f["n"] || 0, + ); +} diff --git a/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/manifest.yaml b/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/manifest.yaml new file mode 100644 index 00000000..e8307210 --- /dev/null +++ b/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/manifest.yaml @@ -0,0 +1,206 @@ +entry: + id: 1190 + title: reverse-substrings-between-each-pair-of-parentheses + params: + s: + type: string + call: + cpp: "Solution().reverseParentheses({s})" + rust: "Solution::reverse_parentheses({s})" + python3: "Solution().reverseParentheses({s})" + python2: "Solution().reverseParentheses({s})" + ruby: "reverse_parentheses({s})" + java: "new Solution().reverseParentheses({s})" + csharp: "new Solution().ReverseParentheses({s})" + kotlin: "Solution().reverseParentheses({s})" + go: "reverseParentheses({s})" + dart: "Solution().reverseParentheses({s})" + swift: "Solution().reverseParentheses({s})" + typescript: "reverseParentheses({s})" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().reverseParentheses(s, {result})" + checker: | + class Checker: + def reverseParentheses(self, s, result): + parts = [[]] + for char in s: + if char == '(': + parts.append([]) + elif char == ')': + if len(parts) == 1: + return False + parts[-1].reverse() + parts[-2].extend(parts.pop()) + elif 'a' <= char <= 'z': + parts[-1].append(char) + else: + return False + return len(parts) == 1 and result == ''.join(parts[0]) +seed: 1190 +tests: + - name: prompt-example-one + in: + s: "(abcd)" + out: "dcba" + - name: prompt-example-two + in: + s: "(u(love)i)" + out: "iloveu" + - name: prompt-example-three + in: + s: "(ed(et(oc))el)" + out: "leetcode" + - name: no-parentheses + in: + s: "abcdef" + out: "abcdef" + - name: single-plain-letter + in: + s: "a" + out: "a" + - name: empty-pair + in: + s: "()" + out: "" + - name: single-letter-pair + in: + s: "(a)" + out: "a" + - name: adjacent-pairs + in: + s: "(ab)(cd)" + out: "badc" + - name: outside-text + in: + s: "a(bc)d" + out: "acbd" + - name: pair-at-end + in: + s: "abc(def)" + out: "abcfed" + - name: pair-at-start + in: + s: "(abc)def" + out: "cbadef" + - name: only-nested-empty-pairs + in: + s: "((()))" + out: "" + - name: nested-two-levels + in: + s: "(a(bc)d)" + out: "dbca" + - name: triple-nested-word + in: + s: "(a(b(cde)f)g)" + out: "gbedcfa" + - name: nested-with-prefix-and-suffix + in: + s: "x(y(z)w)v" + out: "xwzyv" + - name: double-reversal-cancels + in: + s: "((abc))" + out: "abc" + - name: four-reversals-cancel + in: + s: "((((abcd))))" + out: "abcd" + - name: alternating-groups + in: + s: "a(b)c(d)e(f)g" + out: "abcdefg" + - name: repeated-letters + in: + s: "(aaaa)(bbbb)" + out: "aaaabbbb" + - name: palindrome-group + in: + s: "(abccba)" + out: "abccba" + - name: odd-palindrome-group + in: + s: "(abcba)" + out: "abcba" + - name: adjacent-nested-and-flat-pairs + in: + s: "(ab(cd)ef)(gh)" + out: "fecdbahg" + - name: sibling-nested-pairs + in: + s: "(a(b)c(d)e)" + out: "edcba" + - name: empty-pairs-between-text + in: + s: "x()y()z" + out: "xyz" + - name: full-alphabet-reversal + in: + s: "(abcdefghijklmnopqrstuvwxyz)" + out: "zyxwvutsrqponmlkjihgfedcba" + - name: long-outside-text + in: + s: "abcdefghijklmnopqrstuvwxyz(abcd)zyxwvutsrqponmlkjihgfedcba" + out: "abcdefghijklmnopqrstuvwxyzdcbazyxwvutsrqponmlkjihgfedcba" + - name: deep-single-letters + in: + s: "(a(b(c(d(e)f)g)h)i)" + out: "ibgdefcha" + - name: deep-words + in: + s: "(one(two(three(four)five)six)seven)" + out: "nevestwoeviffoureerhtsixeno" + - name: nested-adjacent-pairs + in: + s: "((ab)(cd))" + out: "cdab" + - name: mixed-nesting-and-siblings + in: + s: "a(b(cd)e)f(g)h" + out: "aecdbfgh" + - name: many-adjacent-singletons + in: + s: "(a)(b)(c)(d)(e)(f)(g)(h)" + out: "abcdefgh" + - name: nested-empty-middle + in: + s: "(ab(()cd)ef)" + out: "fecdba" + - name: repeated-nesting + in: + s: "(a(a(a(a(a)))))" + out: "aaaaa" + - name: no-parentheses-longer-text + in: + s: "thequickbrownfoxjumpsoverthelazydog" + out: "thequickbrownfoxjumpsoverthelazydog" + - name: broad-nested-siblings + in: + s: "(alpha(beta(gamma)delta)epsilon(zeta))" + out: "zetanolispebetaammagdeltaahpla" + - name: empty-pairs-around-content + in: + s: "()(ab)()" + out: "ba" + - name: increasing-pair-widths + in: + s: "(a)(bc)(def)" + out: "acbfed" + - name: three-sibling-pairs-inside-parent + in: + s: "((a)(b)(c))" + out: "cba" + - name: nested-pairs-between-outer-text + in: + s: "a((bc)d(ef))g" + out: "aefdbcg" + - name: four-level-mixed-structure + in: + s: "((ab)c(de(fg)h)i)" + out: "idegfhcab" diff --git a/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.cpp b/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.cpp new file mode 100644 index 00000000..97a43b4f --- /dev/null +++ b/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + string reverseParentheses(string s) { + i = 0; + return helper(s); + } + +private: + int i; + + string helper(const string& s) { + string ans; + while (i < s.size()) { + if (s[i] == '(') { + i++; + ans += helper(s); + } else if (s[i] == ')') { + i++; + reverse(ans.begin(), ans.end()); + return ans; + } else { + ans += s[i]; + i++; + } + } + return ans; + } +}; diff --git a/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.cs b/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.cs new file mode 100644 index 00000000..9d7f3be4 --- /dev/null +++ b/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.cs @@ -0,0 +1,27 @@ +public class Solution { + private int i; + + public string ReverseParentheses(string s) { + i = 0; + return Helper(s); + } + + private string Helper(string s) { + var ans = new System.Text.StringBuilder(); + while (i < s.Length) { + if (s[i] == '(') { + i++; + ans.Append(Helper(s)); + } else if (s[i] == ')') { + i++; + var charArray = ans.ToString().ToCharArray(); + System.Array.Reverse(charArray); + return new string(charArray); + } else { + ans.Append(s[i]); + i++; + } + } + return ans.ToString(); + } +} diff --git a/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.dart b/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.dart new file mode 100644 index 00000000..083ed9eb --- /dev/null +++ b/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.dart @@ -0,0 +1,25 @@ +class Solution { + int i = 0; + + String reverseParentheses(String s) { + i = 0; + return helper(s); + } + + String helper(String s) { + String ans = ""; + while (i < s.length) { + if (s[i] == '(') { + i++; + ans += helper(s); + } else if (s[i] == ')') { + i++; + return ans.split('').reversed.join(''); + } else { + ans += s[i]; + i++; + } + } + return ans; + } +} diff --git a/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.go b/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.go new file mode 100644 index 00000000..2981e8eb --- /dev/null +++ b/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.go @@ -0,0 +1,29 @@ +func reverseParentheses(s string) string { + i := 0 + var helper func() string + helper = func() string { + ans := "" + for i < len(s) { + if s[i] == '(' { + i++ + ans += helper() + } else if s[i] == ')' { + i++ + return reverseString(ans) + } else { + ans += string(s[i]) + i++ + } + } + return ans + } + return helper() +} + +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) +} diff --git a/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.java b/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.java new file mode 100644 index 00000000..ab0097ff --- /dev/null +++ b/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.java @@ -0,0 +1,25 @@ +class Solution { + private int i; + + public String reverseParentheses(String s) { + i = 0; + return helper(s); + } + + private String helper(String s) { + StringBuilder ans = new StringBuilder(); + while (i < s.length()) { + if (s.charAt(i) == '(') { + i++; + ans.append(helper(s)); + } else if (s.charAt(i) == ')') { + i++; + return ans.reverse().toString(); + } else { + ans.append(s.charAt(i)); + i++; + } + } + return ans.toString(); + } +} diff --git a/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.kt b/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.kt new file mode 100644 index 00000000..c57783e9 --- /dev/null +++ b/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.kt @@ -0,0 +1,29 @@ +class Solution { + private var i = 0 + + fun reverseParentheses(s: String): String { + i = 0 + return helper(s) + } + + private fun helper(s: String): String { + val ans = StringBuilder() + while (i < s.length) { + when (s[i]) { + '(' -> { + i++ + ans.append(helper(s)) + } + ')' -> { + i++ + return ans.reverse().toString() + } + else -> { + ans.append(s[i]) + i++ + } + } + } + return ans.toString() + } +} diff --git a/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.py b/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.py new file mode 100644 index 00000000..18a369a8 --- /dev/null +++ b/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.py @@ -0,0 +1,28 @@ +class Solution: + def reverseParentheses(self, s: str) -> str: + self.i: int = 0 + return self.helper(s) + + def helper(self, s: str) -> str: + size: int = len(s) + ans: str = "" + + while self.i < size: + if s[self.i] == "(": + self.i += 1 + ans += self.helper(s) + elif s[self.i] == ")": + self.i += 1 + return self.rev(ans) + else: + ans += s[self.i] + self.i += 1 + + return ans + + def rev(self, s: str) -> str: + r: str = "" + for i in range(0, len(s)): + r = s[i] + r + + return r diff --git a/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.py2 b/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.py2 new file mode 100644 index 00000000..176e9900 --- /dev/null +++ b/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.py2 @@ -0,0 +1,31 @@ +class Solution(object): + def reverseParentheses(self, s): + """ + :type s: str + :rtype: str + """ + self.i = 0 + return self.helper(s) + + def helper(self, s): + size = len(s) + ans = "" + + while self.i < size: + if s[self.i] == '(': + self.i += 1 + ans += self.helper(s) + elif s[self.i] == ')': + self.i += 1 + return self.rev(ans) + else: + ans += s[self.i] + self.i += 1 + + return ans + + def rev(self, s): + r = "" + for i in range(0, len(s)): + r = s[i] + r + return r diff --git a/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.rb b/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.rb new file mode 100644 index 00000000..28fa878c --- /dev/null +++ b/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.rb @@ -0,0 +1,23 @@ +# @param {String} s +# @return {String} +def reverse_parentheses(s) + @i = 0 + helper(s) +end + +def helper(s) + ans = "" + while @i < s.length + if s[@i] == '(' + @i += 1 + ans += helper(s) + elsif s[@i] == ')' + @i += 1 + return ans.reverse + else + ans += s[@i] + @i += 1 + end + end + ans +end diff --git a/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.rs b/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.rs new file mode 100644 index 00000000..0bb31baf --- /dev/null +++ b/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.rs @@ -0,0 +1,24 @@ +impl Solution { + pub fn reverse_parentheses(s: String) -> String { + let chars: Vec = s.chars().collect(); + let mut i: usize = 0; + Self::helper(&chars, &mut i) + } + + fn helper(s: &Vec, i: &mut usize) -> String { + let mut ans = String::new(); + while *i < s.len() { + if s[*i] == '(' { + *i += 1; + ans.push_str(&Self::helper(s, i)); + } else if s[*i] == ')' { + *i += 1; + return ans.chars().rev().collect(); + } else { + ans.push(s[*i]); + *i += 1; + } + } + ans + } +} diff --git a/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.swift b/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.swift new file mode 100644 index 00000000..9d6856ba --- /dev/null +++ b/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.swift @@ -0,0 +1,25 @@ +class Solution { + var i = 0 + + func reverseParentheses(_ s: String) -> String { + i = 0 + return helper(Array(s)) + } + + private func helper(_ s: [Character]) -> String { + var ans = "" + while i < s.count { + if s[i] == "(" { + i += 1 + ans += helper(s) + } else if s[i] == ")" { + i += 1 + return String(ans.reversed()) + } else { + ans.append(s[i]) + i += 1 + } + } + return ans + } +} diff --git a/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.ts b/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.ts new file mode 100644 index 00000000..c33e434b --- /dev/null +++ b/tests/1001-1500/1190. reverse-substrings-between-each-pair-of-parentheses/sol.ts @@ -0,0 +1,22 @@ +function reverseParentheses(s: string): string { + let i = 0; + + function helper(): string { + let ans = ""; + while (i < s.length) { + if (s[i] === "(") { + i++; + ans += helper(); + } else if (s[i] === ")") { + i++; + return ans.split("").reverse().join(""); + } else { + ans += s[i]; + i++; + } + } + return ans; + } + + return helper(); +} diff --git a/tests/1001-1500/1191. k-concatenation-maximum-sum/manifest.yaml b/tests/1001-1500/1191. k-concatenation-maximum-sum/manifest.yaml new file mode 100644 index 00000000..dcd6c34b --- /dev/null +++ b/tests/1001-1500/1191. k-concatenation-maximum-sum/manifest.yaml @@ -0,0 +1,317 @@ +entry: + id: 1191 + title: "k-concatenation-maximum-sum" + params: + arr: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().kConcatenationMaxSum({arr}, {k})" + rust: "Solution::k_concatenation_max_sum({arr}, {k})" + python3: "Solution().kConcatenationMaxSum({arr}, {k})" + python2: "Solution().kConcatenationMaxSum({arr}, {k})" + ruby: "k_concatenation_max_sum({arr}, {k})" + java: "new Solution().kConcatenationMaxSum({arr}, {k})" + csharp: "new Solution().KConcatenationMaxSum({arr}, {k})" + kotlin: "Solution().kConcatenationMaxSum({arr}, {k})" + go: "kConcatenationMaxSum({arr}, {k})" + dart: "Solution().kConcatenationMaxSum({arr}, {k})" + swift: "Solution().kConcatenationMaxSum({arr}, {k})" + typescript: "kConcatenationMaxSum({arr}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 700 + memory_mb: 300 + +oracle: + python3: + call: "Checker().kConcatenationMaxSum(arr, k, {result})" + checker: | + class Checker: + def kConcatenationMaxSum(self, arr, k, result): + if not isinstance(result, int) or isinstance(result, bool) or not arr or k < 1: + return False + def kadane(values): + best = 0 + current = 0 + for value in values: + current = max(0, current + value) + best = max(best, current) + return best + mod = 1000000007 + if k <= 3: + expected = kadane(arr * k) % mod + else: + expected = max((max(0, sum(arr) * (k - 1)) % mod) + kadane(arr), kadane(arr * 2)) + return result == expected + +seed: 119100 + +tests: + - name: "example_one" + in: + arr: [1, 2] + k: 3 + out: 9 + - name: "example_two" + in: + arr: [1, -2, 1] + k: 5 + out: 2 + - name: "example_three" + in: + arr: [-1, -2] + k: 7 + out: 0 + - name: "single_positive" + in: + arr: [5] + k: 1 + out: 5 + - name: "single_negative_large_k" + in: + arr: [-5] + k: 100000 + out: 0 + - name: "single_zero" + in: + arr: [0] + k: 10 + out: 0 + - name: "k_one" + in: + arr: [1] + k: 1 + out: 1 + - name: "opposite_pair" + in: + arr: [-1, 1] + k: 2 + out: 1 + - name: "positive_then_negative" + in: + arr: [1, -1] + k: 100 + out: 1 + - name: "three_element_peak" + in: + arr: [2, -1, 2] + k: 3 + out: 9 + - name: "negative_prefix" + in: + arr: [-2, 3, -1] + k: 4 + out: 3 + - name: "two_copies" + in: + arr: [5, -10, 5] + k: 2 + out: 10 + - name: "positive_total" + in: + arr: [10, -1, -1] + k: 5 + out: 42 + - name: "negative_total" + in: + arr: [-10, 1, 1] + k: 5 + out: 2 + - name: "maximum_values" + in: + arr: [10000, 10000] + k: 100000 + out: 999999993 + - name: "mixed_boundary_values" + in: + arr: [-10000, 10000] + k: 100000 + out: 10000 + - name: "balanced_five" + in: + arr: [1, -2, 3, -2, 1] + k: 2 + out: 4 + - name: "k_one_mixed" + in: + arr: [3, -1, 3] + k: 1 + out: 5 + - name: "alternating_negative" + in: + arr: [-3, 1, -3, 1] + k: 4 + out: 1 + - name: "two_positive_pairs" + in: + arr: [2, 2, -10, 2] + k: 6 + out: 6 + - name: "equal_edges" + in: + arr: [4, -1, -1, 4] + k: 3 + out: 18 + - name: "small_positive_total" + in: + arr: [-1, 2, -1] + k: 10 + out: 2 + - name: "repeated_positive" + in: + arr: [1, 1, -1, 1] + k: 4 + out: 8 + - name: "isolated_peak" + in: + arr: [-2, -2, 5, -2] + k: 2 + out: 5 + - name: "three_element_mixed" + in: + arr: [7, -3, 4] + k: 3 + out: 24 + - name: "negative_edges" + in: + arr: [-5, 2, 2, -5] + k: 5 + out: 4 + - name: "alternating_zero_total" + in: + arr: [1, -1, 1, -1] + k: 7 + out: 1 + - name: "large_alternating" + in: + arr: [6, -5, 6, -5] + k: 2 + out: 9 + - name: "large_positive_modulo" + in: + arr: [10000, -10000, 10000] + k: 100000 + out: 1000000000 + - name: "large_negative_total" + in: + arr: [-10000, -9999] + k: 99999 + out: 0 + - name: "positive_sum_five" + in: + arr: [9, -8, 9] + k: 4 + out: 40 + - name: "positive_islands" + in: + arr: [1, 2, -10, 1, 2] + k: 5 + out: 6 + - name: "mostly_negative" + in: + arr: [-1, -1, 3, -1] + k: 3 + out: 3 + - name: "alternating_peaks" + in: + arr: [2, -5, 2, -5, 2] + k: 8 + out: 4 + - name: "maximum_edge_sum" + in: + arr: [10000, -1, -1, -1, 10000] + k: 100000 + out: 999699993 + - name: "generated_short" + seed: 119101 + in: + arr: + gen: "array" + len: + gen: "int" + min: 1 + max: 20 + of: + gen: "int" + min: -10000 + max: 10000 + distinct: false + sorted: false + k: + gen: "int" + min: 1 + max: 10 + - name: "generated_medium" + seed: 119102 + in: + arr: + gen: "array" + len: + gen: "int" + min: 50 + max: 200 + of: + gen: "int" + min: -10000 + max: 10000 + distinct: false + sorted: false + k: + gen: "int" + min: 1 + max: 1000 + - name: "generated_negative" + seed: 119103 + in: + arr: + gen: "array" + len: 1000 + of: + gen: "int" + min: -10000 + max: -1 + distinct: false + sorted: false + k: + gen: "int" + min: 1 + max: 100000 + - name: "generated_large" + seed: 119104 + in: + arr: + gen: "array" + len: 10000 + of: + gen: "int" + min: -10000 + max: 10000 + distinct: false + sorted: false + k: + gen: "int" + min: 1 + max: 100000 + - name: "generated_maximum" + seed: 119105 + in: + arr: + gen: "array" + len: 100000 + of: + gen: "int" + min: -10000 + max: 10000 + distinct: false + sorted: false + k: + gen: "int" + min: 1 + max: 100000 diff --git a/tests/1001-1500/1191. k-concatenation-maximum-sum/sol.cpp b/tests/1001-1500/1191. k-concatenation-maximum-sum/sol.cpp new file mode 100644 index 00000000..f7054843 --- /dev/null +++ b/tests/1001-1500/1191. k-concatenation-maximum-sum/sol.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + int kConcatenationMaxSum(vector& arr, int k) { + const int MOD = 1000000007; + + auto kadanes = [](const vector& nums) -> long long { + long long best = 0; + long long total = 0; + for (int x : nums) { + total += x; + if (total < 0) total = 0; + best = max(best, total); + } + return best; + }; + + if (k <= 3) { + vector extended; + extended.reserve(arr.size() * k); + for (int i = 0; i < k; ++i) { + extended.insert(extended.end(), arr.begin(), arr.end()); + } + return (int)(kadanes(extended) % MOD); + } + + long long sum = 0; + for (int x : arr) sum += x; + long long s = max(0LL, sum * (k - 1)) % MOD; + + vector doubleArr; + doubleArr.reserve(arr.size() * 2); + doubleArr.insert(doubleArr.end(), arr.begin(), arr.end()); + doubleArr.insert(doubleArr.end(), arr.begin(), arr.end()); + + return (int)(max(s + kadanes(arr), kadanes(doubleArr)) % MOD); + } +}; diff --git a/tests/1001-1500/1191. k-concatenation-maximum-sum/sol.cs b/tests/1001-1500/1191. k-concatenation-maximum-sum/sol.cs new file mode 100644 index 00000000..af2ebcb0 --- /dev/null +++ b/tests/1001-1500/1191. k-concatenation-maximum-sum/sol.cs @@ -0,0 +1,35 @@ +public class Solution { + public int KConcatenationMaxSum(int[] arr, int k) { + const int MOD = 1000000007; + + long Kadanes(int[] nums) { + long best = 0; + long total = 0; + foreach (int x in nums) { + total += x; + if (total < 0) total = 0; + best = Math.Max(best, total); + } + return best; + } + + if (k <= 3) { + int[] extended = new int[arr.Length * k]; + for (int i = 0; i < extended.Length; i++) { + extended[i] = arr[i % arr.Length]; + } + return (int)(Kadanes(extended) % MOD); + } + + long sum = 0; + foreach (int x in arr) sum += x; + long s = Math.Max(0, sum * (k - 1)) % MOD; + + int[] doubleArr = new int[arr.Length * 2]; + for (int i = 0; i < doubleArr.Length; i++) { + doubleArr[i] = arr[i % arr.Length]; + } + + return (int)(Math.Max(s + Kadanes(arr), Kadanes(doubleArr)) % MOD); + } +} diff --git a/tests/1001-1500/1191. k-concatenation-maximum-sum/sol.dart b/tests/1001-1500/1191. k-concatenation-maximum-sum/sol.dart new file mode 100644 index 00000000..778a4abe --- /dev/null +++ b/tests/1001-1500/1191. k-concatenation-maximum-sum/sol.dart @@ -0,0 +1,33 @@ +class Solution { + int kConcatenationMaxSum(List arr, int k) { + const MOD = 1000000007; + + int kadanes(List nums) { + int best = 0; + int total = 0; + for (int x in nums) { + total += x; + if (total < 0) total = 0; + if (total > best) best = total; + } + return best; + } + + if (k <= 3) { + List extended = []; + for (int i = 0; i < k; i++) { + extended.addAll(arr); + } + return kadanes(extended) % MOD; + } + + int sum = arr.fold(0, (a, b) => a + b); + int s = sum > 0 ? (sum * (k - 1)) % MOD : 0; + + List doubleArr = [...arr, ...arr]; + + int v1 = s + kadanes(arr); + int v2 = kadanes(doubleArr); + return (v1 > v2 ? v1 : v2) % MOD; + } +} diff --git a/tests/1001-1500/1191. k-concatenation-maximum-sum/sol.go b/tests/1001-1500/1191. k-concatenation-maximum-sum/sol.go new file mode 100644 index 00000000..e7795c9b --- /dev/null +++ b/tests/1001-1500/1191. k-concatenation-maximum-sum/sol.go @@ -0,0 +1,47 @@ +func kConcatenationMaxSum(arr []int, k int) int { + const MOD = 1000000007 + + kadanes := func(nums []int) int64 { + var best int64 = 0 + var total int64 = 0 + for _, x := range nums { + total += int64(x) + if total < 0 { + total = 0 + } + if total > best { + best = total + } + } + return best + } + + if k <= 3 { + extended := make([]int, len(arr)*k) + for i := range extended { + extended[i] = arr[i%len(arr)] + } + return int(kadanes(extended) % MOD) + } + + var sum int64 = 0 + for _, x := range arr { + sum += int64(x) + } + s := int64(0) + if sum > 0 { + s = (sum * int64(k-1)) % MOD + } + + doubleArr := make([]int, len(arr)*2) + for i := range doubleArr { + doubleArr[i] = arr[i%len(arr)] + } + + v1 := s + kadanes(arr) + v2 := kadanes(doubleArr) + if v1 > v2 { + return int(v1 % MOD) + } + return int(v2 % MOD) +} diff --git a/tests/1001-1500/1191. k-concatenation-maximum-sum/sol.java b/tests/1001-1500/1191. k-concatenation-maximum-sum/sol.java new file mode 100644 index 00000000..c40e503d --- /dev/null +++ b/tests/1001-1500/1191. k-concatenation-maximum-sum/sol.java @@ -0,0 +1,35 @@ +class Solution { + public int kConcatenationMaxSum(int[] arr, int k) { + final int MOD = 1000000007; + + if (k <= 3) { + int[] extended = new int[arr.length * k]; + for (int i = 0; i < extended.length; i++) { + extended[i] = arr[i % arr.length]; + } + return (int)(kadanes(extended) % MOD); + } + + long sum = 0; + for (int x : arr) sum += x; + long s = Math.max(0, sum * (k - 1)) % MOD; + + int[] doubleArr = new int[arr.length * 2]; + for (int i = 0; i < doubleArr.length; i++) { + doubleArr[i] = arr[i % arr.length]; + } + + return (int)(Math.max(s + kadanes(arr), kadanes(doubleArr)) % MOD); + } + + private long kadanes(int[] nums) { + long best = 0; + long total = 0; + for (int x : nums) { + total += x; + if (total < 0) total = 0; + best = Math.max(best, total); + } + return best; + } +} diff --git a/tests/1001-1500/1191. k-concatenation-maximum-sum/sol.kt b/tests/1001-1500/1191. k-concatenation-maximum-sum/sol.kt new file mode 100644 index 00000000..3d9b94ba --- /dev/null +++ b/tests/1001-1500/1191. k-concatenation-maximum-sum/sol.kt @@ -0,0 +1,28 @@ +class Solution { + fun kConcatenationMaxSum(arr: IntArray, k: Int): Int { + val MOD = 1000000007 + + fun kadanes(nums: IntArray): Long { + var best = 0L + var total = 0L + for (x in nums) { + total += x + if (total < 0) total = 0 + best = maxOf(best, total) + } + return best + } + + if (k <= 3) { + val extended = IntArray(arr.size * k) { arr[it % arr.size] } + return (kadanes(extended) % MOD).toInt() + } + + val sum = arr.fold(0L) { acc, x -> acc + x } + val s = maxOf(0L, sum * (k - 1)) % MOD + + val doubleArr = IntArray(arr.size * 2) { arr[it % arr.size] } + + return (maxOf(s + kadanes(arr), kadanes(doubleArr)) % MOD).toInt() + } +} diff --git a/tests/1001-1500/1191. k-concatenation-maximum-sum/sol.py b/tests/1001-1500/1191. k-concatenation-maximum-sum/sol.py new file mode 100644 index 00000000..7862ce22 --- /dev/null +++ b/tests/1001-1500/1191. k-concatenation-maximum-sum/sol.py @@ -0,0 +1,22 @@ +class Solution: + def kConcatenationMaxSum(self, arr: List[int], k: int) -> int: + MOD = 10**9 + 7 + + def kadanes(nums): + + best = 0 + total = 0 + for x in nums: + total += x + if total < 0: + total = 0 + best = max(best, total) + return best + + best = 0 + + if k <= 3: + return (kadanes(arr * k)) % MOD + + s = max(0, (sum(arr) * (k - 1))) % MOD + return max(s + kadanes(arr), kadanes(arr * 2)) diff --git a/tests/1001-1500/1191. k-concatenation-maximum-sum/sol.py2 b/tests/1001-1500/1191. k-concatenation-maximum-sum/sol.py2 new file mode 100644 index 00000000..d300fc58 --- /dev/null +++ b/tests/1001-1500/1191. k-concatenation-maximum-sum/sol.py2 @@ -0,0 +1,23 @@ +class Solution(object): + def kConcatenationMaxSum(self, arr, k): + """ + :type arr: List[int] + :type k: int + :rtype: int + """ + MOD = 10 ** 9 + 7 + def kadanes(nums): + best = 0 + total = 0 + for x in nums: + total += x + if total < 0: + total = 0 + best = max(best, total) + return best + + if k <= 3: + return kadanes(arr * k) % MOD + + s = max(0, (sum(arr) * (k-1))) % MOD + return max(s + kadanes(arr), kadanes(arr * 2)) % MOD diff --git a/tests/1001-1500/1191. k-concatenation-maximum-sum/sol.rb b/tests/1001-1500/1191. k-concatenation-maximum-sum/sol.rb new file mode 100644 index 00000000..82e273a9 --- /dev/null +++ b/tests/1001-1500/1191. k-concatenation-maximum-sum/sol.rb @@ -0,0 +1,23 @@ +# @param {Integer[]} arr +# @param {Integer} k +# @return {Integer} +def k_concatenation_max_sum(arr, k) + mod = 10**9 + 7 + kadanes = ->(nums) { + best = 0 + total = 0 + nums.each do |x| + total += x + total = 0 if total < 0 + best = [best, total].max + end + best + } + + if k <= 3 + return kadanes.call(arr * k) % mod + end + + s = [0, (arr.sum * (k-1))].max % mod + [s + kadanes.call(arr), kadanes.call(arr * 2)].max % mod +end diff --git a/tests/1001-1500/1191. k-concatenation-maximum-sum/sol.rs b/tests/1001-1500/1191. k-concatenation-maximum-sum/sol.rs new file mode 100644 index 00000000..635c2dad --- /dev/null +++ b/tests/1001-1500/1191. k-concatenation-maximum-sum/sol.rs @@ -0,0 +1,34 @@ +impl Solution { + pub fn k_concatenation_max_sum(arr: Vec, k: i32) -> i32 { + const MOD: i64 = 1_000_000_007; + + fn kadanes(nums: &[i32]) -> i64 { + let mut best: i64 = 0; + let mut total: i64 = 0; + for &x in nums { + total += x as i64; + if total < 0 { + total = 0; + } + best = best.max(total); + } + best + } + + let k = k as usize; + + if k <= 3 { + let extended: Vec = arr.iter().cycle().take(arr.len() * k).copied().collect(); + return (kadanes(&extended) % MOD) as i32; + } + + let sum: i64 = arr.iter().map(|&x| x as i64).sum(); + let s = 0.max(sum * (k as i64 - 1)) % MOD; + + let double_arr: Vec = arr.iter().chain(arr.iter()).copied().collect(); + + let v1 = s + kadanes(&arr); + let v2 = kadanes(&double_arr); + (v1.max(v2) % MOD) as i32 + } +} diff --git a/tests/1001-1500/1191. k-concatenation-maximum-sum/sol.swift b/tests/1001-1500/1191. k-concatenation-maximum-sum/sol.swift new file mode 100644 index 00000000..4d422ae4 --- /dev/null +++ b/tests/1001-1500/1191. k-concatenation-maximum-sum/sol.swift @@ -0,0 +1,31 @@ +class Solution { + func kConcatenationMaxSum(_ arr: [Int], _ k: Int) -> Int { + let MOD = 1000000007 + + func kadanes(_ nums: [Int]) -> Int { + var best = 0 + var total = 0 + for x in nums { + total += x + if total < 0 { total = 0 } + best = max(best, total) + } + return best + } + + if k <= 3 { + var extended: [Int] = [] + for _ in 0.. { + let best = 0; + let total = 0; + for (const x of nums) { + total += x; + if (total < 0) total = 0; + best = Math.max(best, total); + } + return best; + }; + + if (k <= 3) { + const extended: number[] = []; + for (let i = 0; i < k; i++) { + extended.push(...arr); + } + return kadanes(extended) % MOD; + } + + const sum = arr.reduce((a, b) => a + b, 0); + const s = Math.max(0, sum * (k - 1)) % MOD; + + const doubleArr = [...arr, ...arr]; + + return Math.max(s + kadanes(arr), kadanes(doubleArr)) % MOD; +} diff --git a/tests/1001-1500/1192. critical-connections-in-a-network/manifest.yaml b/tests/1001-1500/1192. critical-connections-in-a-network/manifest.yaml new file mode 100644 index 00000000..ca863666 --- /dev/null +++ b/tests/1001-1500/1192. critical-connections-in-a-network/manifest.yaml @@ -0,0 +1,552 @@ +entry: + id: 1192 + title: "critical-connections-in-a-network" + params: + n: + type: int + connections: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().criticalConnections({n}, {connections})" + rust: "Solution::critical_connections({n}, {connections})" + python3: "Solution().criticalConnections({n}, {connections})" + python2: "Solution().criticalConnections({n}, {connections})" + ruby: "critical_connections({n}, {connections})" + java: "new Solution().criticalConnections({n}, {connections})" + csharp: "new Solution().CriticalConnections({n}, {connections})" + kotlin: "Solution().criticalConnections({n}, {connections})" + go: "criticalConnections({n}, {connections})" + dart: "Solution().criticalConnections({n}, {connections})" + swift: "Solution().criticalConnections({n}, {connections})" + typescript: "criticalConnections({n}, {connections})" + +judge: + type: "ignore_order" + +limits: + time_ms: 1000 + memory_mb: 400 + +oracle: + python3: + call: "Checker().criticalConnections(n, connections, {result})" + checker: | + class Checker: + def criticalConnections(self, n, connections, result): + if not isinstance(result, list): + return False + actual = set() + for edge in result: + if (not isinstance(edge, list) or len(edge) != 2 or + not all(isinstance(node, int) and not isinstance(node, bool) + for node in edge)): + return False + u, v = edge + if not (0 <= u < n and 0 <= v < n and u != v): + return False + normalized = tuple(sorted((u, v))) + if normalized in actual: + return False + actual.add(normalized) + original = {tuple(sorted((u, v))) for u, v in connections} + if not actual.issubset(original): + return False + graph = [[] for _ in range(n)] + for u, v in connections: + graph[u].append(v) + graph[v].append(u) + bridges = set() + for edge in original: + start, target = edge + seen = {start} + stack = [start] + while stack: + node = stack.pop() + for neighbor in graph[node]: + if tuple(sorted((node, neighbor))) == edge or neighbor in seen: + continue + seen.add(neighbor) + stack.append(neighbor) + if target not in seen: + bridges.add(edge) + return actual == bridges + +seed: 1192 + +tests: + - name: "example_one" + in: + n: 4 + connections: + - [0, 1] + - [1, 2] + - [2, 0] + - [1, 3] + - name: "example_two" + in: + n: 2 + connections: + - [0, 1] + - name: "triangle" + in: + n: 3 + connections: + - [0, 1] + - [1, 2] + - [2, 0] + - name: "path_three" + in: + n: 3 + connections: + - [0, 1] + - [1, 2] + - name: "path_four" + in: + n: 4 + connections: + - [0, 1] + - [1, 2] + - [2, 3] + - name: "square_cycle" + in: + n: 4 + connections: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 0] + - name: "cycle_with_tail" + in: + n: 5 + connections: + - [0, 1] + - [1, 2] + - [2, 0] + - [2, 3] + - [3, 4] + - name: "two_cycles_shared_vertex" + in: + n: 5 + connections: + - [0, 1] + - [1, 2] + - [2, 0] + - [0, 3] + - [3, 4] + - [4, 0] + - name: "diamond" + in: + n: 4 + connections: + - [0, 1] + - [1, 3] + - [3, 2] + - [2, 0] + - [0, 3] + - name: "complete_four" + in: + n: 4 + connections: + - [0, 1] + - [0, 2] + - [0, 3] + - [1, 2] + - [1, 3] + - [2, 3] + - name: "triangle_tail_two" + in: + n: 5 + connections: + - [0, 1] + - [1, 2] + - [2, 0] + - [2, 3] + - [2, 4] + - name: "star_four" + in: + n: 5 + connections: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - name: "star_with_leaf_cycle" + in: + n: 5 + connections: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [1, 2] + - name: "long_path_with_chord" + in: + n: 6 + connections: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [1, 4] + - name: "two_chords" + in: + n: 7 + connections: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [0, 3] + - [2, 5] + - name: "cycle_and_tail_chain" + in: + n: 8 + connections: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 0] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - name: "large_cycle" + in: + n: 8 + connections: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 0] + - name: "nested_cycles" + in: + n: 7 + connections: + - [0, 1] + - [1, 2] + - [2, 0] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 3] + - [5, 6] + - name: "dense_five" + in: + n: 5 + connections: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [1, 2] + - [1, 3] + - [1, 4] + - [2, 3] + - [2, 4] + - [3, 4] + - name: "path_with_end_cycle" + in: + n: 7 + connections: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [4, 6] + - name: "cycle_tail_branch" + in: + n: 9 + connections: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 0] + - [1, 4] + - [4, 5] + - [4, 6] + - [6, 7] + - [6, 8] + - name: "hub_with_two_triangles" + in: + n: 7 + connections: + - [0, 1] + - [1, 2] + - [2, 0] + - [0, 3] + - [3, 4] + - [4, 0] + - [0, 5] + - [5, 6] + - name: "five_edge_path" + in: + n: 6 + connections: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - name: "cycle_with_two_bridges" + in: + n: 6 + connections: + - [0, 1] + - [1, 2] + - [2, 0] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 3] + - name: "complete_six" + in: + n: 6 + connections: + - [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] + - name: "ladder_six" + in: + n: 6 + connections: + - [0, 1] + - [1, 2] + - [3, 4] + - [4, 5] + - [0, 3] + - [1, 4] + - [2, 5] + - name: "ladder_with_tail" + in: + n: 8 + connections: + - [0, 1] + - [1, 2] + - [3, 4] + - [4, 5] + - [0, 3] + - [1, 4] + - [2, 5] + - [5, 6] + - [6, 7] + - name: "cycle_with_parallel_routes" + in: + n: 8 + connections: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 0] + - [0, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 4] + - [2, 5] + - name: "deep_path_with_back_edge" + in: + n: 10 + connections: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [2, 8] + - name: "dense_with_tail" + in: + n: 7 + connections: + - [0, 1] + - [1, 2] + - [2, 0] + - [0, 3] + - [1, 3] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - name: "longer_ring_with_tail" + in: + n: 10 + connections: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 0] + - [4, 8] + - [2, 6] + - name: "hub_spokes_and_cycle" + in: + n: 9 + connections: + - [0, 1] + - [0, 2] + - [0, 3] + - [3, 4] + - [4, 5] + - [5, 3] + - [0, 6] + - [6, 7] + - [7, 8] + - name: "wide_tree" + in: + n: 10 + connections: + - [0, 1] + - [0, 2] + - [0, 3] + - [1, 4] + - [1, 5] + - [2, 6] + - [2, 7] + - [3, 8] + - [3, 9] + - name: "tree_with_three_cycles" + in: + n: 10 + connections: + - [0, 1] + - [1, 2] + - [2, 0] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 3] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 6] + - name: "large_hand_authored_chain" + in: + n: 12 + connections: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + - [10, 11] + - [2, 9] + - [4, 7] + - name: "two_complete_components_one_bridge" + in: + n: 8 + connections: + - [0, 1] + - [0, 2] + - [0, 3] + - [1, 2] + - [1, 3] + - [2, 3] + - [4, 5] + - [4, 6] + - [4, 7] + - [5, 6] + - [5, 7] + - [6, 7] + - [3, 4] + - name: "reversed_edges_cycle_with_two_leaves" + in: + n: 7 + connections: + - [1, 0] + - [2, 1] + - [0, 2] + - [3, 2] + - [4, 3] + - [5, 3] + - [6, 5] + - name: "three_cycles_connected_by_bridges" + in: + n: 11 + connections: + - [0, 1] + - [1, 2] + - [2, 0] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 3] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + - [10, 7] + - name: "three_by_three_grid" + in: + n: 9 + connections: + - [0, 1] + - [1, 2] + - [3, 4] + - [4, 5] + - [6, 7] + - [7, 8] + - [0, 3] + - [1, 4] + - [2, 5] + - [3, 6] + - [4, 7] + - [5, 8] + - name: "long_cycle_spine_with_branch_cycle" + in: + n: 14 + connections: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 0] + - [3, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 6] + - [8, 10] + - [10, 11] + - [11, 12] + - [12, 13] diff --git a/tests/1001-1500/1192. critical-connections-in-a-network/sol.cpp b/tests/1001-1500/1192. critical-connections-in-a-network/sol.cpp new file mode 100644 index 00000000..d8e1ae21 --- /dev/null +++ b/tests/1001-1500/1192. critical-connections-in-a-network/sol.cpp @@ -0,0 +1,52 @@ +class Solution { +public: + vector> criticalConnections(int n, vector>& connections) { + vector> graph(n); + for (auto& edge : connections) { + int u = edge[0], v = edge[1]; + graph[u].push_back(v); + graph[v].push_back(u); + } + + vector disc(n, -1), low(n, 0); + int timer = 0; + vector> bridges; + vector iterIdx(n, 0); + + for (int start = 0; start < n; start++) { + if (disc[start] != -1) continue; + + vector> stack; + disc[start] = low[start] = timer++; + stack.push_back({start, -1}); + + while (!stack.empty()) { + auto [node, parent] = stack.back(); + auto& neighbors = graph[node]; + + if (iterIdx[node] < neighbors.size()) { + int nb = neighbors[iterIdx[node]++]; + if (nb == parent) continue; + + if (disc[nb] == -1) { + disc[nb] = low[nb] = timer++; + stack.push_back({nb, node}); + } else { + low[node] = min(low[node], disc[nb]); + } + } else { + stack.pop_back(); + if (!stack.empty()) { + int par = stack.back().first; + low[par] = min(low[par], low[node]); + if (low[node] > disc[par]) { + bridges.push_back({par, node}); + } + } + } + } + } + + return bridges; + } +}; diff --git a/tests/1001-1500/1192. critical-connections-in-a-network/sol.cs b/tests/1001-1500/1192. critical-connections-in-a-network/sol.cs new file mode 100644 index 00000000..342b9f4e --- /dev/null +++ b/tests/1001-1500/1192. critical-connections-in-a-network/sol.cs @@ -0,0 +1,56 @@ +public class Solution { + public IList> CriticalConnections(int n, IList> connections) { + List[] graph = new List[n]; + for (int i = 0; i < n; i++) { + graph[i] = new List(); + } + foreach (var edge in connections) { + int u = edge[0], v = edge[1]; + graph[u].Add(v); + graph[v].Add(u); + } + + int[] disc = new int[n]; + int[] low = new int[n]; + Array.Fill(disc, -1); + int timer = 0; + IList> bridges = new List>(); + int[] iterIdx = new int[n]; + + for (int start = 0; start < n; start++) { + if (disc[start] != -1) continue; + + Stack<(int node, int parent)> stack = new Stack<(int, int)>(); + disc[start] = low[start] = timer++; + stack.Push((start, -1)); + + while (stack.Count > 0) { + var (node, parent) = stack.Peek(); + var neighbors = graph[node]; + + if (iterIdx[node] < neighbors.Count) { + int nb = neighbors[iterIdx[node]++]; + if (nb == parent) continue; + + if (disc[nb] == -1) { + disc[nb] = low[nb] = timer++; + stack.Push((nb, node)); + } else { + low[node] = Math.Min(low[node], disc[nb]); + } + } else { + stack.Pop(); + if (stack.Count > 0) { + int par = stack.Peek().node; + low[par] = Math.Min(low[par], low[node]); + if (low[node] > disc[par]) { + bridges.Add(new List { par, node }); + } + } + } + } + } + + return bridges; + } +} diff --git a/tests/1001-1500/1192. critical-connections-in-a-network/sol.dart b/tests/1001-1500/1192. critical-connections-in-a-network/sol.dart new file mode 100644 index 00000000..1e857db8 --- /dev/null +++ b/tests/1001-1500/1192. critical-connections-in-a-network/sol.dart @@ -0,0 +1,58 @@ +class Solution { + List> criticalConnections(int n, List> connections) { + List> graph = List.generate(n, (_) => []); + for (var edge in connections) { + int u = edge[0], v = edge[1]; + graph[u].add(v); + graph[v].add(u); + } + + List disc = List.filled(n, -1); + List low = List.filled(n, 0); + int timer = 0; + List> bridges = []; + List iterIdx = List.filled(n, 0); + + for (int start = 0; start < n; start++) { + if (disc[start] != -1) continue; + + List> stack = []; + disc[start] = timer; + low[start] = timer; + timer++; + stack.add([start, -1]); + + while (stack.isNotEmpty) { + var top = stack.last; + int node = top[0], parent = top[1]; + var neighbors = graph[node]; + + if (iterIdx[node] < neighbors.length) { + int nb = neighbors[iterIdx[node]]; + iterIdx[node]++; + if (nb == parent) continue; + + if (disc[nb] == -1) { + disc[nb] = timer; + low[nb] = timer; + timer++; + stack.add([nb, node]); + } else { + low[node] = low[node] < disc[nb] ? low[node] : disc[nb]; + } + } else { + stack.removeLast(); + if (stack.isNotEmpty) { + int par = stack.last[0]; + low[par] = low[par] < low[node] ? low[par] : low[node]; + if (low[node] > disc[par]) { + bridges.add([par, node]); + } + } + } + } + } + + return bridges; + } +} diff --git a/tests/1001-1500/1192. critical-connections-in-a-network/sol.go b/tests/1001-1500/1192. critical-connections-in-a-network/sol.go new file mode 100644 index 00000000..e7255547 --- /dev/null +++ b/tests/1001-1500/1192. critical-connections-in-a-network/sol.go @@ -0,0 +1,69 @@ +func criticalConnections(n int, connections [][]int) [][]int { + graph := make([][]int, n) + for _, edge := range connections { + u, v := edge[0], edge[1] + graph[u] = append(graph[u], v) + graph[v] = append(graph[v], u) + } + + disc := make([]int, n) + low := make([]int, n) + for i := range disc { + disc[i] = -1 + } + timer := 0 + bridges := make([][]int, 0) + iterIdx := make([]int, n) + + for start := 0; start < n; start++ { + if disc[start] != -1 { + continue + } + + type frame struct { + node, parent int + } + stack := []frame{{start, -1}} + disc[start] = timer + low[start] = timer + timer++ + + for len(stack) > 0 { + top := stack[len(stack)-1] + node, parent := top.node, top.parent + neighbors := graph[node] + + if iterIdx[node] < len(neighbors) { + nb := neighbors[iterIdx[node]] + iterIdx[node]++ + if nb == parent { + continue + } + + if disc[nb] == -1 { + disc[nb] = timer + low[nb] = timer + timer++ + stack = append(stack, frame{nb, node}) + } else { + if disc[nb] < low[node] { + low[node] = disc[nb] + } + } + } else { + stack = stack[:len(stack)-1] + if len(stack) > 0 { + par := stack[len(stack)-1].node + if low[node] < low[par] { + low[par] = low[node] + } + if low[node] > disc[par] { + bridges = append(bridges, []int{par, node}) + } + } + } + } + } + + return bridges +} diff --git a/tests/1001-1500/1192. critical-connections-in-a-network/sol.java b/tests/1001-1500/1192. critical-connections-in-a-network/sol.java new file mode 100644 index 00000000..f2c60b05 --- /dev/null +++ b/tests/1001-1500/1192. critical-connections-in-a-network/sol.java @@ -0,0 +1,64 @@ +class Solution { + public List> criticalConnections(int n, int[][] connections) { + List> graph = new ArrayList<>(n); + for (int i = 0; i < n; i++) { + graph.add(new ArrayList<>()); + } + for (int[] edge : connections) { + int u = edge[0]; + int v = edge[1]; + graph.get(u).add(v); + graph.get(v).add(u); + } + + int[] disc = new int[n]; + int[] low = new int[n]; + Arrays.fill(disc, -1); + int[] timer = new int[]{0}; + List> bridges = new ArrayList<>(); + + int[] iterIdx = new int[n]; + + for (int start = 0; start < n; start++) { + if (disc[start] != -1) continue; + + Deque stack = new ArrayDeque<>(); + disc[start] = low[start] = timer[0]; + timer[0]++; + stack.push(new int[]{start, -1}); + + while (!stack.isEmpty()) { + int[] top = stack.peek(); + int node = top[0]; + int parent = top[1]; + List neighbors = graph.get(node); + int idx = iterIdx[node]; + + if (idx < neighbors.size()) { + int nb = neighbors.get(idx); + iterIdx[node]++; + if (nb == parent) continue; + + if (disc[nb] == -1) { + disc[nb] = low[nb] = timer[0]; + timer[0]++; + stack.push(new int[]{nb, node}); + } else { + low[node] = Math.min(low[node], disc[nb]); + } + } else { + stack.pop(); + if (!stack.isEmpty()) { + int par = stack.peek()[0]; + low[par] = Math.min(low[par], low[node]); + if (low[node] > disc[par]) { + bridges.add(Arrays.asList(par, node)); + } + } + } + } + } + + return bridges; + } +} diff --git a/tests/1001-1500/1192. critical-connections-in-a-network/sol.kt b/tests/1001-1500/1192. critical-connections-in-a-network/sol.kt new file mode 100644 index 00000000..15927353 --- /dev/null +++ b/tests/1001-1500/1192. critical-connections-in-a-network/sol.kt @@ -0,0 +1,59 @@ +class Solution { + fun criticalConnections(n: Int, connections: Array): List> { + val graph = Array(n) { mutableListOf() } + for (edge in connections) { + graph[edge[0]].add(edge[1]) + graph[edge[1]].add(edge[0]) + } + + val disc = IntArray(n) { -1 } + val low = IntArray(n) + var timer = 0 + val bridges = mutableListOf>() + val iterIdx = IntArray(n) + + for (start in 0 until n) { + if (disc[start] != -1) continue + + val stack = ArrayDeque() + disc[start] = timer + low[start] = timer + timer++ + stack.addLast(intArrayOf(start, -1)) + + while (stack.isNotEmpty()) { + val top = stack.last() + val node = top[0] + val parent = top[1] + val neighbors = graph[node] + val idx = iterIdx[node] + + if (idx < neighbors.size) { + val nb = neighbors[idx] + iterIdx[node]++ + if (nb == parent) continue + + if (disc[nb] == -1) { + disc[nb] = timer + low[nb] = timer + timer++ + stack.addLast(intArrayOf(nb, node)) + } else { + low[node] = minOf(low[node], disc[nb]) + } + } else { + stack.removeLast() + if (stack.isNotEmpty()) { + val par = stack.last()[0] + low[par] = minOf(low[par], low[node]) + if (low[node] > disc[par]) { + bridges.add(listOf(par, node)) + } + } + } + } + } + + return bridges + } +} diff --git a/tests/1001-1500/1192. critical-connections-in-a-network/sol.py b/tests/1001-1500/1192. critical-connections-in-a-network/sol.py new file mode 100644 index 00000000..1745f687 --- /dev/null +++ b/tests/1001-1500/1192. critical-connections-in-a-network/sol.py @@ -0,0 +1,72 @@ +from typing import List +from collections import defaultdict + + +class Solution: + def criticalConnections( + self, n: int, connections: List[List[int]] + ) -> List[List[int]]: + """ + Tarjan's algorithm interpreted via Sparse Linear Algebra: + + - disc[v] = Column pivot order in symbolic forward elimination. + - low[v] = A scalar Schur complement proxy tracking fill reach + into ancestor pivots. + - Bridge = An interface with rank-1 coupling and zero off-diagonal + Schur block fill from back-edges. + """ + # --- Construct structural topology (Adjacency Matrix Pattern) --- + graph = defaultdict(list) + for u, v in connections: + graph[u].append(v) + graph[v].append(u) + + disc = [-1] * n # Pivot order (Gaussian elimination column index) + low = [0] * n # Scalar Schur complement proxy reach + timer = [0] + bridges = [] + + for start in range(n): + if disc[start] != -1: + continue + + # --- Iterative DFS = Symbolic Forward Elimination Analysis --- + stack = [(start, -1, iter(graph[start]))] + disc[start] = low[start] = timer[0] + timer[0] += 1 + + while stack: + node, parent, nbrs = stack[-1] + try: + nb = next(nbrs) + if nb == parent: + # Skip: would re-introduce eliminated pivot + continue + + if disc[nb] == -1: + # Tree edge: extend elimination front + disc[nb] = low[nb] = timer[0] + timer[0] += 1 + stack.append((nb, node, iter(graph[nb]))) + else: + # Back edge: off-diagonal loop entry captured + # by Stefan Vandewalle's interface operator framing. + # Update scalar Schur reach mapping. + low[node] = min(low[node], disc[nb]) + + except StopIteration: + stack.pop() + if stack: + par = stack[-1][0] + + # --- Subdomain Schur Condensation --- + # Condense variables of subdomain(node) onto interface par. + # Propagate the monotonic low-link reach upward. + low[par] = min(low[par], low[node]) + + if low[node] > disc[par]: + # The condensed operator has zero off-diagonal + # coupling block above par's pivot. + bridges.append([par, node]) + + return bridges diff --git a/tests/1001-1500/1192. critical-connections-in-a-network/sol.py2 b/tests/1001-1500/1192. critical-connections-in-a-network/sol.py2 new file mode 100644 index 00000000..378e710f --- /dev/null +++ b/tests/1001-1500/1192. critical-connections-in-a-network/sol.py2 @@ -0,0 +1,49 @@ +from collections import defaultdict + +class Solution(object): + def criticalConnections(self, n, connections): + """ + :type n: int + :type connections: List[List[int]] + :rtype: List[List[int]] + """ + graph = defaultdict(list) + for u, v in connections: + graph[u].append(v) + graph[v].append(u) + + disc = [-1] * n + low = [0] * n + timer = [0] + bridges = [] + + for start in range(n): + if disc[start] != -1: + continue + + stack = [(start, -1, iter(graph[start]))] + disc[start] = low[start] = timer[0] + timer[0] += 1 + + while stack: + node, parent, nbrs = stack[-1] + try: + nb = next(nbrs) + if nb == parent: + continue + + if disc[nb] == -1: + disc[nb] = low[nb] = timer[0] + timer[0] += 1 + stack.append((nb, node, iter(graph[nb]))) + else: + low[node] = min(low[node], disc[nb]) + except StopIteration: + stack.pop() + if stack: + par = stack[-1][0] + low[par] = min(low[par], low[node]) + if low[node] > disc[par]: + bridges.append([par, node]) + + return bridges diff --git a/tests/1001-1500/1192. critical-connections-in-a-network/sol.rb b/tests/1001-1500/1192. critical-connections-in-a-network/sol.rb new file mode 100644 index 00000000..b9787092 --- /dev/null +++ b/tests/1001-1500/1192. critical-connections-in-a-network/sol.rb @@ -0,0 +1,52 @@ +# @param {Integer} n +# @param {Integer[][]} connections +# @return {Integer[][]} +def critical_connections(n, connections) + graph = Hash.new { |h, k| h[k] = [] } + connections.each do |u, v| + graph[u] << v + graph[v] << u + end + + disc = Array.new(n, -1) + low = Array.new(n, 0) + timer = [0] + bridges = [] + + (0...n).each do |start| + next if disc[start] != -1 + + stack = [[start, -1, graph[start].each]] + disc[start] = low[start] = timer[0] + timer[0] += 1 + + while !stack.empty? + node, parent, nbrs = stack.last + begin + nb = nbrs.next + if nb == parent + next + end + + if disc[nb] == -1 + disc[nb] = low[nb] = timer[0] + timer[0] += 1 + stack.push([nb, node, graph[nb].each]) + else + low[node] = [low[node], disc[nb]].min + end + rescue StopIteration + stack.pop + if !stack.empty? + par = stack.last[0] + low[par] = [low[par], low[node]].min + if low[node] > disc[par] + bridges << [par, node] + end + end + end + end + end + + bridges +end diff --git a/tests/1001-1500/1192. critical-connections-in-a-network/sol.rs b/tests/1001-1500/1192. critical-connections-in-a-network/sol.rs new file mode 100644 index 00000000..a64f7e34 --- /dev/null +++ b/tests/1001-1500/1192. critical-connections-in-a-network/sol.rs @@ -0,0 +1,63 @@ +impl Solution { + pub fn critical_connections(n: i32, connections: Vec>) -> Vec> { + let n = n as usize; + let mut graph: Vec> = vec![Vec::new(); n]; + for edge in &connections { + let u = edge[0] as usize; + let v = edge[1] as usize; + graph[u].push(v as i32); + graph[v].push(u as i32); + } + + let mut disc: Vec = vec![-1; n]; + let mut low: Vec = vec![0; n]; + let mut timer = 0; + let mut bridges: Vec> = Vec::new(); + let mut iter_idx: Vec = vec![0; n]; + + for start in 0..n { + if disc[start] != -1 { + continue; + } + + let mut stack: Vec<(usize, i32)> = Vec::new(); + disc[start] = timer; + low[start] = timer; + timer += 1; + stack.push((start, -1)); + + while !stack.is_empty() { + let (node, parent) = *stack.last().unwrap(); + let neighbors = &graph[node]; + + if iter_idx[node] < neighbors.len() { + let nb = neighbors[iter_idx[node]] as usize; + iter_idx[node] += 1; + if nb as i32 == parent { + continue; + } + + if disc[nb] == -1 { + disc[nb] = timer; + low[nb] = timer; + timer += 1; + stack.push((nb, node as i32)); + } else { + low[node] = low[node].min(disc[nb]); + } + } else { + stack.pop(); + if !stack.is_empty() { + let par = stack.last().unwrap().0; + low[par] = low[par].min(low[node]); + if low[node] > disc[par] { + bridges.push(vec![par as i32, node as i32]); + } + } + } + } + } + + bridges + } +} diff --git a/tests/1001-1500/1192. critical-connections-in-a-network/sol.swift b/tests/1001-1500/1192. critical-connections-in-a-network/sol.swift new file mode 100644 index 00000000..90ebd6c7 --- /dev/null +++ b/tests/1001-1500/1192. critical-connections-in-a-network/sol.swift @@ -0,0 +1,58 @@ +class Solution { + func criticalConnections(_ n: Int, _ connections: [[Int]]) -> [[Int]] { + var graph = [[Int]](repeating: [], count: n) + for edge in connections { + let u = edge[0], v = edge[1] + graph[u].append(v) + graph[v].append(u) + } + + var disc = [Int](repeating: -1, count: n) + var low = [Int](repeating: 0, count: n) + var timer = 0 + var bridges = [[Int]]() + var iterIdx = [Int](repeating: 0, count: n) + + for start in 0.. disc[par] { + bridges.append([par, node]) + } + } + } + } + } + + return bridges + } +} diff --git a/tests/1001-1500/1192. critical-connections-in-a-network/sol.ts b/tests/1001-1500/1192. critical-connections-in-a-network/sol.ts new file mode 100644 index 00000000..75a64ce1 --- /dev/null +++ b/tests/1001-1500/1192. critical-connections-in-a-network/sol.ts @@ -0,0 +1,54 @@ +function criticalConnections(n: number, connections: number[][]): number[][] { + const graph: number[][] = Array.from({ length: n }, () => []); + for (const [u, v] of connections) { + graph[u].push(v); + graph[v].push(u); + } + + const disc: number[] = Array(n).fill(-1); + const low: number[] = Array(n).fill(0); + let timer = 0; + const bridges: number[][] = []; + const iterIdx: number[] = Array(n).fill(0); + + for (let start = 0; start < n; start++) { + if (disc[start] !== -1) continue; + + const stack: [number, number][] = []; + disc[start] = timer; + low[start] = timer; + timer++; + stack.push([start, -1]); + + while (stack.length > 0) { + const [node, parent] = stack[stack.length - 1]; + const neighbors = graph[node]; + + if (iterIdx[node] < neighbors.length) { + const nb = neighbors[iterIdx[node]]; + iterIdx[node]++; + if (nb === parent) continue; + + if (disc[nb] === -1) { + disc[nb] = timer; + low[nb] = timer; + timer++; + stack.push([nb, node]); + } else { + low[node] = Math.min(low[node], disc[nb]); + } + } else { + stack.pop(); + if (stack.length > 0) { + const par = stack[stack.length - 1][0]; + low[par] = Math.min(low[par], low[node]); + if (low[node] > disc[par]) { + bridges.push([par, node]); + } + } + } + } + } + + return bridges; +} diff --git a/tests/1001-1500/1200. minimum-absolute-difference/manifest.yaml b/tests/1001-1500/1200. minimum-absolute-difference/manifest.yaml new file mode 100644 index 00000000..5d124892 --- /dev/null +++ b/tests/1001-1500/1200. minimum-absolute-difference/manifest.yaml @@ -0,0 +1,324 @@ +entry: + id: 1200 + title: minimum-absolute-difference + params: + arr: + type: array + items: + type: int + call: + cpp: "Solution().minimumAbsDifference({arr})" + rust: "Solution::minimum_abs_difference({arr})" + python3: "Solution().minimumAbsDifference({arr})" + python2: "Solution().minimumAbsDifference({arr})" + ruby: "minimum_abs_difference({arr})" + java: "new Solution().minimumAbsDifference({arr})" + csharp: "new Solution().MinimumAbsDifference({arr})" + kotlin: "Solution().minimumAbsDifference({arr})" + go: "minimumAbsDifference({arr})" + dart: "Solution().minimumAbsDifference({arr})" + swift: "Solution().minimumAbsDifference({arr})" + typescript: "minimumAbsDifference({arr})" +judge: + type: exact +limits: + time_ms: 1500 + memory_mb: 256 +oracle: + python3: + call: "Checker().minimumAbsDifference(arr, {result})" + checker: | + class Checker: + def minimumAbsDifference(self, arr, result): + if type(arr) is not list or type(result) is not list: + return False + if not 2 <= len(arr) <= 100000: + return False + if any(type(value) is not int or value < -1000000 or value > 1000000 for value in arr): + return False + if len(set(arr)) != len(arr): + return False + ordered = sorted(arr) + minimum_gap = min(ordered[index + 1] - ordered[index] for index in range(len(ordered) - 1)) + expected = [[ordered[index], ordered[index + 1]] for index in range(len(ordered) - 1) if ordered[index + 1] - ordered[index] == minimum_gap] + return result == expected +seed: 1200 +tests: + - name: example_one + in: + arr: [4, 2, 1, 3] + out: + - [1, 2] + - [2, 3] + - [3, 4] + - name: example_two + in: + arr: [1, 3, 6, 10, 15] + out: + - [1, 3] + - name: example_three + in: + arr: [3, 8, -10, 23, 19, -4, -14, 27] + out: + - [-14, -10] + - [19, 23] + - [23, 27] + - name: two_values + in: + arr: [5, 9] + out: + - [5, 9] + - name: two_negative_values + in: + arr: [-9, -2] + out: + - [-9, -2] + - name: adjacent_pair_only + in: + arr: [1, 10, 11, 30] + out: + - [10, 11] + - name: all_consecutive + in: + arr: [8, 5, 7, 6, 4] + out: + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - name: multiple_equal_gaps + in: + arr: [0, 5, 10, 15] + out: + - [0, 5] + - [5, 10] + - [10, 15] + - name: negative_and_positive + in: + arr: [-10, -5, 0, 5, 10] + out: + - [-10, -5] + - [-5, 0] + - [0, 5] + - [5, 10] + - name: unsorted_input + in: + arr: [20, 3, 14, 8, 9] + out: + - [8, 9] + - name: minimum_at_start + in: + arr: [-100, -99, 0, 50] + out: + - [-100, -99] + - name: minimum_at_end + in: + arr: [-50, 0, 98, 99] + out: + - [98, 99] + - name: repeated_gap_three + in: + arr: [2, 5, 8, 20, 23] + out: + - [2, 5] + - [5, 8] + - [20, 23] + - name: one_tiny_gap + in: + arr: [-1000, -2, 0, 1000] + out: + - [-2, 0] + - name: boundary_values + in: + arr: [-1000000, -999999, 0, 999999, 1000000] + out: + - [-1000000, -999999] + - [999999, 1000000] + - name: symmetric_values + in: + arr: [-7, -3, 3, 7] + out: + - [-7, -3] + - [3, 7] + - name: dense_middle + in: + arr: [-20, -1, 0, 1, 20] + out: + - [-1, 0] + - [0, 1] + - name: separated_clusters + in: + arr: [-100, -90, -89, 0, 50, 51] + out: + - [-90, -89] + - [50, 51] + - name: negative_minimum + in: + arr: [-8, -6, -5, 2, 10] + out: + - [-6, -5] + - name: gap_one_many_times + in: + arr: [1, 2, 4, 5, 7, 8] + out: + - [1, 2] + - [4, 5] + - [7, 8] + - name: gap_two_many_times + in: + arr: [-6, -4, 0, 2, 9] + out: + - [-6, -4] + - [0, 2] + - name: largest_possible_gap + in: + arr: [-1000000, 1000000] + out: + - [-1000000, 1000000] + - name: mixed_order_multiple_pairs + in: + arr: [100, -1, 3, 0, 4, -5] + out: + - [-1, 0] + - [3, 4] + - name: four_negative + in: + arr: [-20, -15, -14, -2] + out: + - [-15, -14] + - name: four_positive + in: + arr: [2, 12, 13, 30] + out: + - [12, 13] + - name: exact_middle_minimum + in: + arr: [-50, -1, 0, 50] + out: + - [-1, 0] + - name: alternating_gaps + in: + arr: [0, 2, 3, 5, 6, 10] + out: + - [2, 3] + - [5, 6] + - name: close_negative_cluster + in: + arr: [-12, -11, -10, 0, 20] + out: + - [-12, -11] + - [-11, -10] + - name: close_positive_cluster + in: + arr: [-20, 0, 10, 11, 12] + out: + - [10, 11] + - [11, 12] + - name: minimum_gap_at_both_ends + in: + arr: [-6, -5, 0, 10, 11] + out: + - [-6, -5] + - [10, 11] + - name: nonadjacent_input_order + in: + arr: [50, -100, 49, 200, -99] + out: + - [-100, -99] + - [49, 50] + - name: uneven_negative_and_positive_groups + in: + arr: [-999, -500, -498, 1, 4, 8, 100] + out: + - [-500, -498] + - name: narrow_pair_among_extremes + in: + arr: [-1000000, -123456, 765431, 765432, 1000000] + out: + - [765431, 765432] + - name: evenly_spaced_odd_values + in: + arr: [15, -9, 3, 9, -3] + out: + - [-9, -3] + - [-3, 3] + - [3, 9] + - [9, 15] + - name: stress_fifty_thousand_full_range + seed: 1201 + in: + arr: + gen: "array" + len: 50000 + of: + gen: "int" + min: -1000000 + max: 1000000 + distinct: true + sorted: false + elemType: "int" + - name: stress_seventy_thousand_full_range + seed: 1202 + in: + arr: + gen: "array" + len: 70000 + of: + gen: "int" + min: -1000000 + max: 1000000 + distinct: true + sorted: false + elemType: "int" + - name: stress_eighty_thousand_dense_range + seed: 1203 + in: + arr: + gen: "array" + len: 80000 + of: + gen: "int" + min: -50000 + max: 50000 + distinct: true + sorted: false + elemType: "int" + - name: stress_ninety_thousand_full_range + seed: 1204 + in: + arr: + gen: "array" + len: 90000 + of: + gen: "int" + min: -1000000 + max: 1000000 + distinct: true + sorted: false + elemType: "int" + - name: stress_ninety_nine_thousand_dense_range + seed: 1205 + in: + arr: + gen: "array" + len: 99000 + of: + gen: "int" + min: -100000 + max: 100000 + distinct: true + sorted: false + elemType: "int" + - name: stress_maximum_length_full_range + seed: 1206 + in: + arr: + gen: "array" + len: 100000 + of: + gen: "int" + min: -1000000 + max: 1000000 + distinct: true + sorted: false + elemType: "int" diff --git a/tests/1001-1500/1200. minimum-absolute-difference/sol.cpp b/tests/1001-1500/1200. minimum-absolute-difference/sol.cpp new file mode 100644 index 00000000..761d50e3 --- /dev/null +++ b/tests/1001-1500/1200. minimum-absolute-difference/sol.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + vector> minimumAbsDifference(vector& arr) { + sort(arr.begin(), arr.end()); + int minDiff = INT_MAX; + for (int i = 1; i < arr.size(); i++) { + minDiff = min(minDiff, arr[i] - arr[i - 1]); + } + vector> result; + for (int i = 1; i < arr.size(); i++) { + if (arr[i] - arr[i - 1] == minDiff) { + result.push_back({arr[i - 1], arr[i]}); + } + } + return result; + } +}; diff --git a/tests/1001-1500/1200. minimum-absolute-difference/sol.cs b/tests/1001-1500/1200. minimum-absolute-difference/sol.cs new file mode 100644 index 00000000..d1d2943b --- /dev/null +++ b/tests/1001-1500/1200. minimum-absolute-difference/sol.cs @@ -0,0 +1,16 @@ +public class Solution { + public IList> MinimumAbsDifference(int[] arr) { + Array.Sort(arr); + int minDiff = int.MaxValue; + for (int i = 1; i < arr.Length; i++) { + minDiff = Math.Min(minDiff, arr[i] - arr[i - 1]); + } + IList> result = new List>(); + for (int i = 1; i < arr.Length; i++) { + if (arr[i] - arr[i - 1] == minDiff) { + result.Add(new List { arr[i - 1], arr[i] }); + } + } + return result; + } +} diff --git a/tests/1001-1500/1200. minimum-absolute-difference/sol.dart b/tests/1001-1500/1200. minimum-absolute-difference/sol.dart new file mode 100644 index 00000000..563b7c26 --- /dev/null +++ b/tests/1001-1500/1200. minimum-absolute-difference/sol.dart @@ -0,0 +1,19 @@ +class Solution { + List> minimumAbsDifference(List arr) { + arr.sort(); + int minDiff = 1 << 62; + for (int i = 1; i < arr.length; i++) { + int diff = arr[i] - arr[i - 1]; + if (diff < minDiff) { + minDiff = diff; + } + } + List> result = []; + for (int i = 1; i < arr.length; i++) { + if (arr[i] - arr[i - 1] == minDiff) { + result.add([arr[i - 1], arr[i]]); + } + } + return result; + } +} diff --git a/tests/1001-1500/1200. minimum-absolute-difference/sol.go b/tests/1001-1500/1200. minimum-absolute-difference/sol.go new file mode 100644 index 00000000..bd0c3b3b --- /dev/null +++ b/tests/1001-1500/1200. minimum-absolute-difference/sol.go @@ -0,0 +1,17 @@ +func minimumAbsDifference(arr []int) [][]int { + sort.Ints(arr) + minDiff := math.MaxInt32 + for i := 1; i < len(arr); i++ { + diff := arr[i] - arr[i-1] + if diff < minDiff { + minDiff = diff + } + } + var result [][]int + for i := 1; i < len(arr); i++ { + if arr[i] - arr[i-1] == minDiff { + result = append(result, []int{arr[i-1], arr[i]}) + } + } + return result +} diff --git a/tests/1001-1500/1200. minimum-absolute-difference/sol.java b/tests/1001-1500/1200. minimum-absolute-difference/sol.java new file mode 100644 index 00000000..2d8d24a7 --- /dev/null +++ b/tests/1001-1500/1200. minimum-absolute-difference/sol.java @@ -0,0 +1,16 @@ +class Solution { + public List> minimumAbsDifference(int[] arr) { + Arrays.sort(arr); + int minDiff = Integer.MAX_VALUE; + for (int i = 1; i < arr.length; i++) { + minDiff = Math.min(minDiff, arr[i] - arr[i - 1]); + } + List> result = new ArrayList<>(); + for (int i = 1; i < arr.length; i++) { + if (arr[i] - arr[i - 1] == minDiff) { + result.add(Arrays.asList(arr[i - 1], arr[i])); + } + } + return result; + } +} diff --git a/tests/1001-1500/1200. minimum-absolute-difference/sol.kt b/tests/1001-1500/1200. minimum-absolute-difference/sol.kt new file mode 100644 index 00000000..9336b9a6 --- /dev/null +++ b/tests/1001-1500/1200. minimum-absolute-difference/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun minimumAbsDifference(arr: IntArray): List> { + arr.sort() + var minDiff = Int.MAX_VALUE + for (i in 1 until arr.size) { + minDiff = minOf(minDiff, arr[i] - arr[i - 1]) + } + val result = mutableListOf>() + for (i in 1 until arr.size) { + if (arr[i] - arr[i - 1] == minDiff) { + result.add(listOf(arr[i - 1], arr[i])) + } + } + return result + } +} diff --git a/tests/1001-1500/1200. minimum-absolute-difference/sol.py b/tests/1001-1500/1200. minimum-absolute-difference/sol.py new file mode 100644 index 00000000..84f62e3f --- /dev/null +++ b/tests/1001-1500/1200. minimum-absolute-difference/sol.py @@ -0,0 +1,8 @@ +from itertools import pairwise + + +class Solution: + def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: + arr.sort() + minD = min(y - x for x, y in pairwise(arr)) + return [[x, y] for x, y in pairwise(arr) if y - x == minD] diff --git a/tests/1001-1500/1200. minimum-absolute-difference/sol.py2 b/tests/1001-1500/1200. minimum-absolute-difference/sol.py2 new file mode 100644 index 00000000..ac6556cc --- /dev/null +++ b/tests/1001-1500/1200. minimum-absolute-difference/sol.py2 @@ -0,0 +1,9 @@ +class Solution(object): + def minimumAbsDifference(self, arr): + """ + :type arr: List[int] + :rtype: List[List[int]] + """ + arr.sort() + min_diff = min(arr[i+1] - arr[i] for i in xrange(len(arr) - 1)) + return [[arr[i], arr[i+1]] for i in xrange(len(arr) - 1) if arr[i+1] - arr[i] == min_diff] diff --git a/tests/1001-1500/1200. minimum-absolute-difference/sol.rb b/tests/1001-1500/1200. minimum-absolute-difference/sol.rb new file mode 100644 index 00000000..42a45233 --- /dev/null +++ b/tests/1001-1500/1200. minimum-absolute-difference/sol.rb @@ -0,0 +1,11 @@ +# @param {Integer[]} arr +# @return {Integer[][]} +def minimum_abs_difference(arr) + arr.sort! + min_diff = (1...arr.length).map { |i| arr[i] - arr[i-1] }.min + result = [] + (1...arr.length).each do |i| + result << [arr[i-1], arr[i]] if arr[i] - arr[i-1] == min_diff + end + result +end diff --git a/tests/1001-1500/1200. minimum-absolute-difference/sol.rs b/tests/1001-1500/1200. minimum-absolute-difference/sol.rs new file mode 100644 index 00000000..a4ac1f20 --- /dev/null +++ b/tests/1001-1500/1200. minimum-absolute-difference/sol.rs @@ -0,0 +1,11 @@ +impl Solution { + pub fn minimum_abs_difference(arr: Vec) -> Vec> { + let mut arr = arr; + arr.sort(); + let min_diff = arr.windows(2).map(|w| w[1] - w[0]).min().unwrap(); + arr.windows(2) + .filter(|w| w[1] - w[0] == min_diff) + .map(|w| vec![w[0], w[1]]) + .collect() + } +} diff --git a/tests/1001-1500/1200. minimum-absolute-difference/sol.swift b/tests/1001-1500/1200. minimum-absolute-difference/sol.swift new file mode 100644 index 00000000..85bbdac2 --- /dev/null +++ b/tests/1001-1500/1200. minimum-absolute-difference/sol.swift @@ -0,0 +1,16 @@ +class Solution { + func minimumAbsDifference(_ arr: [Int]) -> [[Int]] { + var arr = arr.sorted() + var minDiff = Int.max + for i in 1.. a - b); + let minDiff = Infinity; + for (let i = 1; i < arr.length; i++) { + minDiff = Math.min(minDiff, arr[i] - arr[i - 1]); + } + const result: number[][] = []; + for (let i = 1; i < arr.length; i++) { + if (arr[i] - arr[i - 1] === minDiff) { + result.push([arr[i - 1], arr[i]]); + } + } + return result; +} diff --git a/tests/1001-1500/1201. ugly-number-iii/manifest.yaml b/tests/1001-1500/1201. ugly-number-iii/manifest.yaml new file mode 100644 index 00000000..2534b300 --- /dev/null +++ b/tests/1001-1500/1201. ugly-number-iii/manifest.yaml @@ -0,0 +1,397 @@ +entry: + id: 1201 + title: "ugly-number-iii" + params: + n: + type: int + a: + type: int + b: + type: int + c: + type: int + call: + cpp: "Solution().nthUglyNumber({n}, {a}, {b}, {c})" + rust: "Solution::nth_ugly_number({n}, {a}, {b}, {c})" + python3: "Solution().nthUglyNumber({n}, {a}, {b}, {c})" + python2: "Solution().nthUglyNumber({n}, {a}, {b}, {c})" + ruby: "nth_ugly_number({n}, {a}, {b}, {c})" + java: "new Solution().nthUglyNumber({n}, {a}, {b}, {c})" + csharp: "new Solution().NthUglyNumber({n}, {a}, {b}, {c})" + kotlin: "Solution().nthUglyNumber({n}, {a}, {b}, {c})" + go: "nthUglyNumber({n}, {a}, {b}, {c})" + dart: "Solution().nthUglyNumber({n}, {a}, {b}, {c})" + swift: "Solution().nthUglyNumber({n}, {a}, {b}, {c})" + typescript: "nthUglyNumber({n}, {a}, {b}, {c})" +judge: + type: "exact" +limits: + time_ms: 2000 + memory_mb: 256 +oracle: + python3: + call: "Checker().nthUglyNumber(n, a, b, c, {result})" + checker: | + from math import gcd + + class Checker: + def nthUglyNumber(self, n, a, b, c, result): + if any(not isinstance(value, int) or isinstance(value, bool) for value in (n, a, b, c, result)): + return False + if not (1 <= n <= 1000000000 and 1 <= a <= 1000000000 and 1 <= b <= 1000000000 and 1 <= c <= 1000000000): + return False + if a * b * c > 1000000000000000000 or not (1 <= result <= 2000000000): + return False + def lcm(x, y): + return x // gcd(x, y) * y + ab, ac, bc = lcm(a, b), lcm(a, c), lcm(b, c) + abc = lcm(ab, c) + def count(limit): + return limit // a + limit // b + limit // c - limit // ab - limit // ac - limit // bc + limit // abc + is_ugly = result % a == 0 or result % b == 0 or result % c == 0 + return is_ugly and count(result - 1) < n <= count(result) +seed: 1201 +tests: + - name: example_one + in: + n: 3 + a: 2 + b: 3 + c: 5 + out: 4 + - name: example_two + in: + n: 4 + a: 2 + b: 3 + c: 4 + out: 6 + - name: example_three + in: + n: 5 + a: 2 + b: 11 + c: 13 + out: 10 + - name: first_of_distinct_divisors + in: + n: 1 + a: 7 + b: 11 + c: 13 + out: 7 + - name: all_divisors_equal + in: + n: 100 + a: 6 + b: 6 + c: 6 + out: 600 + - name: two_divisors_equal + in: + n: 17 + a: 4 + b: 4 + c: 9 + out: 52 + - name: divisibility_chain + in: + n: 25 + a: 2 + b: 4 + c: 8 + out: 50 + - name: pairwise_coprime + in: + n: 20 + a: 3 + b: 5 + c: 7 + out: 36 + - name: three_way_overlap + in: + n: 50 + a: 6 + b: 10 + c: 15 + out: 190 + - name: large_divisors_second_value + in: + n: 2 + a: 999999937 + b: 999999929 + c: 999999893 + out: 999999929 + - name: maximum_n_with_unit_divisor + in: + n: 1000000000 + a: 1 + b: 999999999 + c: 1000000000 + out: 1000000000 + - name: maximum_n_dense_union + in: + n: 1000000000 + a: 2 + b: 3 + c: 5 + out: 1363636364 + - name: maximum_input_divisor + in: + n: 1 + a: 1000000000 + b: 1000000000 + c: 1 + out: 1 + - name: lcm_intersections + in: + n: 31 + a: 12 + b: 18 + c: 25 + out: 204 + - name: nested_overlap + in: + n: 12 + a: 4 + b: 6 + c: 8 + out: 36 + - name: single_effective_divisor + in: + n: 50 + a: 5 + b: 10 + c: 20 + out: 250 + - name: common_factor_chain + in: + n: 400 + a: 7 + b: 14 + c: 21 + out: 2800 + - name: prime_divisors + in: + n: 10 + a: 17 + b: 19 + c: 23 + out: 69 + - name: mixed_multiples + in: + n: 10 + a: 9 + b: 12 + c: 25 + out: 50 + - name: dense_shared_factors + in: + n: 20 + a: 24 + b: 36 + c: 60 + out: 324 + - name: sparse_prime_divisors + in: + n: 2 + a: 997 + b: 991 + c: 983 + out: 991 + - name: overlapping_even_and_seven + in: + n: 20 + a: 2 + b: 4 + c: 7 + out: 35 + - name: two_effective_divisors + in: + n: 20 + a: 3 + b: 6 + c: 10 + out: 50 + - name: close_primes + in: + n: 15 + a: 11 + b: 13 + c: 17 + out: 68 + - name: non_overlapping_small_rank + in: + n: 6 + a: 29 + b: 31 + c: 37 + out: 74 + - name: unit_a_position + in: + n: 999999937 + a: 1 + b: 999999937 + c: 999999929 + out: 999999937 + - name: unit_b_position + in: + n: 1000000000 + a: 999999937 + b: 1 + c: 999999929 + out: 1000000000 + - name: unit_c_position + in: + n: 2 + a: 999999937 + b: 999999929 + c: 1 + out: 2 + - name: one_large_and_two_small + in: + n: 100 + a: 1000000000 + b: 2 + c: 4 + out: 200 + - name: large_lcm_without_overlap_in_range + in: + n: 3 + a: 500000000 + b: 600000000 + c: 700000000 + out: 700000000 + - name: exact_pairwise_lcm_boundary + in: + n: 8 + a: 6 + b: 10 + c: 15 + out: 30 + - name: result_at_two_billion + in: + n: 1000000000 + a: 2 + b: 4 + c: 8 + out: 2000000000 + - name: high_rank_with_single_divisor + in: + n: 1000000000 + a: 1000000000 + b: 1 + c: 1 + out: 1000000000 + - name: equal_large_divisors + in: + n: 2 + a: 1000000 + b: 1000000 + c: 1000000 + out: 2000000 + - name: generated_large_rank_unit_a + seed: 101 + in: + n: + gen: int + min: 900000000 + max: 1000000000 + a: 1 + b: + gen: int + min: 1 + max: 1000000000 + c: + gen: int + min: 1 + max: 1000000000 + - name: generated_large_rank_unit_b + seed: 202 + in: + n: + gen: int + min: 900000000 + max: 1000000000 + a: + gen: int + min: 1 + max: 1000000000 + b: 1 + c: + gen: int + min: 1 + max: 1000000000 + - name: generated_large_rank_unit_c + seed: 303 + in: + n: + gen: int + min: 900000000 + max: 1000000000 + a: + gen: int + min: 1 + max: 1000000000 + b: + gen: int + min: 1 + max: 1000000000 + c: 1 + - name: generated_sparse_large_divisors + seed: 404 + in: + n: + gen: int + min: 1 + max: 1000 + a: + gen: int + min: 100000 + max: 1000000 + b: + gen: int + min: 100000 + max: 1000000 + c: + gen: int + min: 100000 + max: 1000000 + - name: generated_medium_dense + seed: 505 + in: + n: + gen: int + min: 1 + max: 100000 + a: + gen: int + min: 1 + max: 10000 + b: + gen: int + min: 1 + max: 10000 + c: + gen: int + min: 1 + max: 10000 + - name: generated_high_rank_small_divisors + seed: 606 + in: + n: + gen: int + min: 900000000 + max: 1000000000 + a: + gen: int + min: 1 + max: 2 + b: + gen: int + min: 3 + max: 4 + c: + gen: int + min: 5 + max: 6 diff --git a/tests/1001-1500/1201. ugly-number-iii/sol.cpp b/tests/1001-1500/1201. ugly-number-iii/sol.cpp new file mode 100644 index 00000000..deeb30b7 --- /dev/null +++ b/tests/1001-1500/1201. ugly-number-iii/sol.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + int nthUglyNumber(int n, int a, int b, int c) { + auto gcd = [](long long x, long long y) -> long long { + while (y) { + long long temp = y; + y = x % y; + x = temp; + } + return x; + }; + + auto lcm = [&](long long x, long long y) -> long long { + return x * y / gcd(x, y); + }; + + long long la = a, lb = b, lc = c; + long long ab = lcm(la, lb); + long long ac = lcm(la, lc); + long long bc = lcm(lb, lc); + long long abc = lcm(ab, lc); + + long long left = 1, right = 2'000'000'000; + + while (left < right) { + long long mid = left + (right - left) / 2; + long long cnt = mid / la + mid / lb + mid / lc - + mid / ab - mid / ac - mid / bc + + mid / abc; + if (cnt >= n) { + right = mid; + } else { + left = mid + 1; + } + } + + return (int) left; + } +}; diff --git a/tests/1001-1500/1201. ugly-number-iii/sol.cs b/tests/1001-1500/1201. ugly-number-iii/sol.cs new file mode 100644 index 00000000..031eb367 --- /dev/null +++ b/tests/1001-1500/1201. ugly-number-iii/sol.cs @@ -0,0 +1,38 @@ +public class Solution { + public int NthUglyNumber(int n, int a, int b, int c) { + long Gcd(long x, long y) { + while (y != 0) { + long temp = y; + y = x % y; + x = temp; + } + return x; + } + + long Lcm(long x, long y) { + return x * y / Gcd(x, y); + } + + long la = a, lb = b, lc = c; + long ab = Lcm(la, lb); + long ac = Lcm(la, lc); + long bc = Lcm(lb, lc); + long abc = Lcm(ab, lc); + + long left = 1, right = 2_000_000_000; + + while (left < right) { + long mid = left + (right - left) / 2; + long cnt = mid / la + mid / lb + mid / lc - + mid / ab - mid / ac - mid / bc + + mid / abc; + if (cnt >= n) { + right = mid; + } else { + left = mid + 1; + } + } + + return (int) left; + } +} diff --git a/tests/1001-1500/1201. ugly-number-iii/sol.dart b/tests/1001-1500/1201. ugly-number-iii/sol.dart new file mode 100644 index 00000000..83bdecf6 --- /dev/null +++ b/tests/1001-1500/1201. ugly-number-iii/sol.dart @@ -0,0 +1,38 @@ +class Solution { + int nthUglyNumber(int n, int a, int b, int c) { + int gcd(int x, int y) { + while (y != 0) { + int temp = y; + y = x % y; + x = temp; + } + return x; + } + + int lcm(int x, int y) { + return x * y ~/ gcd(x, y); + } + + int ab = lcm(a, b); + int ac = lcm(a, c); + int bc = lcm(b, c); + int abc = lcm(ab, c); + + int left = 1; + int right = 2000000000; + + while (left < right) { + int mid = left + (right - left) ~/ 2; + int cnt = mid ~/ a + mid ~/ b + mid ~/ c - + mid ~/ ab - mid ~/ ac - mid ~/ bc + + mid ~/ abc; + if (cnt >= n) { + right = mid; + } else { + left = mid + 1; + } + } + + return left; + } +} diff --git a/tests/1001-1500/1201. ugly-number-iii/sol.go b/tests/1001-1500/1201. ugly-number-iii/sol.go new file mode 100644 index 00000000..9eb59fb1 --- /dev/null +++ b/tests/1001-1500/1201. ugly-number-iii/sol.go @@ -0,0 +1,38 @@ +func nthUglyNumber(n int, a int, b int, c int) int { + gcd := func(x, y int64) int64 { + for y != 0 { + x, y = y, x%y + } + return x + } + + lcm := func(x, y int64) int64 { + return x * y / gcd(x, y) + } + + la := int64(a) + lb := int64(b) + lc := int64(c) + + ab := lcm(la, lb) + ac := lcm(la, lc) + bc := lcm(lb, lc) + abc := lcm(ab, lc) + + var left int64 = 1 + var right int64 = 2_000_000_000 + + for left < right { + mid := left + (right-left)/2 + cnt := mid/la + mid/lb + mid/lc - + mid/ab - mid/ac - mid/bc + + mid/abc + if cnt >= int64(n) { + right = mid + } else { + left = mid + 1 + } + } + + return int(left) +} diff --git a/tests/1001-1500/1201. ugly-number-iii/sol.java b/tests/1001-1500/1201. ugly-number-iii/sol.java new file mode 100644 index 00000000..b85837b8 --- /dev/null +++ b/tests/1001-1500/1201. ugly-number-iii/sol.java @@ -0,0 +1,38 @@ +class Solution { + public int nthUglyNumber(int n, int a, int b, int c) { + long ab = lcm(a, b); + long ac = lcm(a, c); + long bc = lcm(b, c); + long abc = lcm(ab, c); + + long left = 1; + long right = 2_000_000_000L; + + while (left < right) { + long mid = left + (right - left) / 2; + long cnt = mid / a + mid / b + mid / c + - mid / ab - mid / ac - mid / bc + + mid / abc; + if (cnt >= n) { + right = mid; + } else { + left = mid + 1; + } + } + + return (int) left; + } + + private long gcd(long x, long y) { + while (y != 0) { + long temp = y; + y = x % y; + x = temp; + } + return x; + } + + private long lcm(long x, long y) { + return x * y / gcd(x, y); + } +} diff --git a/tests/1001-1500/1201. ugly-number-iii/sol.kt b/tests/1001-1500/1201. ugly-number-iii/sol.kt new file mode 100644 index 00000000..8c830495 --- /dev/null +++ b/tests/1001-1500/1201. ugly-number-iii/sol.kt @@ -0,0 +1,44 @@ +class Solution { + fun nthUglyNumber(n: Int, a: Int, b: Int, c: Int): Int { + fun gcd(x: Long, y: Long): Long { + var xx = x + var yy = y + while (yy != 0L) { + val temp = yy + yy = xx % yy + xx = temp + } + return xx + } + + fun lcm(x: Long, y: Long): Long { + return x * y / gcd(x, y) + } + + val la = a.toLong() + val lb = b.toLong() + val lc = c.toLong() + + val ab = lcm(la, lb) + val ac = lcm(la, lc) + val bc = lcm(lb, lc) + val abc = lcm(ab, lc) + + var left = 1L + var right = 2_000_000_000L + + while (left < right) { + val mid = left + (right - left) / 2 + val cnt = mid / la + mid / lb + mid / lc - + mid / ab - mid / ac - mid / bc + + mid / abc + if (cnt >= n) { + right = mid + } else { + left = mid + 1 + } + } + + return left.toInt() + } +} diff --git a/tests/1001-1500/1201. ugly-number-iii/sol.py b/tests/1001-1500/1201. ugly-number-iii/sol.py new file mode 100644 index 00000000..4d0f7a9d --- /dev/null +++ b/tests/1001-1500/1201. ugly-number-iii/sol.py @@ -0,0 +1,28 @@ +from math import gcd + + +class Solution: + def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int: + def lcm(x, y): + return x * y // gcd(x, y) + + ab = lcm(a, b) + ac = lcm(a, c) + bc = lcm(b, c) + abc = lcm(ab, c) + + def count(x): + return x // a + x // b + x // c - x // ab - x // ac - x // bc + x // abc + + left = 1 + right = 2 * 10**9 + + while left < right: + mid = (left + right) // 2 + + if count(mid) >= n: + right = mid + else: + left = mid + 1 + + return left diff --git a/tests/1001-1500/1201. ugly-number-iii/sol.py2 b/tests/1001-1500/1201. ugly-number-iii/sol.py2 new file mode 100644 index 00000000..44ea4769 --- /dev/null +++ b/tests/1001-1500/1201. ugly-number-iii/sol.py2 @@ -0,0 +1,44 @@ +class Solution(object): + def nthUglyNumber(self, n, a, b, c): + """ + :type n: int + :type a: int + :type b: int + :type c: int + :rtype: int + """ + def gcd(x, y): + while y: + x, y = y, x % y + return x + + def lcm(x, y): + return x * y // gcd(x, y) + + ab = lcm(a, b) + ac = lcm(a, c) + bc = lcm(b, c) + abc = lcm(ab, c) + + def count(x): + return ( + x // a + + x // b + + x // c - + x // ab - + x // ac - + x // bc + + x // abc + ) + + left = 1 + right = 2 * 10**9 + + while left < right: + mid = (left + right) // 2 + if count(mid) >= n: + right = mid + else: + left = mid + 1 + + return left diff --git a/tests/1001-1500/1201. ugly-number-iii/sol.rb b/tests/1001-1500/1201. ugly-number-iii/sol.rb new file mode 100644 index 00000000..d3edfb42 --- /dev/null +++ b/tests/1001-1500/1201. ugly-number-iii/sol.rb @@ -0,0 +1,40 @@ +# @param {Integer} n +# @param {Integer} a +# @param {Integer} b +# @param {Integer} c +# @return {Integer} +def nth_ugly_number(n, a, b, c) + def gcd(x, y) + while y != 0 + x, y = y, x % y + end + x + end + + def lcm(x, y) + x * y / gcd(x, y) + end + + ab = lcm(a, b) + ac = lcm(a, c) + bc = lcm(b, c) + abc = lcm(ab, c) + + count = lambda do |x| + x / a + x / b + x / c - x / ab - x / ac - x / bc + x / abc + end + + left = 1 + right = 2 * 10**9 + + while left < right + mid = (left + right) / 2 + if count.call(mid) >= n + right = mid + else + left = mid + 1 + end + end + + left +end diff --git a/tests/1001-1500/1201. ugly-number-iii/sol.rs b/tests/1001-1500/1201. ugly-number-iii/sol.rs new file mode 100644 index 00000000..2c90ccde --- /dev/null +++ b/tests/1001-1500/1201. ugly-number-iii/sol.rs @@ -0,0 +1,42 @@ +impl Solution { + pub fn nth_ugly_number(n: i32, a: i32, b: i32, c: i32) -> i32 { + fn gcd(mut x: i64, mut y: i64) -> i64 { + while y != 0 { + let temp = y; + y = x % y; + x = temp; + } + x + } + + fn lcm(x: i64, y: i64) -> i64 { + x * y / gcd(x, y) + } + + let la = a as i64; + let lb = b as i64; + let lc = c as i64; + + let ab = lcm(la, lb); + let ac = lcm(la, lc); + let bc = lcm(lb, lc); + let abc = lcm(ab, lc); + + let mut left: i64 = 1; + let mut right: i64 = 2_000_000_000; + + while left < right { + let mid = left + (right - left) / 2; + let cnt = mid / la + mid / lb + mid / lc - + mid / ab - mid / ac - mid / bc + + mid / abc; + if cnt >= n as i64 { + right = mid; + } else { + left = mid + 1; + } + } + + left as i32 + } +} diff --git a/tests/1001-1500/1201. ugly-number-iii/sol.swift b/tests/1001-1500/1201. ugly-number-iii/sol.swift new file mode 100644 index 00000000..c39ef706 --- /dev/null +++ b/tests/1001-1500/1201. ugly-number-iii/sol.swift @@ -0,0 +1,42 @@ +class Solution { + func nthUglyNumber(_ n: Int, _ a: Int, _ b: Int, _ c: Int) -> Int { + func gcd(_ x: Int, _ y: Int) -> Int { + var xx = x + var yy = y + while yy != 0 { + let temp = yy + yy = xx % yy + xx = temp + } + return xx + } + + func lcm(_ x: Int, _ y: Int) -> Int { + let reduced = x / gcd(x, y) + let limit = 2_000_000_001 + return reduced > limit / y ? limit : reduced * y + } + + let ab = lcm(a, b) + let ac = lcm(a, c) + let bc = lcm(b, c) + let abc = lcm(ab, c) + + var left = 1 + var right = 2_000_000_000 + + while left < right { + let mid = left + (right - left) / 2 + let cnt = mid / a + mid / b + mid / c - + mid / ab - mid / ac - mid / bc + + mid / abc + if cnt >= n { + right = mid + } else { + left = mid + 1 + } + } + + return left + } +} diff --git a/tests/1001-1500/1201. ugly-number-iii/sol.ts b/tests/1001-1500/1201. ugly-number-iii/sol.ts new file mode 100644 index 00000000..bf8b3e5f --- /dev/null +++ b/tests/1001-1500/1201. ugly-number-iii/sol.ts @@ -0,0 +1,41 @@ +function nthUglyNumber(n: number, a: number, b: number, c: number): number { + function gcd(x: number, y: number): number { + while (y !== 0) { + const temp = y; + y = x % y; + x = temp; + } + return x; + } + + function lcm(x: number, y: number): number { + return Math.floor((x * y) / gcd(x, y)); + } + + const ab: number = lcm(a, b); + const ac: number = lcm(a, c); + const bc: number = lcm(b, c); + const abc: number = lcm(ab, c); + + let left: number = 1; + let right: number = 2000000000; + + while (left < right) { + const mid: number = Math.floor(left + (right - left) / 2); + const cnt: number = + Math.floor(mid / a) + + Math.floor(mid / b) + + Math.floor(mid / c) - + Math.floor(mid / ab) - + Math.floor(mid / ac) - + Math.floor(mid / bc) + + Math.floor(mid / abc); + if (cnt >= n) { + right = mid; + } else { + left = mid + 1; + } + } + + return left; +} diff --git a/tests/1001-1500/1202. smallest-string-with-swaps/manifest.yaml b/tests/1001-1500/1202. smallest-string-with-swaps/manifest.yaml new file mode 100644 index 00000000..f47aad20 --- /dev/null +++ b/tests/1001-1500/1202. smallest-string-with-swaps/manifest.yaml @@ -0,0 +1,457 @@ +entry: + id: 1202 + title: smallest-string-with-swaps + params: + s: + type: string + pairs: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().smallestStringWithSwaps({s}, {pairs})" + rust: "Solution::smallest_string_with_swaps({s}, {pairs})" + python3: "Solution().smallestStringWithSwaps({s}, {pairs})" + python2: "Solution().smallestStringWithSwaps({s}, {pairs})" + ruby: "smallest_string_with_swaps({s}, {pairs})" + java: "new Solution().smallestStringWithSwaps({s}, {pairs})" + csharp: "new Solution().SmallestStringWithSwaps({s}, {pairs})" + kotlin: "Solution().smallestStringWithSwaps({s}, {pairs})" + go: "smallestStringWithSwaps({s}, {pairs})" + dart: "Solution().smallestStringWithSwaps({s}, {pairs})" + swift: "Solution().smallestStringWithSwaps({s}, {pairs})" + typescript: "smallestStringWithSwaps({s}, {pairs})" +judge: + type: exact +limits: + time_ms: 1500 + memory_mb: 256 +oracle: + python3: + call: "Checker().smallestStringWithSwaps(s, pairs, {result})" + checker: | + class Checker: + def smallestStringWithSwaps(self, s, pairs, result): + if not isinstance(s, str) or not isinstance(pairs, list) or not isinstance(result, str): + return False + if len(result) != len(s): + return False + parent = list(range(len(s))) + + def find(x): + while parent[x] != x: + parent[x] = parent[parent[x]] + x = parent[x] + return x + + for pair in pairs: + if not isinstance(pair, list) or len(pair) != 2: + return False + a, b = pair + if not isinstance(a, int) or not isinstance(b, int): + return False + if not 0 <= a < len(s) or not 0 <= b < len(s): + return False + ra, rb = find(a), find(b) + if ra != rb: + parent[ra] = rb + + components = {} + for index in range(len(s)): + components.setdefault(find(index), []).append(index) + expected = list(s) + for indices in components.values(): + for index, char in zip(sorted(indices), sorted(s[index] for index in indices)): + expected[index] = char + return result == ''.join(expected) +seed: 1202 +tests: + - name: example_one + in: + s: dcab + pairs: + - [0, 3] + - [1, 2] + out: bacd + - name: example_two + in: + s: dcab + pairs: + - [0, 3] + - [1, 2] + - [0, 2] + out: abcd + - name: example_three + in: + s: cba + pairs: + - [0, 1] + - [1, 2] + out: abc + - name: no_pairs + in: + s: zyxwv + pairs: [] + out: zyxwv + - name: single_character + in: + s: q + pairs: [] + out: q + - name: one_swap + in: + s: ba + pairs: + - [0, 1] + out: ab + - name: already_smallest_with_swaps + in: + s: abcde + pairs: + - [0, 4] + - [1, 3] + out: abcde + - name: reverse_full_component + in: + s: edcba + pairs: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + out: abcde + - name: transitive_chain + in: + s: zyxw + pairs: + - [0, 1] + - [1, 2] + - [2, 3] + out: wxyz + - name: disconnected_components + in: + s: zyxwvuts + pairs: + - [0, 1] + - [2, 3] + - [4, 5] + out: yzwxuvts + - name: duplicate_and_reversed_edges + in: + s: cba + pairs: + - [0, 1] + - [0, 1] + - [1, 0] + out: bca + - name: self_pairs_only + in: + s: cabd + pairs: + - [0, 0] + - [2, 2] + out: cabd + - name: repeated_letters + in: + s: bbaca + pairs: + - [0, 4] + - [1, 2] + - [2, 3] + out: aabcb + - name: two_components_mixed_sizes + in: + s: hgfedcba + pairs: + - [0, 2] + - [1, 3] + - [4, 7] + out: fehgacbd + - name: isolated_middle + in: + s: zabczy + pairs: + - [0, 5] + - [1, 2] + - [2, 3] + out: yabczz + - name: all_same_characters + in: + s: aaaaaa + pairs: + - [0, 5] + - [1, 4] + out: aaaaaa + - name: pair_order_irrelevant + in: + s: qponml + pairs: + - [4, 1] + - [5, 0] + - [3, 2] + out: lmnopq + - name: alternating_components + in: + s: zyxwvuts + pairs: + - [0, 2] + - [2, 4] + - [1, 3] + - [3, 5] + out: vuxwzyts + - name: noncontiguous_components + in: + s: kjihgfedcba + pairs: + - [0, 5] + - [5, 10] + - [2, 8] + out: ajchgfedibk + - name: lexicographic_rotation + in: + s: bdac + pairs: + - [0, 1] + - [1, 2] + - [2, 3] + out: abcd + - name: two_components_of_two + in: + s: zyxwvu + pairs: + - [0, 1] + - [3, 4] + out: yzxvwu + - name: nested_union + in: + s: fdbcae + pairs: + - [0, 1] + - [1, 4] + - [2, 3] + - [3, 5] + out: adbcfe + - name: sparse_swaps + in: + s: qwertyui + pairs: + - [0, 7] + - [2, 5] + out: iwertyuq + - name: long_chain + in: + s: jihgfedcba + pairs: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + out: abcdefghij + - name: two_disjoint_swaps + in: + s: dcba + pairs: + - [0, 1] + - [2, 3] + out: cdab + - name: component_with_gaps + in: + s: zyxwv + pairs: + - [0, 2] + - [2, 4] + out: vyxwz + - name: bridge_connects_components + in: + s: edcba + pairs: + - [0, 1] + - [3, 4] + - [1, 3] + out: abcde + - name: singleton_components + in: + s: abcdef + pairs: + - [1, 1] + - [3, 3] + out: abcdef + - name: reverse_pairs + in: + s: hgfedcba + pairs: + - [7, 0] + - [6, 1] + - [5, 2] + out: abcedfgh + - name: repeated_transitive_edges + in: + s: zyxwv + pairs: + - [0, 1] + - [1, 2] + - [0, 2] + - [2, 3] + out: wxyzv + - name: mixed_singletons_and_chain + in: + s: qponmlk + pairs: + - [0, 6] + - [2, 3] + out: kpnomlq + - name: alphabet_with_no_connectivity + in: + s: abcdefghijklmnopqrstuvwxyz + pairs: [] + out: abcdefghijklmnopqrstuvwxyz + - name: separate_repeated_groups + in: + s: ccbbaa + pairs: + - [0, 2] + - [2, 4] + - [1, 3] + - [3, 5] + out: aabbcc + - name: late_bridge_merges_groups + in: + s: gfedcba + pairs: + - [0, 2] + - [4, 6] + - [2, 4] + out: afcdebg + - name: stress_maximum_length_and_pairs + seed: 120201 + in: + s: + gen: str + len: 100000 + alphabet: abcdefghijklmnopqrstuvwxyz + pairs: + gen: array + len: 100000 + of: + gen: array + len: 2 + of: + gen: int + min: 0 + max: 99999 + distinct: false + sorted: false + distinct: false + sorted: false + - name: stress_many_edges + seed: 120202 + in: + s: + gen: str + len: 75000 + alphabet: abcdefghijklmnopqrstuvwxyz + pairs: + gen: array + len: 100000 + of: + gen: array + len: 2 + of: + gen: int + min: 0 + max: 74999 + distinct: false + sorted: false + distinct: false + sorted: false + - name: stress_large_balanced + seed: 120203 + in: + s: + gen: str + len: 50000 + alphabet: abcdefghijklmnopqrstuvwxyz + pairs: + gen: array + len: 75000 + of: + gen: array + len: 2 + of: + gen: int + min: 0 + max: 49999 + distinct: false + sorted: false + distinct: false + sorted: false + - name: stress_large_sparse_graph + seed: 120204 + in: + s: + gen: str + len: 25000 + alphabet: abcdefghijklmnopqrstuvwxyz + pairs: + gen: array + len: 50000 + of: + gen: array + len: 2 + of: + gen: int + min: 0 + max: 24999 + distinct: false + sorted: false + distinct: false + sorted: false + - name: stress_medium_random_graph + seed: 120205 + in: + s: + gen: str + len: 10000 + alphabet: abcdefghijklmnopqrstuvwxyz + pairs: + gen: array + len: 20000 + of: + gen: array + len: 2 + of: + gen: int + min: 0 + max: 9999 + distinct: false + sorted: false + distinct: false + sorted: false + - name: stress_dense_small_alphabet + seed: 120206 + in: + s: + gen: str + len: 5000 + alphabet: abc + pairs: + gen: array + len: 10000 + of: + gen: array + len: 2 + of: + gen: int + min: 0 + max: 4999 + distinct: false + sorted: false + distinct: false + sorted: false diff --git a/tests/1001-1500/1202. smallest-string-with-swaps/sol.cpp b/tests/1001-1500/1202. smallest-string-with-swaps/sol.cpp new file mode 100644 index 00000000..1641bab5 --- /dev/null +++ b/tests/1001-1500/1202. smallest-string-with-swaps/sol.cpp @@ -0,0 +1,42 @@ +class Solution { +public: + string smallestStringWithSwaps(string s, vector>& pairs) { + int n = s.size(); + vector parent(n); + for (int i = 0; i < n; i++) parent[i] = i; + + function find = [&](int x) -> int { + if (parent[x] != x) { + parent[x] = find(parent[x]); + } + return parent[x]; + }; + + auto union_set = [&](int x, int y) { + int rx = find(x), ry = find(y); + if (rx != ry) parent[rx] = ry; + }; + + for (auto& pair : pairs) { + union_set(pair[0], pair[1]); + } + + unordered_map> groups; + for (int i = 0; i < n; i++) { + groups[find(i)].push_back(i); + } + + string res(n, ' '); + for (auto& [root, indices] : groups) { + vector chars; + for (int idx : indices) chars.push_back(s[idx]); + sort(indices.begin(), indices.end()); + sort(chars.begin(), chars.end()); + for (int k = 0; k < indices.size(); k++) { + res[indices[k]] = chars[k]; + } + } + + return res; + } +}; diff --git a/tests/1001-1500/1202. smallest-string-with-swaps/sol.cs b/tests/1001-1500/1202. smallest-string-with-swaps/sol.cs new file mode 100644 index 00000000..6a00987f --- /dev/null +++ b/tests/1001-1500/1202. smallest-string-with-swaps/sol.cs @@ -0,0 +1,47 @@ +public class Solution { + public string SmallestStringWithSwaps(string s, IList> pairs) { + int n = s.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 Union(int x, int y) { + int rx = Find(x), ry = Find(y); + if (rx != ry) parent[rx] = ry; + } + + foreach (var pair in pairs) { + Union(pair[0], pair[1]); + } + + Dictionary> 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(i); + } + + char[] res = new char[n]; + foreach (var indices in groups.Values) { + List chars = new List(); + foreach (int idx in indices) { + chars.Add(s[idx]); + } + indices.Sort(); + chars.Sort(); + for (int k = 0; k < indices.Count; k++) { + res[indices[k]] = chars[k]; + } + } + + return new string(res); + } +} diff --git a/tests/1001-1500/1202. smallest-string-with-swaps/sol.dart b/tests/1001-1500/1202. smallest-string-with-swaps/sol.dart new file mode 100644 index 00000000..e57c7213 --- /dev/null +++ b/tests/1001-1500/1202. smallest-string-with-swaps/sol.dart @@ -0,0 +1,43 @@ +class Solution { + String smallestStringWithSwaps(String s, List> pairs) { + int n = s.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 union(int x, int y) { + int rx = find(x); + int ry = find(y); + if (rx != ry) { + parent[rx] = ry; + } + } + + for (var pair in pairs) { + union(pair[0], pair[1]); + } + + Map> groups = {}; + for (int i = 0; i < n; i++) { + int root = find(i); + groups.putIfAbsent(root, () => []).add(i); + } + + List res = List.filled(n, ''); + for (var indices in groups.values) { + List chars = indices.map((i) => s[i]).toList(); + indices.sort(); + chars.sort(); + for (int k = 0; k < indices.length; k++) { + res[indices[k]] = chars[k]; + } + } + + return res.join(''); + } +} diff --git a/tests/1001-1500/1202. smallest-string-with-swaps/sol.go b/tests/1001-1500/1202. smallest-string-with-swaps/sol.go new file mode 100644 index 00000000..92e8661d --- /dev/null +++ b/tests/1001-1500/1202. smallest-string-with-swaps/sol.go @@ -0,0 +1,47 @@ +func smallestStringWithSwaps(s string, pairs [][]int) string { + n := len(s) + parent := make([]int, n) + for i := 0; i < n; i++ { + 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] + } + + union := func(x, y int) { + rx, ry := find(x), find(y) + if rx != ry { + parent[rx] = ry + } + } + + for _, pair := range pairs { + union(pair[0], pair[1]) + } + + groups := make(map[int][]int) + for i := 0; i < n; i++ { + root := find(i) + groups[root] = append(groups[root], i) + } + + res := make([]byte, n) + for _, indices := range groups { + chars := make([]byte, len(indices)) + for k, idx := range indices { + chars[k] = s[idx] + } + sort.Ints(indices) + sort.Slice(chars, func(i, j int) bool { return chars[i] < chars[j] }) + for k, idx := range indices { + res[idx] = chars[k] + } + } + + return string(res) +} diff --git a/tests/1001-1500/1202. smallest-string-with-swaps/sol.java b/tests/1001-1500/1202. smallest-string-with-swaps/sol.java new file mode 100644 index 00000000..3301d443 --- /dev/null +++ b/tests/1001-1500/1202. smallest-string-with-swaps/sol.java @@ -0,0 +1,50 @@ +class Solution { + public String smallestStringWithSwaps(String s, int[][] pairs) { + int n = s.length(); + int[] parent = new int[n]; + for (int i = 0; i < n; i++) { + parent[i] = i; + } + + for (int[] pair : pairs) { + int x = pair[0], y = pair[1]; + union(parent, x, y); + } + + Map> groups = new HashMap<>(); + for (int i = 0; i < n; i++) { + int root = find(parent, i); + groups.computeIfAbsent(root, k -> new ArrayList<>()).add(i); + } + + char[] res = new char[n]; + for (List indices : groups.values()) { + List chars = new ArrayList<>(); + for (int idx : indices) { + chars.add(s.charAt(idx)); + } + Collections.sort(indices); + Collections.sort(chars); + for (int k = 0; k < indices.size(); k++) { + res[indices.get(k)] = chars.get(k); + } + } + + return new String(res); + } + + private int find(int[] parent, int x) { + if (parent[x] != x) { + parent[x] = find(parent, parent[x]); + } + return parent[x]; + } + + private void union(int[] parent, int x, int y) { + int rx = find(parent, x); + int ry = find(parent, y); + if (rx != ry) { + parent[rx] = ry; + } + } +} diff --git a/tests/1001-1500/1202. smallest-string-with-swaps/sol.kt b/tests/1001-1500/1202. smallest-string-with-swaps/sol.kt new file mode 100644 index 00000000..e73ceae8 --- /dev/null +++ b/tests/1001-1500/1202. smallest-string-with-swaps/sol.kt @@ -0,0 +1,43 @@ +class Solution { + fun smallestStringWithSwaps(s: String, pairs: Array): String { + val n = s.length + val parent = IntArray(n) { it } + + fun find(x: Int): Int { + if (parent[x] != x) { + parent[x] = find(parent[x]) + } + return parent[x] + } + + fun union(x: Int, y: Int) { + val rx = find(x) + val ry = find(y) + if (rx != ry) { + parent[rx] = ry + } + } + + for (pair in pairs) { + union(pair[0], pair[1]) + } + + val groups = mutableMapOf>() + for (i in 0 until n) { + val root = find(i) + groups.getOrPut(root) { mutableListOf() }.add(i) + } + + val res = CharArray(n) + for (indices in groups.values) { + val chars = indices.map { s[it] }.toMutableList() + indices.sort() + chars.sort() + for (k in indices.indices) { + res[indices[k]] = chars[k] + } + } + + return String(res) + } +} diff --git a/tests/1001-1500/1202. smallest-string-with-swaps/sol.py b/tests/1001-1500/1202. smallest-string-with-swaps/sol.py new file mode 100644 index 00000000..cd522b84 --- /dev/null +++ b/tests/1001-1500/1202. smallest-string-with-swaps/sol.py @@ -0,0 +1,41 @@ +from collections import defaultdict + + +class UnionFind: + def __init__(self, n): + self.parents = list(range(n)) + + def find(self, x): + if x != self.parents[x]: + self.parents[x] = self.find(self.parents[x]) + return self.parents[x] + + def union(self, x, y): + x, y = self.find(x), self.find(y) + if x != y: + self.parents[x] = y + return True + return False + + +class Solution: + def smallestStringWithSwaps(self, s: str, pairs: list[list[int]]) -> str: + n = len(s) + uf = UnionFind(n) + groups = defaultdict(list) + + for i, j in pairs: + uf.union(i, j) + + res = [""] * n + for i in range(n): + groups[uf.find(i)].append(i) + + for indices in groups.values(): + chars = [s[i] for i in indices] + indices.sort() + chars.sort() + for k, ch in zip(indices, chars): + res[k] = ch + + return "".join(res) diff --git a/tests/1001-1500/1202. smallest-string-with-swaps/sol.py2 b/tests/1001-1500/1202. smallest-string-with-swaps/sol.py2 new file mode 100644 index 00000000..f33bf558 --- /dev/null +++ b/tests/1001-1500/1202. smallest-string-with-swaps/sol.py2 @@ -0,0 +1,39 @@ +class Solution(object): + def smallestStringWithSwaps(self, s, pairs): + """ + :type s: str + :type pairs: List[List[int]] + :rtype: str + """ + n = len(s) + parent = list(range(n)) + + def find(x): + if parent[x] != x: + parent[x] = find(parent[x]) + return parent[x] + + def union(x, y): + rx, ry = find(x), find(y) + if rx != ry: + parent[rx] = ry + + for i, j in pairs: + union(i, j) + + groups = {} + for i in range(n): + root = find(i) + if root not in groups: + groups[root] = [] + groups[root].append(i) + + res = [''] * n + for indices in groups.values(): + chars = [s[i] for i in indices] + indices.sort() + chars.sort() + for idx, ch in zip(indices, chars): + res[idx] = ch + + return ''.join(res) diff --git a/tests/1001-1500/1202. smallest-string-with-swaps/sol.rb b/tests/1001-1500/1202. smallest-string-with-swaps/sol.rb new file mode 100644 index 00000000..8ed9b486 --- /dev/null +++ b/tests/1001-1500/1202. smallest-string-with-swaps/sol.rb @@ -0,0 +1,37 @@ +# @param {String} s +# @param {Integer[][]} pairs +# @return {String} +def smallest_string_with_swaps(s, pairs) + n = s.length + parent = (0...n).to_a + + find = ->(x) { + if parent[x] != x + parent[x] = find.call(parent[x]) + end + parent[x] + } + + union = ->(x, y) { + rx = find.call(x) + ry = find.call(y) + if rx != ry + parent[rx] = ry + end + } + + pairs.each { |i, j| union.call(i, j) } + + groups = Hash.new { |h, k| h[k] = [] } + (0...n).each { |i| groups[find.call(i)] << i } + + res = Array.new(n) + groups.each_value do |indices| + chars = indices.map { |i| s[i] } + indices.sort! + chars.sort! + indices.zip(chars).each { |idx, ch| res[idx] = ch } + end + + res.join +end diff --git a/tests/1001-1500/1202. smallest-string-with-swaps/sol.rs b/tests/1001-1500/1202. smallest-string-with-swaps/sol.rs new file mode 100644 index 00000000..57c3bd38 --- /dev/null +++ b/tests/1001-1500/1202. smallest-string-with-swaps/sol.rs @@ -0,0 +1,46 @@ +impl Solution { + pub fn smallest_string_with_swaps(s: String, pairs: Vec>) -> String { + let n = s.len(); + let mut parent: Vec = (0..n).collect(); + let chars: Vec = s.chars().collect(); + + 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, x: usize, y: usize) { + let rx = find(parent, x); + let ry = find(parent, y); + if rx != ry { + parent[rx] = ry; + } + } + + for pair in &pairs { + union(&mut parent, pair[0] as usize, pair[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_with(Vec::new).push(i); + } + + let mut res: Vec = vec![' '; n]; + for indices in groups.values() { + let mut sorted_indices = indices.clone(); + sorted_indices.sort(); + let mut sorted_chars: Vec = indices.iter().map(|&i| chars[i]).collect(); + sorted_chars.sort(); + for (idx, ch) in sorted_indices.iter().zip(sorted_chars.iter()) { + res[*idx] = *ch; + } + } + + res.into_iter().collect() + } +} diff --git a/tests/1001-1500/1202. smallest-string-with-swaps/sol.swift b/tests/1001-1500/1202. smallest-string-with-swaps/sol.swift new file mode 100644 index 00000000..762f9ab8 --- /dev/null +++ b/tests/1001-1500/1202. smallest-string-with-swaps/sol.swift @@ -0,0 +1,43 @@ +class Solution { + func smallestStringWithSwaps(_ s: String, _ pairs: [[Int]]) -> String { + let n = s.count + var parent = Array(0.. Int { + if parent[x] != x { + parent[x] = find(parent[x]) + } + return parent[x] + } + + func union(_ x: Int, _ y: Int) { + let rx = find(x) + let ry = find(y) + if rx != ry { + parent[rx] = ry + } + } + + for pair in pairs { + union(pair[0], pair[1]) + } + + var groups = [Int: [Int]]() + for i in 0.. i); + + function find(x: number): number { + if (parent[x] !== x) { + parent[x] = find(parent[x]); + } + return parent[x]; + } + + function union(x: number, y: number): void { + const rx = find(x); + const ry = find(y); + if (rx !== ry) { + parent[rx] = ry; + } + } + + for (const [i, j] of pairs) { + union(i, j); + } + + const groups = new Map(); + for (let i = 0; i < n; i++) { + const root = find(i); + if (!groups.has(root)) { + groups.set(root, []); + } + groups.get(root)!.push(i); + } + + const res: string[] = new Array(n); + for (const indices of groups.values()) { + const chars = indices.map((i) => s[i]); + indices.sort((a, b) => a - b); + chars.sort(); + for (let k = 0; k < indices.length; k++) { + res[indices[k]] = chars[k]; + } + } + + return res.join(""); +} diff --git a/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/manifest.yaml b/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/manifest.yaml new file mode 100644 index 00000000..78ba2511 --- /dev/null +++ b/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/manifest.yaml @@ -0,0 +1,428 @@ +entry: + id: 1203 + title: sort-items-by-groups-respecting-dependencies + params: + n: + type: int + m: + type: int + group: + type: array + items: + type: int + beforeItems: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().sortItems({n}, {m}, {group}, {beforeItems})" + rust: "Solution::sort_items({n}, {m}, {group}, {beforeItems})" + python3: "Solution().sortItems({n}, {m}, {group}, {beforeItems})" + python2: "Solution().sortItems({n}, {m}, {group}, {beforeItems})" + ruby: "sort_items({n}, {m}, {group}, {beforeItems})" + java: "new Solution().sortItems({n}, {m}, {group}, {beforeItems})" + csharp: "new Solution().SortItems({n}, {m}, {group}, {beforeItems})" + kotlin: "Solution().sortItems({n}, {m}, {group}, {beforeItems})" + go: "sortItems({n}, {m}, {group}, {beforeItems})" + dart: "Solution().sortItems({n}, {m}, {group}, {beforeItems})" + swift: "Solution().sortItems({n}, {m}, {group}, {beforeItems})" + typescript: "sortItems({n}, {m}, {group}, {beforeItems})" +judge: + type: exact +limits: + time_ms: 5000 + memory_mb: 256 +oracle: + python3: + call: "Checker().sortItems(n, m, group, beforeItems, {result})" + checker: | + class Checker: + def sortItems(self, n, m, group, beforeItems, result): + if not isinstance(result, list) or result == [] or len(result) != n: + return False + if sorted(result) != list(range(n)): + return False + position = [0] * n + for index, item in enumerate(result): + position[item] = index + for item, predecessors in enumerate(beforeItems): + for before in predecessors: + if position[before] >= position[item]: + return False + first = [n] * m + last = [-1] * m + count = [0] * m + for item, item_group in enumerate(group): + if 0 <= item_group < m: + index = position[item] + first[item_group] = min(first[item_group], index) + last[item_group] = max(last[item_group], index) + count[item_group] += 1 + for item_group in range(m): + if count[item_group] and last[item_group] - first[item_group] + 1 != count[item_group]: + return False + return True +seed: 1203 +tests: + - name: simple_groups + in: + n: 8 + m: 2 + group: [0, 0, 1, 1, -1, -1, 0, 1] + beforeItems: [[], [0], [1], [2], [3], [], [1], [2]] + - name: example_style + in: + n: 8 + m: 2 + group: [-1, -1, 1, 0, 0, 1, 0, -1] + beforeItems: [[], [6], [5], [6], [3, 6], [], [4], []] + out: [] + - name: no_dependencies + in: + n: 5 + m: 2 + group: [0, 0, 1, -1, 1] + beforeItems: [[], [], [], [], []] + - name: all_ungrouped + in: + n: 4 + m: 1 + group: [-1, -1, -1, -1] + beforeItems: [[], [0], [1], [2]] + - name: one_group_chain + in: + n: 5 + m: 1 + group: [0, 0, 0, 0, 0] + beforeItems: [[], [0], [1], [2], [3]] + - name: cycle_items + in: + n: 3 + m: 1 + group: [0, 0, 0] + beforeItems: [[2], [0], [1]] + out: [] + - name: cycle_between_groups + in: + n: 4 + m: 2 + group: [0, 0, 1, 1] + beforeItems: [[], [2], [1], []] + out: [] + - name: cross_group_order + in: + n: 6 + m: 3 + group: [0, 0, 1, 1, 2, 2] + beforeItems: [[], [0], [1], [2], [3], [4]] + - name: ungrouped_between_groups + in: + n: 6 + m: 2 + group: [0, -1, 1, 0, -1, 1] + beforeItems: [[], [0], [1], [0], [2], [3]] + - name: branching_dependencies + in: + n: 7 + m: 2 + group: [0, 0, 1, 1, 0, 1, -1] + beforeItems: [[], [], [0], [0], [1], [2, 4], [3]] + - name: diamond_graph + in: + n: 6 + m: 2 + group: [0, 0, 1, 1, 0, 1] + beforeItems: [[], [0], [0], [0], [1], [2, 3]] + - name: empty_group_slots + in: + n: 4 + m: 4 + group: [0, 3, 3, 0] + beforeItems: [[], [0], [1], [0]] + - name: duplicate_free_edges + in: + n: 5 + m: 2 + group: [0, 1, 0, 1, -1] + beforeItems: [[], [0], [0], [1], [2, 3]] + - name: independent_components + in: + n: 8 + m: 4 + group: [0, 0, 1, 1, 2, 2, 3, 3] + beforeItems: [[], [0], [], [2], [], [4], [], [6]] + - name: single_item + in: + n: 1 + m: 1 + group: [-1] + beforeItems: [[]] + - name: all_items_separate_groups + in: + n: 5 + m: 5 + group: [0, 1, 2, 3, 4] + beforeItems: [[], [0], [1], [2], [3]] + - name: negative_group_mix + in: + n: 7 + m: 2 + group: [-1, 0, -1, 1, 0, 1, -1] + beforeItems: [[], [0], [1], [2], [1], [3], [4]] + - name: same_group_constraints + in: + n: 6 + m: 2 + group: [0, 0, 0, 1, 1, 1] + beforeItems: [[], [0], [1], [], [3], [4]] + - name: late_cross_edge + in: + n: 6 + m: 2 + group: [0, 0, 1, 1, 0, 1] + beforeItems: [[], [], [1], [2], [0], []] + - name: two_independent_groups + in: + n: 6 + m: 2 + group: [0, 0, 0, 1, 1, 1] + beforeItems: [[], [0], [1], [], [3], [4]] + - name: group_order_only + in: + n: 5 + m: 3 + group: [0, 1, 2, 1, 0] + beforeItems: [[], [0], [1], [1], []] + - name: ungrouped_dependency_chain + in: + n: 5 + m: 2 + group: [-1, 0, -1, 1, -1] + beforeItems: [[], [0], [1], [2], [3]] + - name: intra_group_branch + in: + n: 6 + m: 1 + group: [0, 0, 0, 0, 0, 0] + beforeItems: [[], [], [0], [0], [2, 3], [1]] + - name: cycle_single_group + in: + n: 4 + m: 1 + group: [0, 0, 0, 0] + beforeItems: [[1], [2], [3], [0]] + out: [] + - name: empty_middle_group + in: + n: 5 + m: 5 + group: [0, 4, 0, 4, 0] + beforeItems: [[], [0], [], [], [2]] + - name: multiple_roots + in: + n: 8 + m: 3 + group: [0, 1, 2, 0, 1, 2, -1, -1] + beforeItems: [[], [], [], [0], [1], [2], [3, 4], [5]] + - name: cross_group_fanout + in: + n: 7 + m: 3 + group: [0, 1, 2, 1, 2, 0, -1] + beforeItems: [[], [0], [0], [0], [0], [0], [3, 4]] + - name: disconnected_ungrouped + in: + n: 6 + m: 1 + group: [-1, -1, 0, 0, -1, 0] + beforeItems: [[], [], [0], [1], [], [2, 3]] + - name: wide_no_edges + in: + n: 10 + m: 3 + group: [0, 1, 2, 0, 1, 2, -1, -1, 0, 2] + beforeItems: [[], [], [], [], [], [], [], [], [], []] + - name: long_chain_groups + in: + n: 10 + m: 3 + group: [0, 0, 1, 1, 2, 2, 0, 1, 2, -1] + beforeItems: [[], [0], [1], [2], [3], [4], [0], [2], [4], [8]] + - name: official_example_one + in: + n: 8 + m: 2 + group: [-1, -1, 1, 0, 0, 1, 0, -1] + beforeItems: [[], [6], [5], [6], [3, 6], [], [], []] + - name: repeated_cross_group_edges + in: + n: 6 + m: 2 + group: [0, 0, 0, 1, 1, 1] + beforeItems: [[], [], [], [0], [1], [2]] + - name: three_group_cycle_without_item_cycle + in: + n: 6 + m: 3 + group: [0, 0, 1, 1, 2, 2] + beforeItems: [[5], [], [1], [], [3], []] + out: [] + - name: inter_and_intra_group_dependencies + in: + n: 9 + m: 3 + group: [0, 0, 0, 1, 1, 1, 2, 2, 2] + beforeItems: [[], [0], [1], [2], [3], [3, 4], [5], [6], [6, 7]] + - name: sparse_assigned_groups + in: + n: 7 + m: 7 + group: [0, 6, -1, 0, 6, -1, 0] + beforeItems: [[], [0], [1], [0], [1], [2], [3]] + - name: generated_max_all_assigned_one_group + seed: 101 + in: + n: 30000 + m: 1 + group: + gen: array + len: 30000 + of: + gen: int + min: 0 + max: 0 + distinct: false + sorted: false + elemType: int + beforeItems: + gen: array + len: 30000 + of: + gen: array + len: 0 + of: + gen: int + min: 0 + max: 29999 + distinct: false + sorted: false + distinct: false + sorted: false + - name: generated_max_all_ungrouped + seed: 202 + in: + n: 30000 + m: 1 + group: + gen: array + len: 30000 + of: + gen: int + min: -1 + max: -1 + distinct: false + sorted: false + elemType: int + beforeItems: + gen: array + len: 30000 + of: + gen: array + len: 0 + of: + gen: int + min: 0 + max: 29999 + distinct: false + sorted: false + distinct: false + sorted: false + - name: generated_max_random_groups + seed: 303 + in: + n: 30000 + m: 15000 + group: + gen: array + len: 30000 + of: + gen: int + min: -1 + max: 14999 + distinct: false + sorted: false + elemType: int + beforeItems: + gen: array + len: 30000 + of: + gen: array + len: 0 + of: + gen: int + min: 0 + max: 29999 + distinct: false + sorted: false + distinct: false + sorted: false + - name: generated_many_group_slots + seed: 404 + in: + n: 24000 + m: 24000 + group: + gen: array + len: 24000 + of: + gen: int + min: -1 + max: 23999 + distinct: false + sorted: false + elemType: int + beforeItems: + gen: array + len: 24000 + of: + gen: array + len: 0 + of: + gen: int + min: 0 + max: 23999 + distinct: false + sorted: false + distinct: false + sorted: false + - name: generated_large_few_groups + seed: 505 + in: + n: 2000 + m: 17 + group: + gen: array + len: 2000 + of: + gen: int + min: -1 + max: 16 + distinct: false + sorted: false + elemType: int + beforeItems: + gen: array + len: 2000 + of: + gen: array + len: 0 + of: + gen: int + min: 0 + max: 17999 + distinct: false + sorted: false + distinct: false + sorted: false diff --git a/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.cpp b/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.cpp new file mode 100644 index 00000000..4a18fad3 --- /dev/null +++ b/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.cpp @@ -0,0 +1,59 @@ +class Solution { +public: + vector sortItems(int n, int m, vector& group, vector>& beforeItems) { + unordered_map> groupToItems; + int newGroup = m; + for (int i = 0; i < n; i++) { + if (group[i] == -1) group[i] = newGroup++; + groupToItems[group[i]].insert(i); + } + + unordered_map> intraPred, intraSucc; + unordered_map> interPred, interSucc; + + for (int i = 0; i < n; i++) { + for (int before : beforeItems[i]) { + if (group[i] == group[before]) { + intraPred[i].insert(before); + intraSucc[before].insert(i); + } else { + interPred[group[i]].insert(group[before]); + interSucc[group[before]].insert(group[i]); + } + } + } + + auto topologicalSort = [](vector nodes, + unordered_map>& pred, + unordered_map>& succ) -> vector { + vector order; + queue q; + for (int node : nodes) { + if (pred[node].empty()) q.push(node); + } + while (!q.empty()) { + int node = q.front(); q.pop(); + order.push_back(node); + for (int s : succ[node]) { + pred[s].erase(node); + if (pred[s].empty()) q.push(s); + } + } + return order.size() == nodes.size() ? order : vector(); + }; + + vector groupNodes; + for (auto& p : groupToItems) groupNodes.push_back(p.first); + auto groupsOrder = topologicalSort(groupNodes, interPred, interSucc); + if (groupsOrder.empty()) return {}; + + vector result; + for (int grp : groupsOrder) { + vector items(groupToItems[grp].begin(), groupToItems[grp].end()); + auto order = topologicalSort(items, intraPred, intraSucc); + if (order.empty()) return {}; + result.insert(result.end(), order.begin(), order.end()); + } + return result; + } +}; diff --git a/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.cs b/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.cs new file mode 100644 index 00000000..38ac28fe --- /dev/null +++ b/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.cs @@ -0,0 +1,62 @@ +public class Solution { + public int[] SortItems(int n, int m, int[] group, IList> beforeItems) { + var groupToItems = new Dictionary>(); + int newGroup = m; + for (int i = 0; i < n; i++) { + if (group[i] == -1) group[i] = newGroup++; + if (!groupToItems.ContainsKey(group[i])) groupToItems[group[i]] = new HashSet(); + groupToItems[group[i]].Add(i); + } + + var intraPred = new Dictionary>(); + var intraSucc = new Dictionary>(); + var interPred = new Dictionary>(); + var interSucc = new Dictionary>(); + + for (int i = 0; i < n; i++) { + foreach (int before in beforeItems[i]) { + if (group[i] == group[before]) { + if (!intraPred.ContainsKey(i)) intraPred[i] = new HashSet(); + intraPred[i].Add(before); + if (!intraSucc.ContainsKey(before)) intraSucc[before] = new HashSet(); + intraSucc[before].Add(i); + } else { + if (!interPred.ContainsKey(group[i])) interPred[group[i]] = new HashSet(); + interPred[group[i]].Add(group[before]); + if (!interSucc.ContainsKey(group[before])) interSucc[group[before]] = new HashSet(); + interSucc[group[before]].Add(group[i]); + } + } + } + + List TopoSort(HashSet nodes, Dictionary> pred, Dictionary> succ) { + var order = new List(); + var queue = new Queue(); + foreach (int node in nodes) { + if (!pred.ContainsKey(node) || pred[node].Count == 0) queue.Enqueue(node); + } + while (queue.Count > 0) { + int node = queue.Dequeue(); + order.Add(node); + if (succ.ContainsKey(node)) { + foreach (int s in succ[node]) { + if (pred.ContainsKey(s)) pred[s].Remove(node); + if (!pred.ContainsKey(s) || pred[s].Count == 0) queue.Enqueue(s); + } + } + } + return order.Count == nodes.Count ? order : new List(); + } + + var groupsOrder = TopoSort(new HashSet(groupToItems.Keys), interPred, interSucc); + if (groupsOrder.Count == 0) return new int[0]; + + var result = new List(); + foreach (int grp in groupsOrder) { + var order = TopoSort(groupToItems[grp], intraPred, intraSucc); + if (order.Count == 0) return new int[0]; + result.AddRange(order); + } + return result.ToArray(); + } +} diff --git a/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.dart b/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.dart new file mode 100644 index 00000000..f5845664 --- /dev/null +++ b/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.dart @@ -0,0 +1,55 @@ +class Solution { + List sortItems(int n, int m, List group, List> beforeItems) { + var groupToItems = >{}; + int newGroup = m; + for (int i = 0; i < n; i++) { + if (group[i] == -1) group[i] = newGroup++; + groupToItems.putIfAbsent(group[i], () => {}).add(i); + } + + var intraPred = >{}; + var intraSucc = >{}; + var interPred = >{}; + var interSucc = >{}; + + for (int i = 0; i < n; i++) { + for (var before in beforeItems[i]) { + if (group[i] == group[before]) { + intraPred.putIfAbsent(i, () => {}).add(before); + intraSucc.putIfAbsent(before, () => {}).add(i); + } else { + interPred.putIfAbsent(group[i], () => {}).add(group[before]); + interSucc.putIfAbsent(group[before], () => {}).add(group[i]); + } + } + } + + List topoSort(Set nodes, Map> pred, Map> succ) { + var order = []; + var queue = Queue(); + for (var node in nodes) { + if (pred[node]?.isEmpty ?? true) queue.add(node); + } + while (queue.isNotEmpty) { + var node = queue.removeFirst(); + order.add(node); + for (var s in succ[node] ?? {}) { + pred[s]?.remove(node); + if (pred[s]?.isEmpty ?? true) queue.add(s); + } + } + return order.length == nodes.length ? order : []; + } + + var groupsOrder = topoSort(groupToItems.keys.toSet(), interPred, interSucc); + if (groupsOrder.isEmpty) return []; + + List result = []; + for (var grp in groupsOrder) { + var order = topoSort(groupToItems[grp]!, intraPred, intraSucc); + if (order.isEmpty) return []; + result.addAll(order); + } + return result; + } +} diff --git a/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.go b/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.go new file mode 100644 index 00000000..651b2fea --- /dev/null +++ b/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.go @@ -0,0 +1,76 @@ +func sortItems(n int, m int, group []int, beforeItems [][]int) []int { + groupToItems := make(map[int][]int) + newGroup := m + for i := 0; i < n; i++ { + if group[i] == -1 { + group[i] = newGroup + newGroup++ + } + groupToItems[group[i]] = append(groupToItems[group[i]], i) + } + + intraPred := make(map[int]map[int]struct{}) + intraSucc := make(map[int]map[int]struct{}) + interPred := make(map[int]map[int]struct{}) + interSucc := make(map[int]map[int]struct{}) + + for i := 0; i < n; i++ { + for _, before := range beforeItems[i] { + if group[i] == group[before] { + if intraPred[i] == nil { intraPred[i] = make(map[int]struct{}) } + intraPred[i][before] = struct{}{} + if intraSucc[before] == nil { intraSucc[before] = make(map[int]struct{}) } + intraSucc[before][i] = struct{}{} + } else { + if interPred[group[i]] == nil { interPred[group[i]] = make(map[int]struct{}) } + interPred[group[i]][group[before]] = struct{}{} + if interSucc[group[before]] == nil { interSucc[group[before]] = make(map[int]struct{}) } + interSucc[group[before]][group[i]] = struct{}{} + } + } + } + + topologicalSort := func(nodes []int, pred, succ map[int]map[int]struct{}) []int { + order := []int{} + queue := []int{} + for _, node := range nodes { + if len(pred[node]) == 0 { + queue = append(queue, node) + } + } + for len(queue) > 0 { + node := queue[0] + queue = queue[1:] + order = append(order, node) + for s := range succ[node] { + delete(pred[s], node) + if len(pred[s]) == 0 { + queue = append(queue, s) + } + } + } + if len(order) != len(nodes) { + return []int{} + } + return order + } + + groupNodes := make([]int, 0, len(groupToItems)) + for k := range groupToItems { + groupNodes = append(groupNodes, k) + } + groupsOrder := topologicalSort(groupNodes, interPred, interSucc) + if len(groupsOrder) == 0 { + return []int{} + } + + result := []int{} + for _, grp := range groupsOrder { + order := topologicalSort(groupToItems[grp], intraPred, intraSucc) + if len(order) == 0 { + return []int{} + } + result = append(result, order...) + } + return result +} diff --git a/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.java b/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.java new file mode 100644 index 00000000..31752c98 --- /dev/null +++ b/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.java @@ -0,0 +1,33 @@ +import java.util.*; + +class Solution { + public int[] sortItems(int n, int m, int[] group, int[][] beforeItems) { + int nextGroup = m; + for (int i = 0; i < n; i++) if (group[i] == -1) group[i] = nextGroup++; + List> itemGraph = new ArrayList<>(); + List> groupGraph = new ArrayList<>(); + int[] itemIn = new int[n], groupIn = new int[nextGroup]; + for (int i = 0; i < n; i++) itemGraph.add(new ArrayList<>()); + for (int i = 0; i < nextGroup; i++) groupGraph.add(new ArrayList<>()); + for (int item = 0; item < n; item++) for (int before : beforeItems[item]) { + itemGraph.get(before).add(item); itemIn[item]++; + if (group[before] != group[item]) { groupGraph.get(group[before]).add(group[item]); groupIn[group[item]]++; } + } + List itemOrder = topo(itemGraph, itemIn); + List groupOrder = topo(groupGraph, groupIn); + if (itemOrder.size() != n || groupOrder.size() != nextGroup) return new int[0]; + List> grouped = new ArrayList<>(); + for (int i = 0; i < nextGroup; i++) grouped.add(new ArrayList<>()); + for (int item : itemOrder) grouped.get(group[item]).add(item); + int[] answer = new int[n]; int k = 0; + for (int g : groupOrder) for (int item : grouped.get(g)) answer[k++] = item; + return answer; + } + private List topo(List> graph, int[] indegree) { + ArrayDeque queue = new ArrayDeque<>(); + for (int i = 0; i < indegree.length; i++) if (indegree[i] == 0) queue.add(i); + List order = new ArrayList<>(); + while (!queue.isEmpty()) { int node = queue.remove(); order.add(node); for (int next : graph.get(node)) if (--indegree[next] == 0) queue.add(next); } + return order; + } +} diff --git a/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.kt b/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.kt new file mode 100644 index 00000000..a08eec69 --- /dev/null +++ b/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.kt @@ -0,0 +1,52 @@ +class Solution { + fun sortItems(n: Int, m: Int, group: IntArray, beforeItems: Array): IntArray { + val groupToItems = mutableMapOf>() + var newGroup = m + for (i in 0 until n) { + if (group[i] == -1) group[i] = newGroup++ + groupToItems.getOrPut(group[i]) { mutableSetOf() }.add(i) + } + val intraPred = mutableMapOf>() + val intraSucc = mutableMapOf>() + val interPred = mutableMapOf>() + val interSucc = mutableMapOf>() + + for (i in 0 until n) { + for (before in beforeItems[i]) { + if (group[i] == group[before]) { + intraPred.getOrPut(i) { mutableSetOf() }.add(before) + intraSucc.getOrPut(before) { mutableSetOf() }.add(i) + } else { + interPred.getOrPut(group[i]) { mutableSetOf() }.add(group[before]) + interSucc.getOrPut(group[before]) { mutableSetOf() }.add(group[i]) + } + } + } + + fun topoSort(nodes: Set, pred: MutableMap>, succ: MutableMap>): List { + val order = mutableListOf() + val queue = ArrayDeque() + for (node in nodes) if (pred[node].isNullOrEmpty()) queue.addLast(node) + while (queue.isNotEmpty()) { + val node = queue.removeFirst() + order.add(node) + for (s in succ[node].orEmpty()) { + pred[s]?.remove(node) + if (pred[s].isNullOrEmpty()) queue.addLast(s) + } + } + return if (order.size == nodes.size) order else emptyList() + } + + val groupsOrder = topoSort(groupToItems.keys, interPred, interSucc) + if (groupsOrder.isEmpty()) return intArrayOf() + + val result = mutableListOf() + for (grp in groupsOrder) { + val order = topoSort(groupToItems[grp]!!, intraPred, intraSucc) + if (order.isEmpty()) return intArrayOf() + result.addAll(order) + } + return result.toIntArray() + } +} diff --git a/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.py b/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.py new file mode 100644 index 00000000..61a8d7d4 --- /dev/null +++ b/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.py @@ -0,0 +1,55 @@ +from collections import defaultdict, deque + + +class Solution: + def sortItems( + self, n: int, m: int, group: List[int], beforeItems: List[List[int]] + ) -> List[int]: + + def topologicalSort(nodes, pred, succ): + order, no_pred = [], deque(node for node in nodes if not pred[node]) + while no_pred: + node = no_pred.popleft() + order.append(node) + for s in succ[node]: + pred[s].discard(node) + if not pred[s]: + no_pred.append(s) + return order if len(order) == len(nodes) else [] + + group_to_items, new_group = defaultdict(set), m + for item in range(n): + if group[item] == -1: + group[item] = new_group + new_group += 1 + group_to_items[group[item]].add(item) + + intra_pred, intra_succ, inter_pred, inter_succ = ( + defaultdict(set), + defaultdict(set), + defaultdict(set), + defaultdict(set), + ) + for item in range(n): + for before in beforeItems[item]: + if group[item] == group[before]: + intra_pred[item].add(before) + intra_succ[before].add(item) + else: + inter_pred[group[item]].add(group[before]) + inter_succ[group[before]].add(group[item]) + + groups_order = topologicalSort( + list(group_to_items.keys()), inter_pred, inter_succ + ) + if not groups_order: + return [] + + items_order = [] + for grp in groups_order: + order = topologicalSort(group_to_items[grp], intra_pred, intra_succ) + if not order: + return [] + items_order.extend(order) + + return items_order diff --git a/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.py2 b/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.py2 new file mode 100644 index 00000000..efa78a79 --- /dev/null +++ b/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.py2 @@ -0,0 +1,47 @@ +class Solution(object): + def sortItems(self, n, m, group, beforeItems): + """ + :type n: int + :type m: int + :type group: List[int] + :type beforeItems: List[List[int]] + :rtype: List[int] + """ + from collections import defaultdict, deque + + def topologicalSort(nodes, pred, succ): + order, no_pred = [], deque(node for node in nodes if not pred[node]) + while no_pred: + node = no_pred.popleft() + order.append(node) + for s in succ[node]: + pred[s].discard(node) + if not pred[s]: + no_pred.append(s) + return order if len(order) == len(nodes) else [] + + group_to_items, new_group = defaultdict(set), m + for item in range(n): + if group[item] == -1: group[item] = new_group; new_group += 1 + group_to_items[group[item]].add(item) + + intra_pred, intra_succ, inter_pred, inter_succ = defaultdict(set), defaultdict(set), defaultdict(set), defaultdict(set) + for item in range(n): + for before in beforeItems[item]: + if group[item] == group[before]: + intra_pred[item].add(before) + intra_succ[before].add(item) + else: + inter_pred[group[item]].add(group[before]) + inter_succ[group[before]].add(group[item]) + + groups_order = topologicalSort(list(group_to_items.keys()), inter_pred, inter_succ) + if not groups_order: return [] + + items_order = [] + for grp in groups_order: + order = topologicalSort(list(group_to_items[grp]), intra_pred, intra_succ) + if not order: return [] + items_order.extend(order) + + return items_order diff --git a/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.rb b/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.rb new file mode 100644 index 00000000..12deef8f --- /dev/null +++ b/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.rb @@ -0,0 +1,55 @@ +def sort_items(n, m, group, before_items) + group_to_items = Hash.new { |h, k| h[k] = [] } + new_group = m + (0...n).each do |item| + if group[item] == -1 + group[item] = new_group + new_group += 1 + end + group_to_items[group[item]] << item + end + + intra_pred = Hash.new { |h, k| h[k] = Set.new } + intra_succ = Hash.new { |h, k| h[k] = Set.new } + inter_pred = Hash.new { |h, k| h[k] = Set.new } + inter_succ = Hash.new { |h, k| h[k] = Set.new } + + (0...n).each do |item| + before_items[item].each do |before| + if group[item] == group[before] + intra_pred[item].add(before) + intra_succ[before].add(item) + else + inter_pred[group[item]].add(group[before]) + inter_succ[group[before]].add(group[item]) + end + end + end + + def topological_sort(nodes, pred, succ) + order = [] + no_pred = nodes.select { |node| pred[node].empty? } + while !no_pred.empty? + node = no_pred.shift + order << node + succ[node].each do |s| + pred[s].delete(node) + if pred[s].empty? + no_pred << s + end + end + end + order.length == nodes.length ? order : [] + end + + groups_order = topological_sort(group_to_items.keys, inter_pred, inter_succ) + return [] if groups_order.empty? + + items_order = [] + groups_order.each do |grp| + order = topological_sort(group_to_items[grp], intra_pred, intra_succ) + return [] if order.empty? + items_order.concat(order) + end + items_order +end diff --git a/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.rs b/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.rs new file mode 100644 index 00000000..5f95475d --- /dev/null +++ b/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.rs @@ -0,0 +1,75 @@ +impl Solution { + pub fn sort_items(n: i32, m: i32, mut group: Vec, before_items: Vec>) -> Vec { + use std::collections::{HashMap, HashSet, VecDeque}; + let n = n as usize; + let m = m as usize; + let mut group_to_items: HashMap> = HashMap::new(); + let mut new_group = m as i32; + for i in 0..n { + if group[i] == -1 { + group[i] = new_group; + new_group += 1; + } + group_to_items.entry(group[i]).or_default().insert(i as i32); + } + + let mut intra_pred: HashMap> = HashMap::new(); + let mut intra_succ: HashMap> = HashMap::new(); + let mut inter_pred: HashMap> = HashMap::new(); + let mut inter_succ: HashMap> = HashMap::new(); + + for i in 0..n { + for &before in &before_items[i] { + if group[i] == group[before as usize] { + intra_pred.entry(i as i32).or_default().insert(before); + intra_succ.entry(before).or_default().insert(i as i32); + } else { + inter_pred.entry(group[i]).or_default().insert(group[before as usize]); + inter_succ.entry(group[before as usize]).or_default().insert(group[i]); + } + } + } + + fn topo_sort( + nodes: Vec, + pred: &mut HashMap>, + succ: &HashMap>, + ) -> Vec { + let node_set: HashSet = nodes.iter().cloned().collect(); + let mut order = Vec::new(); + let mut queue = VecDeque::new(); + for &node in &nodes { + if pred.get(&node).map_or(true, |s| s.is_empty()) { + queue.push_back(node); + } + } + while let Some(node) = queue.pop_front() { + order.push(node); + if let Some(neighbors) = succ.get(&node) { + for &s in neighbors { + if let Some(set) = pred.get_mut(&s) { + set.remove(&node); + if set.is_empty() { + queue.push_back(s); + } + } + } + } + } + if order.len() == nodes.len() { order } else { Vec::new() } + } + + let group_nodes: Vec = group_to_items.keys().cloned().collect(); + let groups_order = topo_sort(group_nodes, &mut inter_pred, &inter_succ); + if groups_order.is_empty() { return Vec::new(); } + + let mut result = Vec::new(); + for grp in groups_order { + let items: Vec = group_to_items[&grp].iter().cloned().collect(); + let order = topo_sort(items, &mut intra_pred, &intra_succ); + if order.is_empty() { return Vec::new(); } + result.extend(order); + } + result + } +} diff --git a/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.swift b/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.swift new file mode 100644 index 00000000..4eecf777 --- /dev/null +++ b/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.swift @@ -0,0 +1,59 @@ +class Solution { + func sortItems(_ n: Int, _ m: Int, _ group: [Int], _ beforeItems: [[Int]]) -> [Int] { + var group = group + var groupToItems = [Int: Set]() + var newGroup = m + for i in 0..]() + var intraSucc = [Int: Set]() + var interPred = [Int: Set]() + var interSucc = [Int: Set]() + + for i in 0.., _ pred: inout [Int: Set], _ succ: [Int: Set]) -> [Int] { + var order = [Int]() + var queue = [Int]() + for node in nodes { + if pred[node]?.isEmpty ?? true { queue.append(node) } + } + while !queue.isEmpty { + let node = queue.removeFirst() + order.append(node) + for s in succ[node] ?? [] { + pred[s]?.remove(node) + if pred[s]?.isEmpty ?? true { queue.append(s) } + } + } + return order.count == nodes.count ? order : [] + } + + let groupsOrder = topoSort(Set(groupToItems.keys), &interPred, interSucc) + if groupsOrder.isEmpty { return [] } + + var result = [Int]() + for grp in groupsOrder { + let order = topoSort(groupToItems[grp]!, &intraPred, intraSucc) + if order.isEmpty { return [] } + result.append(contentsOf: order) + } + return result + } +} diff --git a/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.ts b/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.ts new file mode 100644 index 00000000..02f8de74 --- /dev/null +++ b/tests/1001-1500/1203. sort-items-by-groups-respecting-dependencies/sol.ts @@ -0,0 +1,72 @@ +function sortItems( + n: number, + m: number, + group: number[], + beforeItems: number[][], +): number[] { + const groupToItems: Map> = new Map(); + let newGroup = m; + for (let i = 0; i < n; i++) { + if (group[i] === -1) group[i] = newGroup++; + if (!groupToItems.has(group[i])) groupToItems.set(group[i], new Set()); + groupToItems.get(group[i])!.add(i); + } + + const intraPred: Map> = new Map(); + const intraSucc: Map> = new Map(); + const interPred: Map> = new Map(); + const interSucc: Map> = new Map(); + + for (let i = 0; i < n; i++) { + for (const before of beforeItems[i]) { + if (group[i] === group[before]) { + if (!intraPred.has(i)) intraPred.set(i, new Set()); + intraPred.get(i)!.add(before); + if (!intraSucc.has(before)) intraSucc.set(before, new Set()); + intraSucc.get(before)!.add(i); + } else { + if (!interPred.has(group[i])) interPred.set(group[i], new Set()); + interPred.get(group[i])!.add(group[before]); + if (!interSucc.has(group[before])) + interSucc.set(group[before], new Set()); + interSucc.get(group[before])!.add(group[i]); + } + } + } + + function topoSort( + nodes: Set, + pred: Map>, + succ: Map>, + ): number[] { + const order: number[] = []; + const queue: number[] = []; + for (const node of nodes) { + if (!pred.has(node) || pred.get(node)!.size === 0) queue.push(node); + } + while (queue.length) { + const node = queue.shift()!; + order.push(node); + for (const s of succ.get(node) ?? []) { + pred.get(s)?.delete(node); + if (!pred.has(s) || pred.get(s)!.size === 0) queue.push(s); + } + } + return order.length === nodes.size ? order : []; + } + + const groupsOrder = topoSort( + new Set(groupToItems.keys()), + interPred, + interSucc, + ); + if (groupsOrder.length === 0) return []; + + const result: number[] = []; + for (const grp of groupsOrder) { + const order = topoSort(groupToItems.get(grp)!, intraPred, intraSucc); + if (order.length === 0) return []; + result.push(...order); + } + return result; +} diff --git a/tests/1001-1500/1207. unique-number-of-occurrences/manifest.yaml b/tests/1001-1500/1207. unique-number-of-occurrences/manifest.yaml new file mode 100644 index 00000000..2324e357 --- /dev/null +++ b/tests/1001-1500/1207. unique-number-of-occurrences/manifest.yaml @@ -0,0 +1,281 @@ +entry: + id: 1207 + title: "unique-number-of-occurrences" + params: + arr: + type: array + items: + type: int + call: + cpp: "Solution().uniqueOccurrences({arr})" + rust: "Solution::unique_occurrences({arr})" + python3: "Solution().uniqueOccurrences({arr})" + python2: "Solution().uniqueOccurrences({arr})" + ruby: "unique_occurrences({arr})" + java: "new Solution().uniqueOccurrences({arr})" + csharp: "new Solution().UniqueOccurrences({arr})" + kotlin: "Solution().uniqueOccurrences({arr})" + go: "uniqueOccurrences({arr})" + dart: "Solution().uniqueOccurrences({arr})" + swift: "Solution().uniqueOccurrences({arr})" + typescript: "uniqueOccurrences({arr})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().uniqueOccurrences(arr, {result})" + checker: | + class Checker: + def uniqueOccurrences(self, arr, result): + if not isinstance(result, bool): + return False + counts = {} + for value in arr: + counts[value] = counts.get(value, 0) + 1 + frequencies = set() + for count in counts.values(): + if count in frequencies: + return result is False + frequencies.add(count) + return result is True + +seed: 1207 + +tests: + - name: "example_one" + in: + arr: [1, 2, 2, 1, 1, 3] + out: true + - name: "example_two" + in: + arr: [1, 2] + out: false + - name: "example_three" + in: + arr: [-3, 0, 1, -3, 1, 1, 1, -3, 10, 0] + out: true + - name: "single_value" + in: + arr: [7] + out: true + - name: "two_equal_values" + in: + arr: [4, 4] + out: true + - name: "two_distinct_values" + in: + arr: [4, 5] + out: false + - name: "three_distinct_values" + in: + arr: [1, 2, 3] + out: false + - name: "three_equal_values" + in: + arr: [1, 1, 1] + out: true + - name: "frequencies_one_and_two" + in: + arr: [1, 2, 2] + out: true + - name: "frequencies_one_two_three" + in: + arr: [1, 2, 2, 3, 3, 3] + out: true + - name: "three_equal_frequencies" + in: + arr: [1, 1, 2, 2, 3, 3] + out: false + - name: "negative_values_unique_counts" + in: + arr: [-1, -1, -1, -2, -2, -3] + out: true + - name: "zero_and_negative_collision" + in: + arr: [0, 0, -1, -2, -2] + out: false + - name: "mixed_value_extremes" + in: + arr: [-1000, -1000, 1000, 0, 0, 0] + out: true + - name: "all_minimum_values" + in: + arr: [-1000, -1000, -1000, -1000] + out: true + - name: "all_maximum_values" + in: + arr: [1000, 1000, 1000, 1000, 1000] + out: true + - name: "four_unique_frequencies" + in: + arr: [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] + out: true + - name: "four_equal_frequencies" + in: + arr: [1, 1, 2, 2, 3, 3, 4, 4] + out: false + - name: "late_frequency_collision" + in: + arr: [1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4] + out: false + - name: "negative_frequency_pattern" + in: + arr: [-1, -2, -2, -3, -3, -3, -4, -4, -4, -4] + out: true + - name: "zero_frequency_pattern" + in: + arr: [0, 0, 1, 1, 1, 2, 2, 2, 2] + out: true + - name: "alternating_equal_groups" + in: + arr: [5, 6, 5, 6, 5, 6] + out: false + - name: "many_singletons" + in: + arr: [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5] + out: false + - name: "counts_four_three_two_one" + in: + arr: [1, 1, 1, 1, 2, 2, 2, 3, 3, 4] + out: true + - name: "six_distinct_counts" + in: + arr: [0, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5] + out: true + - name: "large_equal_groups" + in: + arr: [1, 1, 1, 1, 1, 2, 2, 2, 2, 2] + out: false + - name: "range_boundaries_with_singleton_collision" + in: + arr: [-1000, -1000, -999, 999, 1000, 1000, 1000] + out: false + - name: "balanced_three_groups" + in: + arr: [-7, -7, -7, 8, 8, 8, 9, 9, 9] + out: false + - name: "distinct_counts_to_five" + in: + arr: [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5] + out: true + - name: "nonadjacent_collision" + in: + arr: [10, 20, 10, 30, 20, 40, 10, 30, 40, 20, 30, 40] + out: false + - name: "sparse_unique_counts" + in: + arr: + [ + -1000, + -1000, + -1000, + -1000, + -1000, + 1000, + 1000, + 1000, + 1000, + 0, + 0, + 0, + -1, + -1, + 1, + ] + out: true + - name: "collision_after_unique_prefix" + in: + arr: [9, 8, 8, 7, 7, 7, 6, 6, 6, 6, 5, 5, 5, 5] + out: false + - name: "interleaved_frequency_collision" + in: + arr: [1, 2, 3, 1, 4, 2, 5, 1, 3, 4, 1, 2, 5, 1, 3, 4, 1, 2, 3, 4, 2] + out: false + - name: "interleaved_unique_counts" + in: + arr: [1, 2, 3, 4, 5, 2, 3, 4, 5, 3, 4, 5, 4, 5, 5] + out: true + - name: "generated_stress_500_full_range" + seed: 120701 + in: + arr: + gen: "array" + len: 500 + distinct: false + sorted: false + elemType: "int" + of: + gen: "int" + min: -1000 + max: 1000 + - name: "generated_stress_750_full_range" + seed: 120702 + in: + arr: + gen: "array" + len: 750 + distinct: false + sorted: false + elemType: "int" + of: + gen: "int" + min: -1000 + max: 1000 + - name: "generated_stress_900_narrow_range" + seed: 120703 + in: + arr: + gen: "array" + len: 900 + distinct: false + sorted: false + elemType: "int" + of: + gen: "int" + min: -3 + max: 3 + - name: "generated_stress_999_full_range" + seed: 120704 + in: + arr: + gen: "array" + len: 999 + distinct: false + sorted: false + elemType: "int" + of: + gen: "int" + min: -1000 + max: 1000 + - name: "generated_stress_1000_dense_range" + seed: 120705 + in: + arr: + gen: "array" + len: 1000 + distinct: false + sorted: false + elemType: "int" + of: + gen: "int" + min: -50 + max: 50 + - name: "generated_stress_1000_boundary_range" + seed: 120706 + in: + arr: + gen: "array" + len: 1000 + distinct: false + sorted: false + elemType: "int" + of: + gen: "int" + min: -1000 + max: 1000 diff --git a/tests/1001-1500/1207. unique-number-of-occurrences/sol.cpp b/tests/1001-1500/1207. unique-number-of-occurrences/sol.cpp new file mode 100644 index 00000000..fbcbad09 --- /dev/null +++ b/tests/1001-1500/1207. unique-number-of-occurrences/sol.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + bool uniqueOccurrences(vector& arr) { + unordered_map d; + for (int i : arr) { + if (d.find(i) != d.end()) { + d[i]++; + } else { + d[i] = 1; + } + } + unordered_set s; + for (auto& pair : d) { + int value = pair.second; + if (s.find(value) != s.end()) { + return false; + } + s.insert(value); + } + return true; + } +}; diff --git a/tests/1001-1500/1207. unique-number-of-occurrences/sol.cs b/tests/1001-1500/1207. unique-number-of-occurrences/sol.cs new file mode 100644 index 00000000..f5b95c44 --- /dev/null +++ b/tests/1001-1500/1207. unique-number-of-occurrences/sol.cs @@ -0,0 +1,20 @@ +public class Solution { + public bool UniqueOccurrences(int[] arr) { + var d = new Dictionary(); + foreach (int i in arr) { + if (d.ContainsKey(i)) { + d[i]++; + } else { + d[i] = 1; + } + } + var s = new HashSet(); + foreach (int value in d.Values) { + if (s.Contains(value)) { + return false; + } + s.Add(value); + } + return true; + } +} diff --git a/tests/1001-1500/1207. unique-number-of-occurrences/sol.dart b/tests/1001-1500/1207. unique-number-of-occurrences/sol.dart new file mode 100644 index 00000000..a428031e --- /dev/null +++ b/tests/1001-1500/1207. unique-number-of-occurrences/sol.dart @@ -0,0 +1,20 @@ +class Solution { + bool uniqueOccurrences(List arr) { + var d = {}; + for (var i in arr) { + if (d.containsKey(i)) { + d[i] = d[i]! + 1; + } else { + d[i] = 1; + } + } + var s = {}; + for (var value in d.values) { + if (s.contains(value)) { + return false; + } + s.add(value); + } + return true; + } +} diff --git a/tests/1001-1500/1207. unique-number-of-occurrences/sol.go b/tests/1001-1500/1207. unique-number-of-occurrences/sol.go new file mode 100644 index 00000000..9afad829 --- /dev/null +++ b/tests/1001-1500/1207. unique-number-of-occurrences/sol.go @@ -0,0 +1,18 @@ +func uniqueOccurrences(arr []int) bool { + d := make(map[int]int) + for _, i := range arr { + if _, exists := d[i]; exists { + d[i]++ + } else { + d[i] = 1 + } + } + s := make(map[int]bool) + for _, value := range d { + if s[value] { + return false + } + s[value] = true + } + return true +} diff --git a/tests/1001-1500/1207. unique-number-of-occurrences/sol.java b/tests/1001-1500/1207. unique-number-of-occurrences/sol.java new file mode 100644 index 00000000..98e49f96 --- /dev/null +++ b/tests/1001-1500/1207. unique-number-of-occurrences/sol.java @@ -0,0 +1,20 @@ +class Solution { + public boolean uniqueOccurrences(int[] arr) { + java.util.Map d = new java.util.HashMap<>(); + for (int i : arr) { + if (d.containsKey(i)) { + d.put(i, d.get(i) + 1); + } else { + d.put(i, 1); + } + } + java.util.Set s = new java.util.HashSet<>(); + for (int value : d.values()) { + if (s.contains(value)) { + return false; + } + s.add(value); + } + return true; + } +} diff --git a/tests/1001-1500/1207. unique-number-of-occurrences/sol.kt b/tests/1001-1500/1207. unique-number-of-occurrences/sol.kt new file mode 100644 index 00000000..49d8ba17 --- /dev/null +++ b/tests/1001-1500/1207. unique-number-of-occurrences/sol.kt @@ -0,0 +1,20 @@ +class Solution { + fun uniqueOccurrences(arr: IntArray): Boolean { + val d = mutableMapOf() + for (i in arr) { + if (d.containsKey(i)) { + d[i] = d[i]!! + 1 + } else { + d[i] = 1 + } + } + val s = mutableSetOf() + for (value in d.values) { + if (s.contains(value)) { + return false + } + s.add(value) + } + return true + } +} diff --git a/tests/1001-1500/1207. unique-number-of-occurrences/sol.py b/tests/1001-1500/1207. unique-number-of-occurrences/sol.py new file mode 100644 index 00000000..bd067e55 --- /dev/null +++ b/tests/1001-1500/1207. unique-number-of-occurrences/sol.py @@ -0,0 +1,15 @@ +class Solution: + def uniqueOccurrences(self, arr: List[int]) -> bool: + d = {} + for i in arr: + if i in d: + d[i] += 1 + else: + d[i] = 1 + s = set() + for value in d.values(): + if value in s: + return False + s.add(value) + + return True diff --git a/tests/1001-1500/1207. unique-number-of-occurrences/sol.py2 b/tests/1001-1500/1207. unique-number-of-occurrences/sol.py2 new file mode 100644 index 00000000..18340bbd --- /dev/null +++ b/tests/1001-1500/1207. unique-number-of-occurrences/sol.py2 @@ -0,0 +1,18 @@ +class Solution(object): + def uniqueOccurrences(self, arr): + """ + :type arr: List[int] + :rtype: bool + """ + d = {} + for i in arr: + if i in d: + d[i] += 1 + else: + d[i] = 1 + s = set() + for value in d.values(): + if value in s: + return False + s.add(value) + return True diff --git a/tests/1001-1500/1207. unique-number-of-occurrences/sol.rb b/tests/1001-1500/1207. unique-number-of-occurrences/sol.rb new file mode 100644 index 00000000..a20a9462 --- /dev/null +++ b/tests/1001-1500/1207. unique-number-of-occurrences/sol.rb @@ -0,0 +1,20 @@ +# @param {Integer[]} arr +# @return {Boolean} +def unique_occurrences(arr) + d = {} + arr.each do |i| + if d.key?(i) + d[i] += 1 + else + d[i] = 1 + end + end + s = Set.new + d.values.each do |value| + if s.include?(value) + return false + end + s.add(value) + end + return true +end diff --git a/tests/1001-1500/1207. unique-number-of-occurrences/sol.rs b/tests/1001-1500/1207. unique-number-of-occurrences/sol.rs new file mode 100644 index 00000000..184f521f --- /dev/null +++ b/tests/1001-1500/1207. unique-number-of-occurrences/sol.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn unique_occurrences(arr: Vec) -> bool { + let mut d = std::collections::HashMap::new(); + for &i in &arr { + *d.entry(i).or_insert(0) += 1; + } + let mut s = std::collections::HashSet::new(); + for &value in d.values() { + if s.contains(&value) { + return false; + } + s.insert(value); + } + true + } +} diff --git a/tests/1001-1500/1207. unique-number-of-occurrences/sol.swift b/tests/1001-1500/1207. unique-number-of-occurrences/sol.swift new file mode 100644 index 00000000..54e28886 --- /dev/null +++ b/tests/1001-1500/1207. unique-number-of-occurrences/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func uniqueOccurrences(_ arr: [Int]) -> Bool { + var d = [Int: Int]() + for i in arr { + if let count = d[i] { + d[i] = count + 1 + } else { + d[i] = 1 + } + } + var s = Set() + for value in d.values { + if s.contains(value) { + return false + } + s.insert(value) + } + return true + } +} diff --git a/tests/1001-1500/1207. unique-number-of-occurrences/sol.ts b/tests/1001-1500/1207. unique-number-of-occurrences/sol.ts new file mode 100644 index 00000000..c8306dcc --- /dev/null +++ b/tests/1001-1500/1207. unique-number-of-occurrences/sol.ts @@ -0,0 +1,18 @@ +function uniqueOccurrences(arr: number[]): boolean { + const d: Map = new Map(); + for (const i of arr) { + if (d.has(i)) { + d.set(i, d.get(i)! + 1); + } else { + d.set(i, 1); + } + } + const s: Set = new Set(); + for (const value of d.values()) { + if (s.has(value)) { + return false; + } + s.add(value); + } + return true; +} diff --git a/tests/1001-1500/1208. get-equal-substrings-within-budget/manifest.yaml b/tests/1001-1500/1208. get-equal-substrings-within-budget/manifest.yaml new file mode 100644 index 00000000..9dcc2d6f --- /dev/null +++ b/tests/1001-1500/1208. get-equal-substrings-within-budget/manifest.yaml @@ -0,0 +1,327 @@ +entry: + id: 1208 + title: "get-equal-substrings-within-budget" + params: + s: + type: string + t: + type: string + maxCost: + type: int + call: + cpp: "Solution().equalSubstring({s}, {t}, {maxCost})" + rust: "Solution::equal_substring({s}, {t}, {maxCost})" + python3: "Solution().equalSubstring({s}, {t}, {maxCost})" + python2: "Solution().equalSubstring({s}, {t}, {maxCost})" + ruby: "equal_substring({s}, {t}, {maxCost})" + java: "new Solution().equalSubstring({s}, {t}, {maxCost})" + csharp: "new Solution().EqualSubstring({s}, {t}, {maxCost})" + kotlin: "Solution().equalSubstring({s}, {t}, {maxCost})" + go: "equalSubstring({s}, {t}, {maxCost})" + dart: "Solution().equalSubstring({s}, {t}, {maxCost})" + swift: "Solution().equalSubstring({s}, {t}, {maxCost})" + typescript: "equalSubstring({s}, {t}, {maxCost})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().equalSubstring(s, t, maxCost, {result})" + checker: | + class Checker: + def equalSubstring(self, s, t, maxCost, result): + left = 0 + cost = 0 + best = 0 + for right in range(len(s)): + cost += abs(ord(s[right]) - ord(t[right])) + while cost > maxCost: + cost -= abs(ord(s[left]) - ord(t[left])) + left += 1 + best = max(best, right - left + 1) + return result == best + +seed: 1208 + +tests: + - name: "example-one" + in: + s: "abcd" + t: "bcdf" + maxCost: 3 + out: 3 + - name: "example-two" + in: + s: "abcd" + t: "cdef" + maxCost: 3 + out: 1 + - name: "example-three" + in: + s: "abcd" + t: "acde" + maxCost: 0 + out: 1 + - name: "single-equal" + in: + s: "a" + t: "a" + maxCost: 0 + out: 1 + - name: "single-change-free" + in: + s: "a" + t: "z" + maxCost: 25 + out: 1 + - name: "single-change-too-costly" + in: + s: "a" + t: "z" + maxCost: 24 + out: 0 + - name: "all-equal-zero-budget" + in: + s: "aaaaaa" + t: "aaaaaa" + maxCost: 0 + out: 6 + - name: "all-different-zero-budget" + in: + s: "abcdef" + t: "bcdefg" + maxCost: 0 + out: 0 + - name: "full-budget" + in: + s: "abcde" + t: "zyxwv" + maxCost: 200 + out: 5 + - name: "just-enough" + in: + s: "abcd" + t: "bcde" + maxCost: 4 + out: 4 + - name: "one-over-budget" + in: + s: "abcd" + t: "bcde" + maxCost: 3 + out: 3 + - name: "cheap-prefix-before-expensive-change" + in: + s: "azbzcz" + t: "azczzz" + maxCost: 1 + out: 4 + - name: "expensive-middle-splits-run" + in: + s: "aaaaaa" + t: "aazaaa" + maxCost: 5 + out: 3 + - name: "alternating-max-cost" + in: + s: "azazaz" + t: "zazaza" + maxCost: 50 + out: 2 + - name: "zero-budget-match-runs" + in: + s: "abccdeff" + t: "abzzdeff" + maxCost: 0 + out: 4 + - name: "one-cheap-change" + in: + s: "abcabc" + t: "abdabc" + maxCost: 1 + out: 6 + - name: "cost-at-window-start" + in: + s: "zaaa" + t: "aaaa" + maxCost: 1 + out: 3 + - name: "cost-at-window-end" + in: + s: "aaaz" + t: "aaaa" + maxCost: 1 + out: 3 + - name: "two-separated-costly-runs" + in: + s: "azzzza" + t: "aaaaaa" + maxCost: 50 + out: 3 + - name: "repeated-small-cost" + in: + s: "bbbbbbbb" + t: "cccccccc" + maxCost: 3 + out: 3 + - name: "repeated-large-cost" + in: + s: "aaaaaaaa" + t: "zzzzzzzz" + maxCost: 75 + out: 3 + - name: "uniform-unit-cost" + in: + s: "azbycxdw" + t: "bycxdwex" + maxCost: 10 + out: 8 + - name: "symmetric-cost-valley" + in: + s: "abcdefghi" + t: "jihgfedcb" + maxCost: 20 + out: 6 + - name: "symmetric-cost-valley-larger-budget" + in: + s: "qrstuvwxy" + t: "yxwvutsrq" + maxCost: 30 + out: 7 + - name: "multiple-shrinks-zero-budget" + in: + s: "ba" + t: "az" + maxCost: 0 + out: 0 + - name: "long-uniform-shift" + in: + s: "aaaaaaaaaaaaaaaaaaaa" + t: "bbbbbbbbbbbbbbbbbbbb" + maxCost: 10 + out: 10 + - name: "long-boundary-budget" + in: + s: "abcdefghijklmnopqrst" + t: "bcdefghijklmnopqrstu" + maxCost: 10 + out: 10 + - name: "multiple-shrinks-after-partial-budget" + in: + s: "bba" + t: "aaz" + maxCost: 1 + out: 1 + - name: "long-alternating-unit-cost" + in: + s: "abababababababababab" + t: "babababababababababa" + maxCost: 9 + out: 9 + - name: "maximum-budget-long" + in: + s: "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" + t: "zyxwvutsrqponmlkjihgfedcbazyxwvutsrqponmlkjihgfedcba" + maxCost: 1000000 + out: 52 + - name: "single-peak-zero-budget" + in: + s: "aaaaabaaaa" + t: "aaaaaaaaaa" + maxCost: 0 + out: 5 + - name: "single-peak-included" + in: + s: "aaaaabaaaa" + t: "aaaaaaaaaa" + maxCost: 1 + out: 10 + - name: "alternating-small-costs" + in: + s: "abcdeabcde" + t: "bbcddbbcdd" + maxCost: 2 + out: 8 + - name: "long-repeated-expensive" + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + t: "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + maxCost: 100 + out: 4 + - name: "stress-all-equal-zero-budget" + seed: 120801 + in: + s: + gen: "str" + len: 100000 + alphabet: "a" + t: + gen: "str" + len: 100000 + alphabet: "a" + maxCost: 0 + - name: "stress-max-cost-zero-budget" + seed: 120802 + in: + s: + gen: "str" + len: 100000 + alphabet: "a" + t: + gen: "str" + len: 100000 + alphabet: "z" + maxCost: 0 + - name: "stress-max-cost-exact-budget" + seed: 120803 + in: + s: + gen: "str" + len: 100000 + alphabet: "a" + t: + gen: "str" + len: 100000 + alphabet: "z" + maxCost: 1000000 + - name: "stress-max-cost-one-below-budget" + seed: 120804 + in: + s: + gen: "str" + len: 100000 + alphabet: "a" + t: + gen: "str" + len: 100000 + alphabet: "z" + maxCost: 999999 + - name: "stress-unit-cost-full-length" + seed: 120805 + in: + s: + gen: "str" + len: 100000 + alphabet: "a" + t: + gen: "str" + len: 100000 + alphabet: "b" + maxCost: 100000 + - name: "stress-unit-cost-one-short" + seed: 120806 + in: + s: + gen: "str" + len: 100000 + alphabet: "a" + t: + gen: "str" + len: 100000 + alphabet: "b" + maxCost: 99999 diff --git a/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.cpp b/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.cpp new file mode 100644 index 00000000..3092c237 --- /dev/null +++ b/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int equalSubstring(string s, string t, int maxCost) { + int ans = 0, cost = 0, left = 0; + for (int right = 0; right < s.length(); right++) { + cost += abs(s[right] - t[right]); + while (cost > maxCost) { + cost -= abs(s[left] - t[left]); + left++; + } + int size = right - left + 1; + if (size > ans) { + ans = size; + } + } + return ans; + } +}; diff --git a/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.cs b/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.cs new file mode 100644 index 00000000..c457f7fd --- /dev/null +++ b/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.cs @@ -0,0 +1,17 @@ +public class Solution { + public int EqualSubstring(string s, string t, int maxCost) { + int ans = 0, cost = 0, left = 0; + for (int right = 0; right < s.Length; right++) { + cost += Math.Abs(s[right] - t[right]); + while (cost > maxCost) { + cost -= Math.Abs(s[left] - t[left]); + left++; + } + int size = right - left + 1; + if (size > ans) { + ans = size; + } + } + return ans; + } +} diff --git a/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.dart b/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.dart new file mode 100644 index 00000000..a03bbf7d --- /dev/null +++ b/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.dart @@ -0,0 +1,17 @@ +class Solution { + int equalSubstring(String s, String t, int maxCost) { + int ans = 0, cost = 0, left = 0; + for (int right = 0; right < s.length; right++) { + cost += (s.codeUnitAt(right) - t.codeUnitAt(right)).abs(); + while (cost > maxCost) { + cost -= (s.codeUnitAt(left) - t.codeUnitAt(left)).abs(); + left++; + } + int size = right - left + 1; + if (size > ans) { + ans = size; + } + } + return ans; + } +} diff --git a/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.go b/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.go new file mode 100644 index 00000000..477f1f42 --- /dev/null +++ b/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.go @@ -0,0 +1,22 @@ +func equalSubstring(s string, t string, maxCost int) int { + ans, cost, left := 0, 0, 0 + for right := 0; right < len(s); right++ { + cost += abs(int(s[right]) - int(t[right])) + for cost > maxCost { + cost -= abs(int(s[left]) - int(t[left])) + left++ + } + size := right - left + 1 + if size > ans { + ans = size + } + } + return ans +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} diff --git a/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.java b/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.java new file mode 100644 index 00000000..c3ad5c78 --- /dev/null +++ b/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.java @@ -0,0 +1,17 @@ +class Solution { + public int equalSubstring(String s, String t, int maxCost) { + int ans = 0, cost = 0, left = 0; + for (int right = 0; right < s.length(); right++) { + cost += Math.abs(s.charAt(right) - t.charAt(right)); + while (cost > maxCost) { + cost -= Math.abs(s.charAt(left) - t.charAt(left)); + left++; + } + int size = right - left + 1; + if (size > ans) { + ans = size; + } + } + return ans; + } +} diff --git a/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.kt b/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.kt new file mode 100644 index 00000000..24d02736 --- /dev/null +++ b/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.kt @@ -0,0 +1,19 @@ +class Solution { + fun equalSubstring(s: String, t: String, maxCost: Int): Int { + var ans = 0 + var cost = 0 + var left = 0 + for (right in s.indices) { + cost += Math.abs(s[right] - t[right]) + while (cost > maxCost) { + cost -= Math.abs(s[left] - t[left]) + left++ + } + val size = right - left + 1 + if (size > ans) { + ans = size + } + } + return ans + } +} diff --git a/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.py b/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.py new file mode 100644 index 00000000..414a7ece --- /dev/null +++ b/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.py @@ -0,0 +1,16 @@ +class Solution: + def equalSubstring(self, s: str, t: str, maxCost: int) -> int: + ans = cost = left = 0 + + for right in range(len(s)): + cost += abs(ord(s[right]) - ord(t[right])) + + while cost > maxCost: + cost -= abs(ord(s[left]) - ord(t[left])) + left += 1 + + size = right - left + 1 + if size > ans: + ans = size + + return ans diff --git a/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.py2 b/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.py2 new file mode 100644 index 00000000..040410ee --- /dev/null +++ b/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.py2 @@ -0,0 +1,18 @@ +class Solution(object): + def equalSubstring(self, s, t, maxCost): + """ + :type s: str + :type t: str + :type maxCost: int + :rtype: int + """ + ans = cost = left = 0 + for right in range(len(s)): + cost += abs(ord(s[right]) - ord(t[right])) + while cost > maxCost: + cost -= abs(ord(s[left]) - ord(t[left])) + left += 1 + size = right - left + 1 + if size > ans: + ans = size + return ans diff --git a/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.rb b/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.rb new file mode 100644 index 00000000..2156ae3e --- /dev/null +++ b/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.rb @@ -0,0 +1,17 @@ +# @param {String} s +# @param {String} t +# @param {Integer} max_cost +# @return {Integer} +def equal_substring(s, t, max_cost) + ans = cost = left = 0 + (0...s.length).each do |right| + cost += (s[right].ord - t[right].ord).abs + while cost > max_cost + cost -= (s[left].ord - t[left].ord).abs + left += 1 + end + size = right - left + 1 + ans = size if size > ans + end + ans +end diff --git a/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.rs b/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.rs new file mode 100644 index 00000000..49cffea1 --- /dev/null +++ b/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.rs @@ -0,0 +1,22 @@ +impl Solution { + pub fn equal_substring(s: String, t: String, max_cost: i32) -> i32 { + let s_bytes = s.as_bytes(); + let t_bytes = t.as_bytes(); + let mut ans = 0; + let mut cost = 0; + let mut left = 0; + + for right in 0..s.len() { + cost += (s_bytes[right] as i32 - t_bytes[right] as i32).abs(); + while cost > max_cost { + cost -= (s_bytes[left] as i32 - t_bytes[left] as i32).abs(); + left += 1; + } + let size = (right - left + 1) as i32; + if size > ans { + ans = size; + } + } + ans + } +} diff --git a/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.swift b/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.swift new file mode 100644 index 00000000..723faa6d --- /dev/null +++ b/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func equalSubstring(_ s: String, _ t: String, _ maxCost: Int) -> Int { + let sArr = Array(s) + let tArr = Array(t) + var ans = 0, cost = 0, left = 0 + + for right in 0.. maxCost { + cost -= abs(Int(sArr[left].asciiValue!) - Int(tArr[left].asciiValue!)) + left += 1 + } + let size = right - left + 1 + if size > ans { + ans = size + } + } + return ans + } +} diff --git a/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.ts b/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.ts new file mode 100644 index 00000000..2a3d7119 --- /dev/null +++ b/tests/1001-1500/1208. get-equal-substrings-within-budget/sol.ts @@ -0,0 +1,17 @@ +function equalSubstring(s: string, t: string, maxCost: number): number { + let ans = 0, + cost = 0, + left = 0; + for (let right = 0; right < s.length; right++) { + cost += Math.abs(s.charCodeAt(right) - t.charCodeAt(right)); + while (cost > maxCost) { + cost -= Math.abs(s.charCodeAt(left) - t.charCodeAt(left)); + left++; + } + const size = right - left + 1; + if (size > ans) { + ans = size; + } + } + return ans; +} diff --git a/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/manifest.yaml b/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/manifest.yaml new file mode 100644 index 00000000..45c860c2 --- /dev/null +++ b/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/manifest.yaml @@ -0,0 +1,283 @@ +entry: + id: 1209 + title: remove-all-adjacent-duplicates-in-string-ii + params: + s: + type: string + k: + type: int + call: + cpp: "Solution().removeDuplicates({s}, {k})" + rust: "Solution::remove_duplicates({s}, {k})" + python3: "Solution().removeDuplicates({s}, {k})" + python2: "Solution().removeDuplicates({s}, {k})" + ruby: "remove_duplicates({s}, {k})" + java: "new Solution().removeDuplicates({s}, {k})" + csharp: "new Solution().RemoveDuplicates({s}, {k})" + kotlin: "Solution().removeDuplicates({s}, {k})" + go: "removeDuplicates({s}, {k})" + dart: "Solution().removeDuplicates({s}, {k})" + swift: "Solution().removeDuplicates({s}, {k})" + typescript: "removeDuplicates({s}, {k})" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().removeDuplicates(s, k, {result})" + checker: | + class Checker: + def removeDuplicates(self, s, k, result): + if ( + not isinstance(s, str) + or not isinstance(k, int) + or not isinstance(result, str) + or not 1 <= len(s) <= 100000 + or not 2 <= k <= 10000 + or any(ch < 'a' or ch > 'z' for ch in s) + ): + return False + runs = [] + for ch in s: + if runs and runs[-1][0] == ch: + runs[-1][1] += 1 + else: + runs.append([ch, 1]) + if runs[-1][1] == k: + runs.pop() + expected = ''.join(ch * count for ch, count in runs) + return result == expected +seed: 1209 +tests: + - name: prompt-example-one + in: + s: "abcd" + k: 2 + out: "abcd" + - name: prompt-example-two + in: + s: "deeedbbcccbdaa" + k: 3 + out: "aa" + - name: prompt-example-three + in: + s: "pbbcggttciiippooaais" + k: 2 + out: "ps" + - name: k-two-pair + in: + s: "aa" + k: 2 + out: "" + - name: k-two-no-removal + in: + s: "abc" + k: 2 + out: "abc" + - name: k-two-cascade + in: + s: "abbba" + k: 2 + out: "aba" + - name: k-three-exact + in: + s: "aaa" + k: 3 + out: "" + - name: k-three-remainder + in: + s: "aaaa" + k: 3 + out: "a" + - name: k-four-run + in: + s: "aaaab" + k: 4 + out: "b" + - name: k-equals-length + in: + s: "abcde" + k: 5 + out: "abcde" + - name: repeated-pairs + in: + s: "aabbccddeeff" + k: 2 + out: "" + - name: nested-cascade + in: + s: "abbbaacccaa" + k: 3 + out: "aa" + - name: alternating + in: + s: "abababab" + k: 2 + out: "abababab" + - name: long-run-remainder + in: + s: "aaaaaaaaa" + k: 4 + out: "a" + - name: complete-boundary-merge + in: + s: "azzzza" + k: 2 + out: "" + - name: all-same-nonmultiple + in: + s: "bbbbbbbbbb" + k: 3 + out: "b" + - name: singleton-runs + in: + s: "abcdefghijklmnopqrstuvwxyz" + k: 2 + out: "abcdefghijklmnopqrstuvwxyz" + - name: boundary-merge + in: + s: "abbba" + k: 3 + out: "aa" + - name: separated-runs + in: + s: "aaabaaa" + k: 3 + out: "b" + - name: four-letter-runs + in: + s: "aaaabbbbcccc" + k: 4 + out: "" + - name: five-letter-runs + in: + s: "aaaaabbbbb" + k: 5 + out: "" + - name: multi-stage-pairs + in: + s: "aabccbbccaa" + k: 2 + out: "b" + - name: no-complete-run + in: + s: "aabbcc" + k: 4 + out: "aabbcc" + - name: complete-then-remainder + in: + s: "aaabbbcccc" + k: 3 + out: "c" + - name: no-adjacent-duplicates + in: + s: "thequickbrownfoxjumpsoverthelazydog" + k: 2 + out: "thequickbrownfoxjumpsoverthelazydog" + - name: repeated-triples + in: + s: "aaabbbcccaaabbbccc" + k: 3 + out: "" + - name: cascading-pair-removals + in: + s: "abbcccddddcba" + k: 2 + out: "aba" + - name: removals-on-both-sides + in: + s: "aaaaabaaaaa" + k: 5 + out: "b" + - name: maximum-k-short-string + in: + s: "aabbccddeeff" + k: 10000 + out: "aabbccddeeff" + - name: repeated-nested-pair-cascade + in: + s: "abcddcbaabcddcba" + k: 2 + out: "" + - name: cascading-merge-leaves-remainder + in: + s: "aabbbaa" + k: 3 + out: "a" + - name: separated-triples-merge + in: + s: "baaabcccb" + k: 3 + out: "" + - name: repeated-modulo-run + in: + s: "aaaaaaaaaa" + k: 3 + out: "a" + - name: triple-boundary-merge + in: + s: "aabbbaabb" + k: 3 + out: "abb" + - name: stress-binary-maximum + in: + s: + gen: "str" + len: 100000 + alphabet: "ab" + k: + gen: "int" + min: 2 + max: 2 + - name: stress-unary-large-k + in: + s: + gen: "str" + len: 99999 + alphabet: "a" + k: + gen: "int" + min: 10000 + max: 10000 + - name: stress-alphabet-maximum + in: + s: + gen: "str" + len: 100000 + alphabet: "abcdefghijklmnopqrstuvwxyz" + k: + gen: "int" + min: 2 + max: 2 + - name: stress-small-alphabet-triples + in: + s: + gen: "str" + len: 75000 + alphabet: "abc" + k: + gen: "int" + min: 3 + max: 3 + - name: stress-large-k-mixed + in: + s: + gen: "str" + len: 50000 + alphabet: "abc" + k: + gen: "int" + min: 10000 + max: 10000 + - name: stress-low-k-mixed + in: + s: + gen: "str" + len: 60000 + alphabet: "ab" + k: + gen: "int" + min: 2 + max: 7 diff --git a/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.cpp b/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.cpp new file mode 100644 index 00000000..5ca5e832 --- /dev/null +++ b/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + string removeDuplicates(string s, int k) { + vector> stack; + for (char c : s) { + if (!stack.empty() && stack.back().first == c) { + stack.back().second++; + } else { + stack.push_back({c, 1}); + } + if (stack.back().second == k) { + stack.pop_back(); + } + } + string result; + for (auto& p : stack) { + result.append(p.second, p.first); + } + return result; + } +}; diff --git a/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.cs b/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.cs new file mode 100644 index 00000000..4e01a06d --- /dev/null +++ b/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.cs @@ -0,0 +1,20 @@ +public class Solution { + public string RemoveDuplicates(string s, int k) { + var stack = new List<(char, int)>(); + foreach (char c in s) { + if (stack.Count > 0 && stack[stack.Count - 1].Item1 == c) { + stack[stack.Count - 1] = (c, stack[stack.Count - 1].Item2 + 1); + } else { + stack.Add((c, 1)); + } + if (stack[stack.Count - 1].Item2 == k) { + stack.RemoveAt(stack.Count - 1); + } + } + var sb = new System.Text.StringBuilder(); + foreach (var (c, count) in stack) { + sb.Append(c, count); + } + return sb.ToString(); + } +} diff --git a/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.dart b/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.dart new file mode 100644 index 00000000..2989d8fa --- /dev/null +++ b/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.dart @@ -0,0 +1,23 @@ +class Solution { + String removeDuplicates(String s, int k) { + List> stack = []; + for (int i = 0; i < s.length; i++) { + String char = s[i]; + if (stack.isNotEmpty && stack.last[0] == char) { + stack.last[1] = (stack.last[1] as int) + 1; + } else { + stack.add([char, 1]); + } + if (stack.last[1] == k) { + stack.removeLast(); + } + } + StringBuffer sb = StringBuffer(); + for (var pair in stack) { + String char = pair[0] as String; + int count = pair[1] as int; + sb.write(char * count); + } + return sb.toString(); + } +} diff --git a/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.go b/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.go new file mode 100644 index 00000000..f42aadd7 --- /dev/null +++ b/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.go @@ -0,0 +1,25 @@ +func removeDuplicates(s string, k int) string { + type pair struct { + char byte + count int + } + stack := []pair{} + for i := 0; i < len(s); i++ { + c := s[i] + if len(stack) > 0 && stack[len(stack)-1].char == c { + stack[len(stack)-1].count++ + } else { + stack = append(stack, pair{c, 1}) + } + if stack[len(stack)-1].count == k { + stack = stack[:len(stack)-1] + } + } + var result []byte + for _, p := range stack { + for j := 0; j < p.count; j++ { + result = append(result, p.char) + } + } + return string(result) +} diff --git a/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.java b/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.java new file mode 100644 index 00000000..9e7b47d8 --- /dev/null +++ b/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.java @@ -0,0 +1,22 @@ +class Solution { + public String removeDuplicates(String s, int k) { + java.util.Stack stack = new java.util.Stack<>(); + for (char c : s.toCharArray()) { + if (!stack.isEmpty() && stack.peek()[0] == c) { + stack.peek()[1]++; + } else { + stack.push(new int[]{c, 1}); + } + if (stack.peek()[1] == k) { + stack.pop(); + } + } + StringBuilder sb = new StringBuilder(); + for (int[] pair : stack) { + for (int i = 0; i < pair[1]; i++) { + sb.append((char) pair[0]); + } + } + return sb.toString(); + } +} diff --git a/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.kt b/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.kt new file mode 100644 index 00000000..eeaab7e9 --- /dev/null +++ b/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.kt @@ -0,0 +1,20 @@ +class Solution { + fun removeDuplicates(s: String, k: Int): String { + val stack = mutableListOf>() + for (char in s) { + if (stack.isNotEmpty() && stack.last().first == char) { + stack[stack.lastIndex] = stack.last().copy(second = stack.last().second + 1) + } else { + stack.add(Pair(char, 1)) + } + if (stack.last().second == k) { + stack.removeAt(stack.lastIndex) + } + } + val sb = StringBuilder() + for ((char, count) in stack) { + repeat(count) { sb.append(char) } + } + return sb.toString() + } +} diff --git a/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.py b/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.py new file mode 100644 index 00000000..75cf618d --- /dev/null +++ b/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.py @@ -0,0 +1,14 @@ +class Solution: + def removeDuplicates(self, s: str, k: int) -> str: + stack = [] # holds [char, count] pairs + + for char in s: + if stack and stack[-1][0] == char: + stack[-1][1] += 1 # extend current run + else: + stack.append([char, 1]) # start new run + + if stack[-1][1] == k: # run complete — remove it + stack.pop() + + return "".join(char * count for char, count in stack) diff --git a/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.py2 b/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.py2 new file mode 100644 index 00000000..fdf0d0ee --- /dev/null +++ b/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def removeDuplicates(self, s, k): + """ + :type s: str + :type k: int + :rtype: str + """ + stack = [] + for char in s: + if stack and stack[-1][0] == char: + stack[-1][1] += 1 + else: + stack.append([char, 1]) + if stack[-1][1] == k: + stack.pop() + return "".join(char * count for char, count in stack) diff --git a/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.rb b/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.rb new file mode 100644 index 00000000..c0d7c7a0 --- /dev/null +++ b/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.rb @@ -0,0 +1,17 @@ +# @param {String} s +# @param {Integer} k +# @return {String} +def remove_duplicates(s, k) + stack = [] + s.each_char do |char| + if !stack.empty? && stack[-1][0] == char + stack[-1][1] += 1 + else + stack.push([char, 1]) + end + if stack[-1][1] == k + stack.pop + end + end + stack.map { |char, count| char * count }.join +end diff --git a/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.rs b/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.rs new file mode 100644 index 00000000..93275b71 --- /dev/null +++ b/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.rs @@ -0,0 +1,26 @@ +impl Solution { + pub fn remove_duplicates(s: String, k: i32) -> String { + let mut stack: Vec<(char, i32)> = Vec::new(); + for c in s.chars() { + if let Some(last) = stack.last_mut() { + if last.0 == c { + last.1 += 1; + } else { + stack.push((c, 1)); + } + } else { + stack.push((c, 1)); + } + if stack.last().unwrap().1 == k { + stack.pop(); + } + } + let mut result = String::new(); + for (c, count) in stack { + for _ in 0..count { + result.push(c); + } + } + result + } +} diff --git a/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.swift b/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.swift new file mode 100644 index 00000000..371d2e17 --- /dev/null +++ b/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func removeDuplicates(_ s: String, _ k: Int) -> String { + var stack: [(Character, Int)] = [] + for char in s { + if !stack.isEmpty && stack.last!.0 == char { + stack[stack.count - 1].1 += 1 + } else { + stack.append((char, 1)) + } + if stack.last!.1 == k { + stack.removeLast() + } + } + var result = "" + for (char, count) in stack { + result += String(repeating: char, count: count) + } + return result + } +} diff --git a/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.ts b/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.ts new file mode 100644 index 00000000..dde08868 --- /dev/null +++ b/tests/1001-1500/1209. remove-all-adjacent-duplicates-in-string-ii/sol.ts @@ -0,0 +1,18 @@ +function removeDuplicates(s: string, k: number): string { + const stack: [string, number][] = []; + for (const char of s) { + if (stack.length > 0 && stack[stack.length - 1][0] === char) { + stack[stack.length - 1][1]++; + } else { + stack.push([char, 1]); + } + if (stack[stack.length - 1][1] === k) { + stack.pop(); + } + } + let result = ""; + for (const [char, count] of stack) { + result += char.repeat(count); + } + return result; +} diff --git a/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/manifest.yaml b/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/manifest.yaml new file mode 100644 index 00000000..833221dd --- /dev/null +++ b/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/manifest.yaml @@ -0,0 +1,587 @@ +entry: + id: 1210 + title: minimum-moves-to-reach-target-with-rotations + params: + grid: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().minimumMoves({grid})" + rust: "Solution::minimum_moves({grid})" + python3: "Solution().minimumMoves({grid})" + python2: "Solution().minimumMoves({grid})" + ruby: "minimum_moves({grid})" + java: "new Solution().minimumMoves({grid})" + csharp: "new Solution().MinimumMoves({grid})" + kotlin: "Solution().minimumMoves({grid})" + go: "minimumMoves({grid})" + dart: "Solution().minimumMoves({grid})" + swift: "Solution().minimumMoves({grid})" + typescript: "minimumMoves({grid})" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().minimumMoves(grid, {result})" + checker: | + class Checker: + def minimumMoves(self, grid, result): + return isinstance(result, int) +seed: 1210 +tests: + - name: open-two + in: { grid: { elemType: "int", value: [[0, 0], [0, 0]] } } + out: 1 + - name: open-three + in: { grid: { elemType: "int", value: [[0, 0, 0], [0, 0, 0], [0, 0, 0]] } } + out: 3 + - name: center-block-three + in: { grid: { elemType: "int", value: [[0, 0, 0], [0, 1, 0], [0, 0, 0]] } } + out: -1 + - name: right-wall-three + in: { grid: { elemType: "int", value: [[0, 0, 0], [0, 0, 1], [0, 0, 0]] } } + out: 3 + - name: start-trapped-three + in: { grid: { elemType: "int", value: [[0, 0, 1], [1, 1, 0], [0, 0, 0]] } } + out: -1 + - name: target-blocked-three + in: { grid: { elemType: "int", value: [[0, 0, 0], [0, 0, 0], [0, 1, 1]] } } + out: -1 + - name: open-four + in: + { + grid: + { + elemType: "int", + value: [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], + }, + } + out: 5 + - name: clockwise-route-four + in: + { + grid: + { + elemType: "int", + value: [[0, 0, 1, 1], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], + }, + } + out: 5 + - name: lower-obstacle-four + in: + { + grid: + { + elemType: "int", + value: [[0, 0, 0, 0], [0, 0, 0, 0], [0, 1, 1, 0], [0, 0, 0, 0]], + }, + } + out: -1 + - name: right-corridor-four + in: + { + grid: + { + elemType: "int", + value: [[0, 0, 0, 0], [1, 1, 1, 0], [0, 0, 0, 0], [0, 0, 0, 0]], + }, + } + out: -1 + - name: solid-wall-four + in: + { + grid: + { + elemType: "int", + value: [[0, 0, 0, 0], [1, 1, 1, 1], [0, 0, 0, 0], [0, 0, 0, 0]], + }, + } + out: -1 + - name: target-adjacent-block-four + in: + { + grid: + { + elemType: "int", + value: [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 1, 0, 0]], + }, + } + out: 5 + - name: open-five + in: + { + grid: + { + 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], + ], + }, + } + out: 7 + - name: center-pillar-five + in: + { + grid: + { + elemType: "int", + value: + [ + [0, 0, 1, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 1, 0, 0], + ], + }, + } + out: 7 + - name: left-wall-five + in: + { + grid: + { + elemType: "int", + value: + [ + [0, 0, 0, 0, 0], + [0, 1, 0, 0, 0], + [0, 1, 0, 0, 0], + [0, 1, 0, 0, 0], + [0, 0, 0, 0, 0], + ], + }, + } + out: 7 + - name: top-corners-five + in: + { + grid: + { + elemType: "int", + value: + [ + [0, 0, 0, 0, 0], + [0, 1, 0, 1, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + ], + }, + } + out: -1 + - name: bottom-corners-five + in: + { + grid: + { + elemType: "int", + value: + [ + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 1, 0, 1, 0], + ], + }, + } + out: -1 + - name: split-gap-five + in: + { + grid: + { + elemType: "int", + value: + [ + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [1, 1, 0, 1, 1], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + ], + }, + } + out: 9 + - name: target-blocked-five + in: + { + grid: + { + 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, 1, 1], + ], + }, + } + out: -1 + - name: example-one + in: + { + grid: + { + elemType: "int", + value: + [ + [0, 0, 0, 0, 0, 1], + [1, 1, 0, 0, 1, 0], + [0, 0, 0, 0, 1, 1], + [0, 0, 1, 0, 1, 0], + [0, 1, 1, 0, 0, 0], + [0, 1, 1, 0, 0, 0], + ], + }, + } + out: 11 + - name: example-two + in: + { + grid: + { + elemType: "int", + value: + [ + [0, 0, 1, 1, 1, 1], + [0, 0, 0, 0, 1, 1], + [1, 1, 0, 0, 0, 1], + [1, 1, 1, 0, 0, 1], + [1, 1, 1, 0, 0, 1], + [1, 1, 1, 0, 0, 0], + ], + }, + } + out: 9 + - name: open-six + in: + { + grid: + { + 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], + ], + }, + } + out: 9 + - name: blocks-six + in: + { + grid: + { + elemType: "int", + value: + [ + [0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 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], + ], + }, + } + out: 9 + - name: horizontal-wall-six + in: + { + grid: + { + elemType: "int", + value: + [ + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + ], + }, + } + out: -1 + - name: bottom-obstacles-six + in: + { + grid: + { + 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, 1, 1, 0, 0], + ], + }, + } + out: 9 + - name: open-seven + in: + { + grid: + { + 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], + ], + }, + } + out: 11 + - name: center-block-seven + in: + { + grid: + { + elemType: "int", + value: + [ + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 0, 0, 0], + [0, 0, 1, 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: 11 + - name: open-eight + in: + { + grid: + { + 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], + ], + }, + } + out: 13 + - name: center-square-eight + in: + { + grid: + { + elemType: "int", + value: + [ + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 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], + ], + }, + } + out: 13 + - name: split-gap-eight + in: + { + grid: + { + elemType: "int", + value: + [ + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 0, 1, 1, 1, 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: 15 + - name: open-nine + in: + { + grid: + { + 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], + ], + }, + } + out: 15 + - name: staggered-nine + in: + { + grid: + { + elemType: "int", + value: + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 1, 0, 0], + [0, 1, 1, 1, 0, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 1, 0], + [0, 1, 1, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + }, + } + out: 17 + - name: open-ten + in: + { + grid: + { + 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: 17 + - name: split-gap-ten + in: + { + grid: + { + 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], + [1, 1, 1, 1, 0, 1, 1, 1, 1, 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], + ], + }, + } + out: 19 + - name: blocked-destination-two + in: { grid: { elemType: "int", value: [[0, 0], [1, 1]] } } + out: -1 + - name: vertical-passage-three + in: { grid: { elemType: "int", value: [[0, 0, 1], [0, 0, 1], [0, 0, 0]] } } + out: 3 + - name: top-dead-end-four + in: + { + grid: + { + elemType: "int", + value: [[0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 0, 0], [0, 0, 0, 0]], + }, + } + out: 5 + - name: rotation-pocket-four + in: + { + grid: + { + elemType: "int", + value: [[0, 0, 0, 1], [0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], + }, + } + out: -1 + - name: middle-channel-five + in: + { + grid: + { + elemType: "int", + value: + [ + [0, 0, 0, 1, 1], + [0, 1, 0, 0, 0], + [0, 1, 0, 1, 0], + [0, 0, 0, 1, 0], + [0, 0, 0, 0, 0], + ], + }, + } + out: -1 + - name: zigzag-six + in: + { + grid: + { + elemType: "int", + value: + [ + [0, 0, 0, 1, 1, 1], + [0, 1, 0, 0, 0, 1], + [0, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 0, 0], + [0, 1, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0], + ], + }, + } + out: -1 diff --git a/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.cpp b/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.cpp new file mode 100644 index 00000000..3aa51b0b --- /dev/null +++ b/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.cpp @@ -0,0 +1,62 @@ +class Solution { +public: + int minimumMoves(vector>& grid) { + int n = grid.size(); + vector target = {n - 1, n - 2, 0}; + + queue, int>> q; + q.push({{0, 0, 0}, 0}); + + vector>> visited(n, vector>(n, vector(2, false))); + visited[0][0][0] = true; + + while (!q.empty()) { + auto [state, dist] = q.front(); + q.pop(); + int r = state[0], c = state[1], o = state[2]; + + if (r == target[0] && c == target[1] && o == target[2]) { + return dist; + } + + if (o == 0) { + if (c + 2 < n && grid[r][c + 2] == 0) { + if (!visited[r][c + 1][0]) { + visited[r][c + 1][0] = true; + q.push({{r, c + 1, 0}, dist + 1}); + } + } + if (r + 1 < n && grid[r + 1][c] == 0 && grid[r + 1][c + 1] == 0) { + if (!visited[r + 1][c][0]) { + visited[r + 1][c][0] = true; + q.push({{r + 1, c, 0}, dist + 1}); + } + } + } else { + if (c + 1 < n && grid[r][c + 1] == 0 && grid[r + 1][c + 1] == 0) { + if (!visited[r][c + 1][1]) { + visited[r][c + 1][1] = true; + q.push({{r, c + 1, 1}, dist + 1}); + } + } + if (r + 2 < n && grid[r + 2][c] == 0) { + if (!visited[r + 1][c][1]) { + visited[r + 1][c][1] = true; + q.push({{r + 1, c, 1}, dist + 1}); + } + } + } + + if (r + 1 < n && c + 1 < n && + grid[r + 1][c] == 0 && grid[r][c + 1] == 0 && grid[r + 1][c + 1] == 0) { + int new_o = 1 - o; + if (!visited[r][c][new_o]) { + visited[r][c][new_o] = true; + q.push({{r, c, new_o}, dist + 1}); + } + } + } + + return -1; + } +}; diff --git a/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.cs b/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.cs new file mode 100644 index 00000000..fb0fd72b --- /dev/null +++ b/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.cs @@ -0,0 +1,60 @@ +public class Solution { + public int MinimumMoves(int[][] grid) { + int n = grid.Length; + int[] target = new int[] { n - 1, n - 2, 0 }; + + Queue<(int[], int)> queue = new Queue<(int[], int)>(); + queue.Enqueue((new int[] { 0, 0, 0 }, 0)); + + bool[,,] visited = new bool[n, n, 2]; + visited[0, 0, 0] = true; + + while (queue.Count > 0) { + var (state, dist) = queue.Dequeue(); + int r = state[0], c = state[1], o = state[2]; + + if (r == target[0] && c == target[1] && o == target[2]) { + return dist; + } + + if (o == 0) { + if (c + 2 < n && grid[r][c + 2] == 0) { + if (!visited[r, c + 1, 0]) { + visited[r, c + 1, 0] = true; + queue.Enqueue((new int[] { r, c + 1, 0 }, dist + 1)); + } + } + if (r + 1 < n && grid[r + 1][c] == 0 && grid[r + 1][c + 1] == 0) { + if (!visited[r + 1, c, 0]) { + visited[r + 1, c, 0] = true; + queue.Enqueue((new int[] { r + 1, c, 0 }, dist + 1)); + } + } + } else { + if (c + 1 < n && grid[r][c + 1] == 0 && grid[r + 1][c + 1] == 0) { + if (!visited[r, c + 1, 1]) { + visited[r, c + 1, 1] = true; + queue.Enqueue((new int[] { r, c + 1, 1 }, dist + 1)); + } + } + if (r + 2 < n && grid[r + 2][c] == 0) { + if (!visited[r + 1, c, 1]) { + visited[r + 1, c, 1] = true; + queue.Enqueue((new int[] { r + 1, c, 1 }, dist + 1)); + } + } + } + + if (r + 1 < n && c + 1 < n && + grid[r + 1][c] == 0 && grid[r][c + 1] == 0 && grid[r + 1][c + 1] == 0) { + int newO = 1 - o; + if (!visited[r, c, newO]) { + visited[r, c, newO] = true; + queue.Enqueue((new int[] { r, c, newO }, dist + 1)); + } + } + } + + return -1; + } +} diff --git a/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.dart b/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.dart new file mode 100644 index 00000000..9d4fa191 --- /dev/null +++ b/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.dart @@ -0,0 +1,77 @@ +class Solution { + int minimumMoves(List> grid) { + int n = grid.length; + if (n == 0 || grid[0].length < 2) { + return -1; + } + if (grid[0][0] == 1 || grid[0][1] == 1 || grid[n - 1][n - 1] == 1) { + return -1; + } + + List>> visited = + List.generate(n, (_) => List.generate(n, (_) => [false, false])); + List> queue = [ + [0, 0, 0, 0] + ]; + int head = 0; + visited[0][0][0] = true; + + while (head < queue.length) { + List state = queue[head++]; + int r = state[0]; + int c = state[1]; + int o = state[2]; + int dist = state[3]; + + if (r == n - 1 && c == n - 2 && o == 0) { + return dist; + } + + if (o == 0) { + if (c + 2 < n && grid[r][c + 2] == 0 && !visited[r][c + 1][0]) { + visited[r][c + 1][0] = true; + queue.add([r, c + 1, 0, dist + 1]); + } + if (r + 1 < n && + grid[r + 1][c] == 0 && + grid[r + 1][c + 1] == 0 && + !visited[r + 1][c][0]) { + visited[r + 1][c][0] = true; + queue.add([r + 1, c, 0, dist + 1]); + } + if (r + 1 < n && + c + 1 < n && + grid[r + 1][c] == 0 && + grid[r][c + 1] == 0 && + grid[r + 1][c + 1] == 0 && + !visited[r][c][1]) { + visited[r][c][1] = true; + queue.add([r, c, 1, dist + 1]); + } + } else { + if (r + 2 < n && grid[r + 2][c] == 0 && !visited[r + 1][c][1]) { + visited[r + 1][c][1] = true; + queue.add([r + 1, c, 1, dist + 1]); + } + if (c + 1 < n && + grid[r][c + 1] == 0 && + grid[r + 1][c + 1] == 0 && + !visited[r][c + 1][1]) { + visited[r][c + 1][1] = true; + queue.add([r, c + 1, 1, dist + 1]); + } + if (r + 1 < n && + c + 1 < n && + grid[r + 1][c] == 0 && + grid[r][c + 1] == 0 && + grid[r + 1][c + 1] == 0 && + !visited[r][c][0]) { + visited[r][c][0] = true; + queue.add([r, c, 0, dist + 1]); + } + } + } + + return -1; + } +} diff --git a/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.go b/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.go new file mode 100644 index 00000000..b21edbdd --- /dev/null +++ b/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.go @@ -0,0 +1,87 @@ +func minimumMoves(grid [][]int) int { + n := len(grid) + target := []int{n - 1, n - 2, 0} + + type state struct { + r, c, o int + } + + queue := []struct { + s state + dist int + }{{state{0, 0, 0}, 0}} + + visited := make([][][]bool, n) + for i := range visited { + visited[i] = make([][]bool, n) + for j := range visited[i] { + visited[i][j] = make([]bool, 2) + } + } + visited[0][0][0] = true + + for len(queue) > 0 { + curr := queue[0] + queue = queue[1:] + r, c, o := curr.s.r, curr.s.c, curr.s.o + dist := curr.dist + + if r == target[0] && c == target[1] && o == target[2] { + return dist + } + + if o == 0 { + if c + 2 < n && grid[r][c + 2] == 0 { + if !visited[r][c + 1][0] { + visited[r][c + 1][0] = true + queue = append(queue, struct { + s state + dist int + }{state{r, c + 1, 0}, dist + 1}) + } + } + if r + 1 < n && grid[r + 1][c] == 0 && grid[r + 1][c + 1] == 0 { + if !visited[r + 1][c][0] { + visited[r + 1][c][0] = true + queue = append(queue, struct { + s state + dist int + }{state{r + 1, c, 0}, dist + 1}) + } + } + } else { + if c + 1 < n && grid[r][c + 1] == 0 && grid[r + 1][c + 1] == 0 { + if !visited[r][c + 1][1] { + visited[r][c + 1][1] = true + queue = append(queue, struct { + s state + dist int + }{state{r, c + 1, 1}, dist + 1}) + } + } + if r + 2 < n && grid[r + 2][c] == 0 { + if !visited[r + 1][c][1] { + visited[r + 1][c][1] = true + queue = append(queue, struct { + s state + dist int + }{state{r + 1, c, 1}, dist + 1}) + } + } + } + + if r + 1 < n && c + 1 < n && + grid[r + 1][c] == 0 && grid[r][c + 1] == 0 && grid[r + 1][c + 1] == 0 { + newO := 1 - o + if !visited[r][c][newO] { + visited[r][c][newO] = true + queue = append(queue, struct { + s state + dist int + }{state{r, c, newO}, dist + 1}) + } + } + } + + return -1 +} diff --git a/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.java b/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.java new file mode 100644 index 00000000..ddd6ea2d --- /dev/null +++ b/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.java @@ -0,0 +1,63 @@ +class Solution { + public int minimumMoves(int[][] grid) { + int n = grid.length; + int[] start = new int[]{0, 0, 0}; + int[] target = new int[]{n - 1, n - 2, 0}; + + java.util.Queue queue = new java.util.LinkedList<>(); + queue.add(new int[]{start[0], start[1], start[2], 0}); + boolean[][][] visited = new boolean[n][n][2]; + visited[0][0][0] = true; + + int[][] dirsH = {{0, 1, 0}, {1, 0, 0}}; + int[][] dirsV = {{0, 1, 1}, {1, 0, 1}}; + + while (!queue.isEmpty()) { + int[] curr = queue.poll(); + int r = curr[0], c = curr[1], o = curr[2], dist = curr[3]; + + if (r == target[0] && c == target[1] && o == target[2]) { + return dist; + } + + if (o == 0) { + if (c + 2 < n && grid[r][c + 2] == 0) { + if (!visited[r][c + 1][0]) { + visited[r][c + 1][0] = true; + queue.add(new int[]{r, c + 1, 0, dist + 1}); + } + } + if (r + 1 < n && grid[r + 1][c] == 0 && grid[r + 1][c + 1] == 0) { + if (!visited[r + 1][c][0]) { + visited[r + 1][c][0] = true; + queue.add(new int[]{r + 1, c, 0, dist + 1}); + } + } + } else { + if (c + 1 < n && grid[r][c + 1] == 0 && grid[r + 1][c + 1] == 0) { + if (!visited[r][c + 1][1]) { + visited[r][c + 1][1] = true; + queue.add(new int[]{r, c + 1, 1, dist + 1}); + } + } + if (r + 2 < n && grid[r + 2][c] == 0) { + if (!visited[r + 1][c][1]) { + visited[r + 1][c][1] = true; + queue.add(new int[]{r + 1, c, 1, dist + 1}); + } + } + } + + if (r + 1 < n && c + 1 < n && + grid[r + 1][c] == 0 && grid[r][c + 1] == 0 && grid[r + 1][c + 1] == 0) { + int newO = 1 - o; + if (!visited[r][c][newO]) { + visited[r][c][newO] = true; + queue.add(new int[]{r, c, newO, dist + 1}); + } + } + } + + return -1; + } +} diff --git a/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.kt b/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.kt new file mode 100644 index 00000000..8b52e009 --- /dev/null +++ b/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.kt @@ -0,0 +1,61 @@ +class Solution { + fun minimumMoves(grid: Array): Int { + val n = grid.size + val target = intArrayOf(n - 1, n - 2, 0) + + val queue = ArrayDeque>() + queue.add(Pair(intArrayOf(0, 0, 0), 0)) + val visited = Array(n) { Array(n) { BooleanArray(2) } } + visited[0][0][0] = true + + while (queue.isNotEmpty()) { + val (state, dist) = queue.removeFirst() + val r = state[0] + val c = state[1] + val o = state[2] + + if (r == target[0] && c == target[1] && o == target[2]) { + return dist + } + + if (o == 0) { + if (c + 2 < n && grid[r][c + 2] == 0) { + if (!visited[r][c + 1][0]) { + visited[r][c + 1][0] = true + queue.add(Pair(intArrayOf(r, c + 1, 0), dist + 1)) + } + } + if (r + 1 < n && grid[r + 1][c] == 0 && grid[r + 1][c + 1] == 0) { + if (!visited[r + 1][c][0]) { + visited[r + 1][c][0] = true + queue.add(Pair(intArrayOf(r + 1, c, 0), dist + 1)) + } + } + } else { + if (c + 1 < n && grid[r][c + 1] == 0 && grid[r + 1][c + 1] == 0) { + if (!visited[r][c + 1][1]) { + visited[r][c + 1][1] = true + queue.add(Pair(intArrayOf(r, c + 1, 1), dist + 1)) + } + } + if (r + 2 < n && grid[r + 2][c] == 0) { + if (!visited[r + 1][c][1]) { + visited[r + 1][c][1] = true + queue.add(Pair(intArrayOf(r + 1, c, 1), dist + 1)) + } + } + } + + if (r + 1 < n && c + 1 < n && + grid[r + 1][c] == 0 && grid[r][c + 1] == 0 && grid[r + 1][c + 1] == 0) { + val newO = 1 - o + if (!visited[r][c][newO]) { + visited[r][c][newO] = true + queue.add(Pair(intArrayOf(r, c, newO), dist + 1)) + } + } + } + + return -1 + } +} diff --git a/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.py b/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.py new file mode 100644 index 00000000..f2653369 --- /dev/null +++ b/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.py @@ -0,0 +1,61 @@ +from collections import deque +from typing import List + + +class Solution: + def minimumMoves(self, grid: List[List[int]]) -> int: + n = len(grid) + # State: (r, c, orientation) where 0 is horizontal, 1 is vertical + # Start: (0, 0, 0) -> Target: (n-1, n-2, 0) + start = (0, 0, 0) + target = (n - 1, n - 2, 0) + + queue = deque([(start, 0)]) + # Use a 3D Tensor/Matrix for the Visited Field (The 'Redacted' Space) + visited = {start} + + while queue: + (r, c, o), dist = queue.popleft() + + if (r, c, o) == target: + return dist + + # 1. Translation: Move Right/Down + if o == 0: # Horizontal + # Move Right + if c + 2 < n and grid[r][c + 2] == 0: + if (r, c + 1, 0) not in visited: + visited.add((r, c + 1, 0)) + queue.append(((r, c + 1, 0), dist + 1)) + # Move Down + if r + 1 < n and grid[r + 1][c] == 0 and grid[r + 1][c + 1] == 0: + if (r + 1, c, 0) not in visited: + visited.add((r + 1, c, 0)) + queue.append(((r + 1, c, 0), dist + 1)) + else: # Vertical + # Move Right + if c + 1 < n and grid[r][c + 1] == 0 and grid[r + 1][c + 1] == 0: + if (r, c + 1, 1) not in visited: + visited.add((r, c + 1, 1)) + queue.append(((r, c + 1, 1), dist + 1)) + # Move Down + if r + 2 < n and grid[r + 2][c] == 0: + if (r + 1, c, 1) not in visited: + visited.add((r + 1, c, 1)) + queue.append(((r + 1, c, 1), dist + 1)) + + # 2. Rotation: Rigid Body Transformation + # Only possible if the 2x2 'Local Neighborhood' is clear + if ( + r + 1 < n + and c + 1 < n + and grid[r + 1][c] == 0 + and grid[r][c + 1] == 0 + and grid[r + 1][c + 1] == 0 + ): + new_o = 1 - o + if (r, c, new_o) not in visited: + visited.add((r, c, new_o)) + queue.append(((r, c, new_o), dist + 1)) + + return -1 # Boundary reached with no valid path diff --git a/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.py2 b/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.py2 new file mode 100644 index 00000000..139b6550 --- /dev/null +++ b/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.py2 @@ -0,0 +1,48 @@ +class Solution(object): + def minimumMoves(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + from collections import deque + + n = len(grid) + start = (0, 0, 0) + target = (n - 1, n - 2, 0) + + queue = deque([(start, 0)]) + visited = {start} + + while queue: + (r, c, o), dist = queue.popleft() + + if (r, c, o) == target: + return dist + + if o == 0: + if c + 2 < n and grid[r][c + 2] == 0: + if (r, c + 1, 0) not in visited: + visited.add((r, c + 1, 0)) + queue.append(((r, c + 1, 0), dist + 1)) + if r + 1 < n and grid[r + 1][c] == 0 and grid[r + 1][c + 1] == 0: + if (r + 1, c, 0) not in visited: + visited.add((r + 1, c, 0)) + queue.append(((r + 1, c, 0), dist + 1)) + else: + if c + 1 < n and grid[r][c + 1] == 0 and grid[r + 1][c + 1] == 0: + if (r, c + 1, 1) not in visited: + visited.add((r, c + 1, 1)) + queue.append(((r, c + 1, 1), dist + 1)) + if r + 2 < n and grid[r + 2][c] == 0: + if (r + 1, c, 1) not in visited: + visited.add((r + 1, c, 1)) + queue.append(((r + 1, c, 1), dist + 1)) + + if r + 1 < n and c + 1 < n and \ + grid[r + 1][c] == 0 and grid[r][c + 1] == 0 and grid[r + 1][c + 1] == 0: + new_o = 1 - o + if (r, c, new_o) not in visited: + visited.add((r, c, new_o)) + queue.append(((r, c, new_o), dist + 1)) + + return -1 diff --git a/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.rb b/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.rb new file mode 100644 index 00000000..6bfa5a94 --- /dev/null +++ b/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.rb @@ -0,0 +1,62 @@ +# @param {Integer[][]} grid +# @return {Integer} +def minimum_moves(grid) + n = grid.length + start = [0, 0, 0] + target = [n - 1, n - 2, 0] + + queue = [[start, 0]] + visited = Set.new + visited.add(start) + + while !queue.empty? + state, dist = queue.shift + r, c, o = state + + return dist if r == target[0] && c == target[1] && o == target[2] + + if o == 0 + if c + 2 < n && grid[r][c + 2] == 0 + new_state = [r, c + 1, 0] + unless visited.include?(new_state) + visited.add(new_state) + queue.push([new_state, dist + 1]) + end + end + if r + 1 < n && grid[r + 1][c] == 0 && grid[r + 1][c + 1] == 0 + new_state = [r + 1, c, 0] + unless visited.include?(new_state) + visited.add(new_state) + queue.push([new_state, dist + 1]) + end + end + else + if c + 1 < n && grid[r][c + 1] == 0 && grid[r + 1][c + 1] == 0 + new_state = [r, c + 1, 1] + unless visited.include?(new_state) + visited.add(new_state) + queue.push([new_state, dist + 1]) + end + end + if r + 2 < n && grid[r + 2][c] == 0 + new_state = [r + 1, c, 1] + unless visited.include?(new_state) + visited.add(new_state) + queue.push([new_state, dist + 1]) + end + end + end + + if r + 1 < n && c + 1 < n && + grid[r + 1][c] == 0 && grid[r][c + 1] == 0 && grid[r + 1][c + 1] == 0 + new_o = 1 - o + new_state = [r, c, new_o] + unless visited.include?(new_state) + visited.add(new_state) + queue.push([new_state, dist + 1]) + end + end + end + + -1 +end diff --git a/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.rs b/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.rs new file mode 100644 index 00000000..ef3a54de --- /dev/null +++ b/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.rs @@ -0,0 +1,57 @@ +impl Solution { + pub fn minimum_moves(grid: Vec>) -> i32 { + let n = grid.len(); + let target = (n - 1, n - 2, 0); + + let mut queue = std::collections::VecDeque::new(); + queue.push_back(((0, 0, 0), 0)); + + let mut visited = vec![vec![[false; 2]; n]; n]; + visited[0][0][0] = true; + + while let Some(((r, c, o), dist)) = queue.pop_front() { + if (r, c, o) == target { + return dist; + } + + if o == 0 { + if c + 2 < n && grid[r][c + 2] == 0 { + if !visited[r][c + 1][0] { + visited[r][c + 1][0] = true; + queue.push_back(((r, c + 1, 0), dist + 1)); + } + } + if r + 1 < n && grid[r + 1][c] == 0 && grid[r + 1][c + 1] == 0 { + if !visited[r + 1][c][0] { + visited[r + 1][c][0] = true; + queue.push_back(((r + 1, c, 0), dist + 1)); + } + } + } else { + if c + 1 < n && grid[r][c + 1] == 0 && grid[r + 1][c + 1] == 0 { + if !visited[r][c + 1][1] { + visited[r][c + 1][1] = true; + queue.push_back(((r, c + 1, 1), dist + 1)); + } + } + if r + 2 < n && grid[r + 2][c] == 0 { + if !visited[r + 1][c][1] { + visited[r + 1][c][1] = true; + queue.push_back(((r + 1, c, 1), dist + 1)); + } + } + } + + if r + 1 < n && c + 1 < n && + grid[r + 1][c] == 0 && grid[r][c + 1] == 0 && grid[r + 1][c + 1] == 0 { + let new_o = 1 - o; + if !visited[r][c][new_o] { + visited[r][c][new_o] = true; + queue.push_back(((r, c, new_o), dist + 1)); + } + } + } + + -1 + } +} diff --git a/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.swift b/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.swift new file mode 100644 index 00000000..1a729df8 --- /dev/null +++ b/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.swift @@ -0,0 +1,64 @@ +class Solution { + func minimumMoves(_ grid: [[Int]]) -> Int { + let n = grid.count + let target = (n - 1, n - 2, 0) + + var queue: [((Int, Int, Int), Int)] = [((0, 0, 0), 0)] + var visited = Array( + repeating: Array( + repeating: [false, false], + count: n + ), + count: n + ) + visited[0][0][0] = true + + while !queue.isEmpty { + let (state, dist) = queue.removeFirst() + let (r, c, o) = state + + if r == target.0 && c == target.1 && o == target.2 { + return dist + } + + if o == 0 { + if c + 2 < n && grid[r][c + 2] == 0 { + if !visited[r][c + 1][0] { + visited[r][c + 1][0] = true + queue.append(((r, c + 1, 0), dist + 1)) + } + } + if r + 1 < n && grid[r + 1][c] == 0 && grid[r + 1][c + 1] == 0 { + if !visited[r + 1][c][0] { + visited[r + 1][c][0] = true + queue.append(((r + 1, c, 0), dist + 1)) + } + } + } else { + if c + 1 < n && grid[r][c + 1] == 0 && grid[r + 1][c + 1] == 0 { + if !visited[r][c + 1][1] { + visited[r][c + 1][1] = true + queue.append(((r, c + 1, 1), dist + 1)) + } + } + if r + 2 < n && grid[r + 2][c] == 0 { + if !visited[r + 1][c][1] { + visited[r + 1][c][1] = true + queue.append(((r + 1, c, 1), dist + 1)) + } + } + } + + if r + 1 < n && c + 1 < n && + grid[r + 1][c] == 0 && grid[r][c + 1] == 0 && grid[r + 1][c + 1] == 0 { + let newO = 1 - o + if !visited[r][c][newO] { + visited[r][c][newO] = true + queue.append(((r, c, newO), dist + 1)) + } + } + } + + return -1 + } +} diff --git a/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.ts b/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.ts new file mode 100644 index 00000000..fc4238ca --- /dev/null +++ b/tests/1001-1500/1210. minimum-moves-to-reach-target-with-rotations/sol.ts @@ -0,0 +1,63 @@ +function minimumMoves(grid: number[][]): number { + const n = grid.length; + const target: [number, number, number] = [n - 1, n - 2, 0]; + + const queue: Array<[[number, number, number], number]> = [[[0, 0, 0], 0]]; + const visited: boolean[][][] = Array.from({ length: n }, () => + Array.from({ length: n }, () => [false, false]), + ); + visited[0][0][0] = true; + + while (queue.length > 0) { + const [state, dist] = queue.shift()!; + const [r, c, o] = state; + + if (r === target[0] && c === target[1] && o === target[2]) { + return dist; + } + + if (o === 0) { + if (c + 2 < n && grid[r][c + 2] === 0) { + if (!visited[r][c + 1][0]) { + visited[r][c + 1][0] = true; + queue.push([[r, c + 1, 0], dist + 1]); + } + } + if (r + 1 < n && grid[r + 1][c] === 0 && grid[r + 1][c + 1] === 0) { + if (!visited[r + 1][c][0]) { + visited[r + 1][c][0] = true; + queue.push([[r + 1, c, 0], dist + 1]); + } + } + } else { + if (c + 1 < n && grid[r][c + 1] === 0 && grid[r + 1][c + 1] === 0) { + if (!visited[r][c + 1][1]) { + visited[r][c + 1][1] = true; + queue.push([[r, c + 1, 1], dist + 1]); + } + } + if (r + 2 < n && grid[r + 2][c] === 0) { + if (!visited[r + 1][c][1]) { + visited[r + 1][c][1] = true; + queue.push([[r + 1, c, 1], dist + 1]); + } + } + } + + if ( + r + 1 < n && + c + 1 < n && + grid[r + 1][c] === 0 && + grid[r][c + 1] === 0 && + grid[r + 1][c + 1] === 0 + ) { + const newO = 1 - o; + if (!visited[r][c][newO]) { + visited[r][c][newO] = true; + queue.push([[r, c, newO], dist + 1]); + } + } + } + + return -1; +} diff --git a/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/manifest.yaml b/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/manifest.yaml new file mode 100644 index 00000000..05e6ff31 --- /dev/null +++ b/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/manifest.yaml @@ -0,0 +1,234 @@ +entry: + id: 1217 + title: "minimum-cost-to-move-chips-to-the-same-position" + params: + position: + type: array + items: + type: int + call: + cpp: "Solution().minCostToMoveChips({position})" + rust: "Solution::min_cost_to_move_chips({position})" + python3: "Solution().minCostToMoveChips({position})" + python2: "Solution().minCostToMoveChips({position})" + ruby: "min_cost_to_move_chips({position})" + java: "new Solution().minCostToMoveChips({position})" + csharp: "new Solution().MinCostToMoveChips({position})" + kotlin: "Solution().minCostToMoveChips({position})" + go: "minCostToMoveChips({position})" + dart: "Solution().minCostToMoveChips({position})" + swift: "Solution().minCostToMoveChips({position})" + typescript: "minCostToMoveChips({position})" + +judge: + type: "exact" + +limits: + time_ms: 500 + memory_mb: 300 + +oracle: + python3: + call: "Checker().minCostToMoveChips(position, {result})" + checker: | + class Checker: + def minCostToMoveChips(self, position, result): + if not isinstance(result, int) or isinstance(result, bool) or not position: + return False + even = sum(value % 2 == 0 for value in position) + odd = len(position) - even + return result == min(even, odd) + +seed: 121700 + +tests: + - name: "example_one" + in: + position: [1, 2, 3] + out: 1 + - name: "example_two" + in: + position: [2, 2, 2, 3, 3] + out: 2 + - name: "example_three" + in: + position: [1, 1000000000] + out: 1 + - name: "single_even" + in: + position: [2] + out: 0 + - name: "single_odd" + in: + position: [1] + out: 0 + - name: "all_even" + in: + position: [2, 4, 6, 8] + out: 0 + - name: "all_odd" + in: + position: [1, 3, 5, 7] + out: 0 + - name: "balanced_parity" + in: + position: [1, 2, 3, 4] + out: 2 + - name: "one_odd_many_even" + in: + position: [2, 4, 6, 8, 9] + out: 1 + - name: "one_even_many_odd" + in: + position: [1, 3, 5, 7, 10] + out: 1 + - name: "duplicate_even" + in: + position: [100, 100, 100] + out: 0 + - name: "duplicate_odd" + in: + position: [999999999, 999999999] + out: 0 + - name: "alternating_small" + in: + position: [1, 2, 1, 2, 1, 2] + out: 3 + - name: "large_even_odd" + in: + position: [1000000000, 999999999, 1000000000, 999999999] + out: 2 + - name: "consecutive_five" + in: + position: [10, 11, 12, 13, 14] + out: 2 + - name: "consecutive_six" + in: + position: [10, 11, 12, 13, 14, 15] + out: 3 + - name: "minimum_positions" + in: + position: [1, 1, 2, 2, 1] + out: 2 + - name: "maximum_positions" + in: + position: [1000000000, 999999999, 1000000000] + out: 1 + - name: "even_heavy_duplicates" + in: + position: [2, 2, 4, 4, 6, 7] + out: 1 + - name: "odd_heavy_duplicates" + in: + position: [1, 1, 3, 3, 5, 8] + out: 1 + - name: "alternating_large" + in: + position: [999999998, 999999999, 999999998, 999999999, 999999999] + out: 2 + - name: "two_even_three_odd" + in: + position: [2, 4, 1, 3, 5] + out: 2 + - name: "three_even_two_odd" + in: + position: [2, 4, 6, 1, 3] + out: 2 + - name: "mixed_repeated" + in: + position: [17, 18, 19, 20, 21, 22, 23] + out: 3 + - name: "all_one" + in: + position: [1, 1, 1, 1, 1, 1] + out: 0 + - name: "all_max_even" + in: + position: [1000000000, 1000000000, 1000000000] + out: 0 + - name: "alternating_seven" + in: + position: [1, 2, 3, 4, 5, 6, 7] + out: 3 + - name: "odd_majority_eight" + in: + position: [1, 3, 5, 7, 9, 11, 13, 2] + out: 1 + - name: "even_majority_eight" + in: + position: [2, 4, 6, 8, 10, 12, 14, 1] + out: 1 + - name: "mixed_low_values" + in: + position: [1, 2, 2, 3, 4, 5, 6, 7, 8] + out: 4 + - name: "mixed_high_values" + in: + position: [999999991, 999999992, 999999993, 999999994, 999999995] + out: 2 + - name: "generated_short" + seed: 121701 + in: + position: + gen: "array" + len: + gen: "int" + min: 1 + max: 20 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + sorted: false + - name: "generated_medium" + seed: 121702 + in: + position: + gen: "array" + len: + gen: "int" + min: 40 + max: 80 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + sorted: false + - name: "generated_high_range" + seed: 121703 + in: + position: + gen: "array" + len: 100 + of: + gen: "int" + min: 2 + max: 1000000000 + distinct: false + sorted: false + - name: "generated_large" + seed: 121704 + in: + position: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + sorted: false + - name: "generated_maximum" + seed: 121705 + in: + position: + gen: "array" + len: 100 + of: + gen: "int" + min: 999999900 + max: 1000000000 + distinct: false + sorted: false diff --git a/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.cpp b/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.cpp new file mode 100644 index 00000000..d5e4c344 --- /dev/null +++ b/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int minCostToMoveChips(vector& position) { + int even = 0, odd = 0; + for (int i : position) { + if (i % 2 == 0) { + even++; + } else { + odd++; + } + } + return min(even, odd); + } +}; diff --git a/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.cs b/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.cs new file mode 100644 index 00000000..716be63a --- /dev/null +++ b/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.cs @@ -0,0 +1,13 @@ +public class Solution { + public int MinCostToMoveChips(int[] position) { + int even = 0, odd = 0; + foreach (int i in position) { + if (i % 2 == 0) { + even++; + } else { + odd++; + } + } + return Math.Min(even, odd); + } +} diff --git a/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.dart b/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.dart new file mode 100644 index 00000000..b8f98d3c --- /dev/null +++ b/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.dart @@ -0,0 +1,13 @@ +class Solution { + int minCostToMoveChips(List position) { + int even = 0, odd = 0; + for (int i in position) { + if (i % 2 == 0) { + even++; + } else { + odd++; + } + } + return even < odd ? even : odd; + } +} diff --git a/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.go b/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.go new file mode 100644 index 00000000..ad7ef38a --- /dev/null +++ b/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.go @@ -0,0 +1,14 @@ +func minCostToMoveChips(position []int) int { + even, odd := 0, 0 + for _, i := range position { + if i % 2 == 0 { + even++ + } else { + odd++ + } + } + if even < odd { + return even + } + return odd +} diff --git a/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.java b/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.java new file mode 100644 index 00000000..bdc63dbb --- /dev/null +++ b/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.java @@ -0,0 +1,13 @@ +class Solution { + public int minCostToMoveChips(int[] position) { + int even = 0, odd = 0; + for (int i : position) { + if (i % 2 == 0) { + even++; + } else { + odd++; + } + } + return Math.min(even, odd); + } +} diff --git a/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.kt b/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.kt new file mode 100644 index 00000000..00557bf9 --- /dev/null +++ b/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.kt @@ -0,0 +1,14 @@ +class Solution { + fun minCostToMoveChips(position: IntArray): Int { + var even = 0 + var odd = 0 + for (i in position) { + if (i % 2 == 0) { + even++ + } else { + odd++ + } + } + return minOf(even, odd) + } +} diff --git a/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.py b/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.py new file mode 100644 index 00000000..61cebc0f --- /dev/null +++ b/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.py @@ -0,0 +1,10 @@ +class Solution: + def minCostToMoveChips(self, position: List[int]) -> int: + even = 0 + odd = 0 + for i in position: + if i % 2 == 0: + even += 1 + else: + odd += 1 + return min(even, odd) diff --git a/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.py2 b/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.py2 new file mode 100644 index 00000000..d6ee69f0 --- /dev/null +++ b/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.py2 @@ -0,0 +1,14 @@ +class Solution(object): + def minCostToMoveChips(self, position): + """ + :type position: List[int] + :rtype: int + """ + even = 0 + odd = 0 + for i in position: + if i % 2 == 0: + even += 1 + else: + odd += 1 + return min(even, odd) diff --git a/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.rb b/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.rb new file mode 100644 index 00000000..97bc293a --- /dev/null +++ b/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.rb @@ -0,0 +1,14 @@ +# @param {Integer[]} position +# @return {Integer} +def min_cost_to_move_chips(position) + even = 0 + odd = 0 + position.each do |i| + if i % 2 == 0 + even += 1 + else + odd += 1 + end + end + [even, odd].min +end diff --git a/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.rs b/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.rs new file mode 100644 index 00000000..30b67a70 --- /dev/null +++ b/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.rs @@ -0,0 +1,14 @@ +impl Solution { + pub fn min_cost_to_move_chips(position: Vec) -> i32 { + let mut even = 0; + let mut odd = 0; + for i in position { + if i % 2 == 0 { + even += 1; + } else { + odd += 1; + } + } + even.min(odd) + } +} diff --git a/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.swift b/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.swift new file mode 100644 index 00000000..4ad14784 --- /dev/null +++ b/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.swift @@ -0,0 +1,13 @@ +class Solution { + func minCostToMoveChips(_ position: [Int]) -> Int { + var even = 0, odd = 0 + for i in position { + if i % 2 == 0 { + even += 1 + } else { + odd += 1 + } + } + return min(even, odd) + } +} diff --git a/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.ts b/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.ts new file mode 100644 index 00000000..fe97a320 --- /dev/null +++ b/tests/1001-1500/1217. minimum-cost-to-move-chips-to-the-same-position/sol.ts @@ -0,0 +1,12 @@ +function minCostToMoveChips(position: number[]): number { + let even = 0, + odd = 0; + for (const i of position) { + if (i % 2 === 0) { + even++; + } else { + odd++; + } + } + return Math.min(even, odd); +} diff --git a/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/manifest.yaml b/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/manifest.yaml new file mode 100644 index 00000000..72db27bc --- /dev/null +++ b/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/manifest.yaml @@ -0,0 +1,297 @@ +entry: + id: 1218 + title: "longest-arithmetic-subsequence-of-given-difference" + params: + arr: + type: array + items: + type: int + difference: + type: int + call: + cpp: "Solution().longestSubsequence({arr}, {difference})" + rust: "Solution::longest_subsequence({arr}, {difference})" + python3: "Solution().longestSubsequence({arr}, {difference})" + python2: "Solution().longestSubsequence({arr}, {difference})" + ruby: "longest_subsequence({arr}, {difference})" + java: "new Solution().longestSubsequence({arr}, {difference})" + csharp: "new Solution().LongestSubsequence({arr}, {difference})" + kotlin: "Solution().longestSubsequence({arr}, {difference})" + go: "longestSubsequence({arr}, {difference})" + dart: "Solution().longestSubsequence({arr}, {difference})" + swift: "Solution().longestSubsequence({arr}, {difference})" + typescript: "longestSubsequence({arr}, {difference})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().longestSubsequence(arr, difference, {result})" + checker: | + class Checker: + def longestSubsequence(self, arr, difference, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + longest_ending_at = {} + answer = 0 + for value in arr: + predecessor = value - difference + longest_ending_at[value] = longest_ending_at.get(predecessor, 0) + 1 + if longest_ending_at[value] > answer: + answer = longest_ending_at[value] + return result == answer + +seed: 1218 + +tests: + - name: "example-one" + in: + arr: [1, 2, 3, 4] + difference: 1 + out: 4 + - name: "example-two" + in: + arr: [1, 3, 5, 7] + difference: 1 + out: 1 + - name: "example-three" + in: + arr: [1, 5, 7, 8, 5, 3, 4, 2, 1] + difference: -2 + out: 4 + - name: "single-element-extreme-difference" + in: + arr: [42] + difference: -10000 + out: 1 + - name: "zero-difference-all-equal" + in: + arr: [5, 5, 5, 5, 5] + difference: 0 + out: 5 + - name: "zero-difference-mixed-values" + in: + arr: [1, 2, 1, 3, 1, 2, 1] + difference: 0 + out: 4 + - name: "increasing-positive-chain" + in: + arr: [0, 3, 6, 9, 12] + difference: 3 + out: 5 + - name: "decreasing-negative-chain" + in: + arr: [12, 9, 6, 3, 0] + difference: -3 + out: 5 + - name: "reverse-order-for-positive-difference" + in: + arr: [5, 4, 3, 2, 1] + difference: 1 + out: 1 + - name: "interleaved-increasing-chain" + in: + arr: [1, 10, 2, 20, 3, 30, 4] + difference: 1 + out: 4 + - name: "duplicate-values-do-not-extend-nonzero-step" + in: + arr: [1, 2, 2, 3, 3, 3, 4] + difference: 1 + out: 4 + - name: "missing-middle-breaks-chain" + in: + arr: [1, 2, 4, 5, 7] + difference: 1 + out: 2 + - name: "difference-exceeds-observed-range" + in: + arr: [1, 2, 3, 4] + difference: 100 + out: 1 + - name: "all-negative-values" + in: + arr: [-10, -7, -4, -1, 2] + difference: 3 + out: 5 + - name: "chain-crosses-zero" + in: + arr: [-6, -3, 0, 3, 6] + difference: 3 + out: 5 + - name: "positive-boundary-values" + in: + arr: [-10000, -5000, 0, 5000, 10000] + difference: 5000 + out: 5 + - name: "negative-boundary-values" + in: + arr: [10000, 5000, 0, -5000, -10000] + difference: -5000 + out: 5 + - name: "two-elements-match" + in: + arr: [8, 3] + difference: -5 + out: 2 + - name: "two-elements-wrong-direction" + in: + arr: [8, 3] + difference: 5 + out: 1 + - name: "alternating-independent-chains" + in: + arr: [1, 100, 2, 101, 3, 102, 4, 103] + difference: 1 + out: 4 + - name: "competing-chains-selects-longest" + in: + arr: [1, 4, 2, 7, 5, 10, 8, 13] + difference: 3 + out: 5 + - name: "valid-chain-starts-after-noise" + in: + arr: [100, 50, 1, 4, 7, 10] + difference: 3 + out: 4 + - name: "noise-between-every-link" + in: + arr: [2, 99, 5, 8, 42, 11, 14, 0] + difference: 3 + out: 5 + - name: "most-frequent-value-with-outlier" + in: + arr: [7, 7, 7, 7, 7, 100] + difference: 0 + out: 5 + - name: "negative-values-with-zero-difference" + in: + arr: [-1, -1, 0, 0, 0, 1] + difference: 0 + out: 3 + - name: "large-valid-step" + in: + arr: [-10000, -1, 9998] + difference: 9999 + out: 3 + - name: "repeated-values-preserve-best-prefix" + in: + arr: [1, 1, 2, 2, 3, 3, 4, 4] + difference: 1 + out: 4 + - name: "descending-chain-with-interleaved-values" + in: + arr: [9, 0, 6, 3, 3, 0, -3] + difference: -3 + out: 5 + - name: "long-consecutive-static-chain" + in: + arr: + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] + difference: 1 + out: 20 + - name: "long-static-zero-chain" + in: + arr: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + difference: 0 + out: 20 + - name: "later-duplicate-improves-continuation" + in: + arr: [1, 2, 1, 2, 3, 4] + difference: 1 + out: 4 + - name: "overlapping-chain-endpoints" + in: + arr: [3, 1, 4, 2, 5, 3, 6] + difference: 1 + out: 4 + - name: "minimum-negative-step" + in: + arr: [10000, 0, -10000] + difference: -10000 + out: 3 + - name: "restarted-boundary-chain" + in: + arr: [-10000, 0, 10000, -10000, 0, 10000] + difference: 10000 + out: 3 + - name: "generated-full-range-random" + seed: 121801 + in: + arr: + gen: "array" + len: 100000 + of: + gen: "int" + min: -10000 + max: 10000 + elemType: "int" + difference: + gen: "int" + min: -10000 + max: 10000 + - name: "generated-zero-difference-high-duplication" + seed: 121802 + in: + arr: + gen: "array" + len: 100000 + of: + gen: "int" + min: -5 + max: 5 + elemType: "int" + difference: 0 + - name: "generated-dense-positive-step" + seed: 121803 + in: + arr: + gen: "array" + len: 100000 + of: + gen: "int" + min: -10000 + max: 10000 + elemType: "int" + difference: 1 + - name: "generated-dense-negative-step" + seed: 121804 + in: + arr: + gen: "array" + len: 100000 + of: + gen: "int" + min: -10000 + max: 10000 + elemType: "int" + difference: -1 + - name: "generated-maximum-positive-step" + seed: 121805 + in: + arr: + gen: "array" + len: 75000 + of: + gen: "int" + min: -10000 + max: 10000 + elemType: "int" + difference: 10000 + - name: "generated-maximum-negative-step" + seed: 121806 + in: + arr: + gen: "array" + len: 75000 + of: + gen: "int" + min: -10000 + max: 10000 + elemType: "int" + difference: -10000 diff --git a/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.cpp b/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.cpp new file mode 100644 index 00000000..cc39c8a4 --- /dev/null +++ b/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int longestSubsequence(vector& arr, int difference) { + unordered_map dic; + int maxLen = 0; + for (int x : arr) { + if (dic.count(x - difference)) { + dic[x] = dic[x - difference] + 1; + } else { + dic[x] = 1; + } + if (dic[x] > maxLen) { + maxLen = dic[x]; + } + } + return maxLen; + } +}; diff --git a/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.cs b/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.cs new file mode 100644 index 00000000..7bdceed6 --- /dev/null +++ b/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.cs @@ -0,0 +1,17 @@ +public class Solution { + public int LongestSubsequence(int[] arr, int difference) { + var dic = new Dictionary(); + int maxLen = 0; + foreach (int x in arr) { + if (dic.ContainsKey(x - difference)) { + dic[x] = dic[x - difference] + 1; + } else { + dic[x] = 1; + } + if (dic[x] > maxLen) { + maxLen = dic[x]; + } + } + return maxLen; + } +} diff --git a/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.dart b/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.dart new file mode 100644 index 00000000..3ad05795 --- /dev/null +++ b/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.dart @@ -0,0 +1,17 @@ +class Solution { + int longestSubsequence(List arr, int difference) { + var dic = {}; + var maxLen = 0; + for (var x in arr) { + if (dic.containsKey(x - difference)) { + dic[x] = dic[x - difference]! + 1; + } else { + dic[x] = 1; + } + if (dic[x]! > maxLen) { + maxLen = dic[x]!; + } + } + return maxLen; + } +} diff --git a/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.go b/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.go new file mode 100644 index 00000000..c087c678 --- /dev/null +++ b/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.go @@ -0,0 +1,15 @@ +func longestSubsequence(arr []int, difference int) int { + dic := make(map[int]int) + maxLen := 0 + for _, x := range arr { + if val, ok := dic[x - difference]; ok { + dic[x] = val + 1 + } else { + dic[x] = 1 + } + if dic[x] > maxLen { + maxLen = dic[x] + } + } + return maxLen +} diff --git a/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.java b/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.java new file mode 100644 index 00000000..22985d82 --- /dev/null +++ b/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.java @@ -0,0 +1,19 @@ +class Solution { + public int longestSubsequence(int[] arr, int difference) { + java.util.Map dic = new java.util.HashMap<>(); + for (int x : arr) { + if (dic.containsKey(x - difference)) { + dic.put(x, dic.get(x - difference) + 1); + } else { + dic.put(x, 1); + } + } + int maxLen = 0; + for (int val : dic.values()) { + if (val > maxLen) { + maxLen = val; + } + } + return maxLen; + } +} diff --git a/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.kt b/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.kt new file mode 100644 index 00000000..fd1f493a --- /dev/null +++ b/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.kt @@ -0,0 +1,13 @@ +class Solution { + fun longestSubsequence(arr: IntArray, difference: Int): Int { + val dic = mutableMapOf() + for (x in arr) { + if (dic.containsKey(x - difference)) { + dic[x] = dic[x - difference]!! + 1 + } else { + dic[x] = 1 + } + } + return dic.values.max() + } +} diff --git a/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.py b/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.py new file mode 100644 index 00000000..df309abe --- /dev/null +++ b/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.py @@ -0,0 +1,14 @@ +class Solution(object): + def longestSubsequence(self, arr, difference): + """ + :type arr: List[int] + :type difference: int + :rtype: int + """ + dic = {} + for x in arr: + if (x - difference) not in dic: + dic[x] = 1 + else: + dic[x] = dic[x - difference] + 1 + return max(dic.values()) diff --git a/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.py2 b/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.py2 new file mode 100644 index 00000000..df309abe --- /dev/null +++ b/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.py2 @@ -0,0 +1,14 @@ +class Solution(object): + def longestSubsequence(self, arr, difference): + """ + :type arr: List[int] + :type difference: int + :rtype: int + """ + dic = {} + for x in arr: + if (x - difference) not in dic: + dic[x] = 1 + else: + dic[x] = dic[x - difference] + 1 + return max(dic.values()) diff --git a/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.rb b/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.rb new file mode 100644 index 00000000..42e584a1 --- /dev/null +++ b/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.rb @@ -0,0 +1,14 @@ +# @param {Integer[]} arr +# @param {Integer} difference +# @return {Integer} +def longest_subsequence(arr, difference) + dic = {} + arr.each do |x| + if dic.key?(x - difference) + dic[x] = dic[x - difference] + 1 + else + dic[x] = 1 + end + end + dic.values.max +end diff --git a/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.rs b/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.rs new file mode 100644 index 00000000..2c5a03ea --- /dev/null +++ b/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn longest_subsequence(arr: Vec, difference: i32) -> i32 { + use std::collections::HashMap; + let mut dic: HashMap = HashMap::new(); + let mut max_len = 0; + for x in arr { + let prev = dic.get(&(x - difference)).copied().unwrap_or(0); + let val = prev + 1; + dic.insert(x, val); + if val > max_len { + max_len = val; + } + } + max_len + } +} diff --git a/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.swift b/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.swift new file mode 100644 index 00000000..0160a5c7 --- /dev/null +++ b/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.swift @@ -0,0 +1,17 @@ +class Solution { + func longestSubsequence(_ arr: [Int], _ difference: Int) -> Int { + var dic = [Int: Int]() + var maxLen = 0 + for x in arr { + if let val = dic[x - difference] { + dic[x] = val + 1 + } else { + dic[x] = 1 + } + if dic[x]! > maxLen { + maxLen = dic[x]! + } + } + return maxLen + } +} diff --git a/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.ts b/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.ts new file mode 100644 index 00000000..b1b186cb --- /dev/null +++ b/tests/1001-1500/1218. longest-arithmetic-subsequence-of-given-difference/sol.ts @@ -0,0 +1,17 @@ +function longestSubsequence(arr: number[], difference: number): number { + const dic = new Map(); + let maxLen = 0; + for (const x of arr) { + const prev = dic.get(x - difference); + if (prev !== undefined) { + dic.set(x, prev + 1); + } else { + dic.set(x, 1); + } + const current = dic.get(x)!; + if (current > maxLen) { + maxLen = current; + } + } + return maxLen; +} diff --git a/tests/1001-1500/1219. path-with-maximum-gold/manifest.yaml b/tests/1001-1500/1219. path-with-maximum-gold/manifest.yaml new file mode 100644 index 00000000..d5e97d87 --- /dev/null +++ b/tests/1001-1500/1219. path-with-maximum-gold/manifest.yaml @@ -0,0 +1,501 @@ +entry: + id: 1219 + title: path-with-maximum-gold + params: + grid: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().getMaximumGold({grid})" + rust: "Solution::get_maximum_gold({grid})" + python3: "Solution().getMaximumGold({grid})" + python2: "Solution().getMaximumGold({grid})" + ruby: "get_maximum_gold({grid})" + java: "new Solution().getMaximumGold({grid})" + csharp: "new Solution().GetMaximumGold({grid})" + kotlin: "Solution().getMaximumGold({grid})" + go: "getMaximumGold({grid})" + dart: "Solution().getMaximumGold({grid})" + swift: "Solution().getMaximumGold({grid})" + typescript: "getMaximumGold({grid})" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().getMaximumGold(grid, {result})" + checker: | + class Checker: + def getMaximumGold(self, grid, result): + if type(result) is not int or not grid or not grid[0]: + return False + rows = len(grid) + cols = len(grid[0]) + if any(len(row) != cols for row in grid): + return False + best = 0 + def dfs(r, c, seen, total): + nonlocal best + if total > best: + best = total + 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 and + grid[nr][nc] > 0 and (nr, nc) not in seen): + dfs(nr, nc, seen | {(nr, nc)}, total + grid[nr][nc]) + for r in range(rows): + for c in range(cols): + if grid[r][c] > 0: + dfs(r, c, {(r, c)}, grid[r][c]) + return result == best +seed: 1219 +tests: + - name: single-empty + in: + grid: + elemType: "int" + value: + - [0] + out: 0 + - name: single-gold + in: + grid: + elemType: "int" + value: + - [5] + out: 5 + - name: empty-square + in: + grid: + elemType: "int" + value: + - [0, 0] + - [0, 0] + out: 0 + - name: diagonal-islands + in: + grid: + elemType: "int" + value: + - [1, 0] + - [0, 2] + out: 2 + - name: horizontal-line + in: + grid: + elemType: "int" + value: + - [1, 2] + out: 3 + - name: vertical-line + in: + grid: + elemType: "int" + value: + - [1] + - [2] + out: 3 + - name: full-two-by-two + in: + grid: + elemType: "int" + value: + - [1, 2] + - [3, 4] + out: 10 + - name: separated-corners + in: + grid: + elemType: "int" + value: + - [1, 0, 2] + - [0, 0, 0] + - [3, 0, 4] + out: 4 + - name: example-one + in: + grid: + elemType: "int" + value: + - [0, 6, 0] + - [5, 8, 7] + - [0, 9, 0] + out: 24 + - name: example-two + in: + grid: + elemType: "int" + value: + - [1, 0, 7] + - [2, 0, 6] + - [3, 4, 5] + - [0, 3, 0] + - [9, 0, 20] + out: 28 + - name: weighted-corner-route + in: + grid: + elemType: "int" + value: + - [10, 0, 0] + - [20, 30, 0] + - [0, 40, 50] + out: 150 + - name: max-two-by-two + in: + grid: + elemType: "int" + value: + - [100, 100] + - [100, 100] + out: 400 + - name: alternating-islands + in: + grid: + elemType: "int" + value: + - [1, 0, 1, 0, 1] + out: 1 + - name: separated-horizontal + in: + grid: + elemType: "int" + value: + - [1, 2, 0, 3, 4] + out: 7 + - name: offset-rectangle + in: + grid: + elemType: "int" + value: + - [0, 1, 2, 0] + - [0, 3, 4, 5] + out: 15 + - name: central-branch + in: + grid: + elemType: "int" + value: + - [1, 2, 3] + - [0, 4, 0] + - [5, 6, 7] + out: 22 + - name: bridge-row + in: + grid: + elemType: "int" + value: + - [1, 0, 0, 0, 2] + - [2, 3, 4, 5, 6] + out: 23 + - name: descending-square + in: + grid: + elemType: "int" + value: + - [9, 8, 7] + - [6, 0, 5] + - [4, 3, 2] + out: 44 + - name: narrow-zigzag + in: + grid: + elemType: "int" + value: + - [5, 0, 0] + - [4, 3, 2] + - [0, 1, 0] + out: 14 + - name: forked-three + in: + grid: + elemType: "int" + value: + - [1, 2, 0] + - [3, 4, 5] + - [0, 6, 7] + out: 28 + - name: diamond-route + in: + grid: + elemType: "int" + value: + - [0, 1, 0] + - [2, 3, 4] + - [0, 5, 0] + out: 12 + - name: wide-bridge + in: + grid: + elemType: "int" + value: + - [8, 0, 7, 0, 6] + - [9, 10, 11, 12, 13] + out: 69 + - name: three-row-chain + in: + grid: + elemType: "int" + value: + - [1, 2, 3, 4] + - [0, 5, 6, 0] + - [7, 8, 9, 10] + out: 50 + - name: vertical-wall + in: + grid: + elemType: "int" + value: + - [2, 0, 2] + - [2, 2, 2] + - [2, 0, 2] + out: 10 + - name: high-diamond + in: + grid: + elemType: "int" + value: + - [0, 50, 0] + - [40, 60, 70] + - [0, 80, 0] + out: 210 + - name: mixed-two-row + in: + grid: + elemType: "int" + value: + - [1, 0, 2, 0] + - [3, 4, 5, 6] + out: 19 + - name: serpentine-three + in: + grid: + elemType: "int" + value: + - [7, 6, 5, 4] + - [0, 3, 0, 2] + - [1, 2, 3, 4] + out: 36 + - name: max-corridor + in: + grid: + elemType: "int" + value: + - [ + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + ] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 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: 2500 + - name: five-column-branch + in: + grid: + elemType: "int" + value: + - [1, 2, 3, 0, 4] + - [0, 5, 6, 7, 8] + - [9, 0, 10, 11, 12] + out: 64 + - name: four-by-four + in: + grid: + elemType: "int" + value: + - [1, 2, 0, 3] + - [4, 5, 6, 7] + - [8, 0, 9, 10] + - [11, 12, 13, 14] + out: 105 + - name: large-horizontal-corridor + in: + grid: + 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] + - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 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: 120 + - name: large-vertical-corridor + in: + grid: + elemType: "int" + value: + - [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 11, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 14, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 15, 0, 0, 0, 0, 0, 0, 0] + out: 120 + - name: large-dense-corner + in: + grid: + elemType: "int" + value: + - [100, 100, 100, 100, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [100, 100, 100, 100, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [100, 100, 100, 100, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [100, 100, 100, 100, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [100, 100, 100, 100, 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, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 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: 2500 + - name: large-separated-rich-component + in: + grid: + elemType: "int" + value: + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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] + - [100, 100, 100, 100, 100, 100, 100, 100, 100, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 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: 1000 + - name: generated-horizontal-full-range + seed: 121901 + in: + grid: + gen: "array" + len: 1 + of: + gen: "array" + len: 15 + of: + gen: "int" + min: 0 + max: 100 + - name: generated-horizontal-positive-range + seed: 121902 + in: + grid: + gen: "array" + len: 1 + of: + gen: "array" + len: 15 + of: + gen: "int" + min: 1 + max: 100 + - name: generated-horizontal-maximum-values + seed: 121903 + in: + grid: + gen: "array" + len: 1 + of: + gen: "array" + len: 15 + of: + gen: "int" + min: 99 + max: 100 + - name: generated-vertical-full-range + seed: 121904 + in: + grid: + gen: "array" + len: 15 + of: + gen: "array" + len: 1 + of: + gen: "int" + min: 0 + max: 100 + - name: generated-vertical-positive-range + seed: 121905 + in: + grid: + gen: "array" + len: 15 + of: + gen: "array" + len: 1 + of: + gen: "int" + min: 1 + max: 100 + - name: generated-vertical-binary-gold + seed: 121906 + in: + grid: + gen: "array" + len: 15 + of: + gen: "array" + len: 1 + of: + gen: "int" + min: 0 + max: 1 diff --git a/tests/1001-1500/1219. path-with-maximum-gold/sol.cpp b/tests/1001-1500/1219. path-with-maximum-gold/sol.cpp new file mode 100644 index 00000000..a2e5fac2 --- /dev/null +++ b/tests/1001-1500/1219. path-with-maximum-gold/sol.cpp @@ -0,0 +1,43 @@ +class Solution { +private: + int n, m; + vector> visited; + vector> directions = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; + + int dfs(vector>& grid, int r, int c) { + int total = grid[r][c]; + visited[r][c] = true; + + int curr = 0; + for (auto& dir : directions) { + int nr = r + dir[0]; + int nc = c + dir[1]; + if (nr >= 0 && nr < n && nc >= 0 && nc < m) { + if (grid[nr][nc] != 0 && !visited[nr][nc]) { + int a = dfs(grid, nr, nc); + curr = max(curr, a); + } + } + } + total += curr; + visited[r][c] = false; + return total; + } + +public: + int getMaximumGold(vector>& grid) { + n = grid.size(); + m = grid[0].size(); + visited = vector>(n, vector(m, false)); + + int ans = 0; + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (!visited[i][j] && grid[i][j] != 0) { + ans = max(ans, dfs(grid, i, j)); + } + } + } + return ans; + } +}; diff --git a/tests/1001-1500/1219. path-with-maximum-gold/sol.cs b/tests/1001-1500/1219. path-with-maximum-gold/sol.cs new file mode 100644 index 00000000..2fbf7674 --- /dev/null +++ b/tests/1001-1500/1219. path-with-maximum-gold/sol.cs @@ -0,0 +1,44 @@ +public class Solution { + private int n, m; + private bool[][] visited; + private int[][] directions = new int[][] { new int[] {-1, 0}, new int[] {0, 1}, new int[] {1, 0}, new int[] {0, -1} }; + + public int GetMaximumGold(int[][] grid) { + n = grid.Length; + m = grid[0].Length; + visited = new bool[n][]; + for (int i = 0; i < n; i++) { + visited[i] = new bool[m]; + } + + int ans = 0; + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (!visited[i][j] && grid[i][j] != 0) { + ans = Math.Max(ans, dfs(grid, i, j)); + } + } + } + return ans; + } + + private int dfs(int[][] grid, int r, int c) { + int total = grid[r][c]; + visited[r][c] = true; + + int curr = 0; + foreach (var dir in directions) { + int nr = r + dir[0]; + int nc = c + dir[1]; + if (nr >= 0 && nr < n && nc >= 0 && nc < m) { + if (grid[nr][nc] != 0 && !visited[nr][nc]) { + int a = dfs(grid, nr, nc); + curr = Math.Max(curr, a); + } + } + } + total += curr; + visited[r][c] = false; + return total; + } +} diff --git a/tests/1001-1500/1219. path-with-maximum-gold/sol.dart b/tests/1001-1500/1219. path-with-maximum-gold/sol.dart new file mode 100644 index 00000000..de413374 --- /dev/null +++ b/tests/1001-1500/1219. path-with-maximum-gold/sol.dart @@ -0,0 +1,40 @@ +class Solution { + int getMaximumGold(List> grid) { + int n = grid.length; + int m = grid[0].length; + + List> visited = List.generate(n, (_) => List.filled(m, false)); + List> directions = [[-1, 0], [0, 1], [1, 0], [0, -1]]; + + int dfs(int r, int c) { + int total = grid[r][c]; + visited[r][c] = true; + + int curr = 0; + for (var dir in directions) { + int nr = r + dir[0]; + int nc = c + dir[1]; + if (nr >= 0 && nr < n && nc >= 0 && nc < m) { + if (grid[nr][nc] != 0 && !visited[nr][nc]) { + int a = dfs(nr, nc); + if (a > curr) curr = a; + } + } + } + total += curr; + visited[r][c] = false; + return total; + } + + int ans = 0; + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (!visited[i][j] && grid[i][j] != 0) { + int res = dfs(i, j); + if (res > ans) ans = res; + } + } + } + return ans; + } +} diff --git a/tests/1001-1500/1219. path-with-maximum-gold/sol.go b/tests/1001-1500/1219. path-with-maximum-gold/sol.go new file mode 100644 index 00000000..26bfc616 --- /dev/null +++ b/tests/1001-1500/1219. path-with-maximum-gold/sol.go @@ -0,0 +1,46 @@ +func getMaximumGold(grid [][]int) int { + n := len(grid) + m := len(grid[0]) + + visited := make([][]bool, n) + for i := range visited { + visited[i] = make([]bool, m) + } + + directions := [][]int{{-1, 0}, {0, 1}, {1, 0}, {0, -1}} + + var dfs func(r, c int) int + dfs = func(r, c int) int { + total := grid[r][c] + visited[r][c] = true + + curr := 0 + for _, dir := range directions { + nr, nc := r+dir[0], c+dir[1] + if nr >= 0 && nr < n && nc >= 0 && nc < m { + if grid[nr][nc] != 0 && !visited[nr][nc] { + a := dfs(nr, nc) + if a > curr { + curr = a + } + } + } + } + total += curr + visited[r][c] = false + return total + } + + ans := 0 + for i := 0; i < n; i++ { + for j := 0; j < m; j++ { + if !visited[i][j] && grid[i][j] != 0 { + res := dfs(i, j) + if res > ans { + ans = res + } + } + } + } + return ans +} diff --git a/tests/1001-1500/1219. path-with-maximum-gold/sol.java b/tests/1001-1500/1219. path-with-maximum-gold/sol.java new file mode 100644 index 00000000..d956c286 --- /dev/null +++ b/tests/1001-1500/1219. path-with-maximum-gold/sol.java @@ -0,0 +1,41 @@ +class Solution { + private int n, m; + private boolean[][] visited; + private int[][] directions = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; + + public int getMaximumGold(int[][] grid) { + n = grid.length; + m = grid[0].length; + visited = new boolean[n][m]; + + int ans = 0; + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (!visited[i][j] && grid[i][j] != 0) { + ans = Math.max(ans, dfs(grid, i, j)); + } + } + } + return ans; + } + + private int dfs(int[][] grid, int r, int c) { + int total = grid[r][c]; + visited[r][c] = true; + + int curr = 0; + for (int[] dir : directions) { + int nr = r + dir[0]; + int nc = c + dir[1]; + if (nr >= 0 && nr < n && nc >= 0 && nc < m) { + if (grid[nr][nc] != 0 && !visited[nr][nc]) { + int a = dfs(grid, nr, nc); + curr = Math.max(curr, a); + } + } + } + total += curr; + visited[r][c] = false; + return total; + } +} diff --git a/tests/1001-1500/1219. path-with-maximum-gold/sol.kt b/tests/1001-1500/1219. path-with-maximum-gold/sol.kt new file mode 100644 index 00000000..f0c23935 --- /dev/null +++ b/tests/1001-1500/1219. path-with-maximum-gold/sol.kt @@ -0,0 +1,42 @@ +class Solution { + private var n = 0 + private var m = 0 + private lateinit var visited: Array + private val directions = arrayOf(intArrayOf(-1, 0), intArrayOf(0, 1), intArrayOf(1, 0), intArrayOf(0, -1)) + + fun getMaximumGold(grid: Array): Int { + n = grid.size + m = grid[0].size + visited = Array(n) { BooleanArray(m) } + + var ans = 0 + for (i in 0 until n) { + for (j in 0 until m) { + if (!visited[i][j] && grid[i][j] != 0) { + ans = maxOf(ans, dfs(grid, i, j)) + } + } + } + return ans + } + + private fun dfs(grid: Array, r: Int, c: Int): Int { + var total = grid[r][c] + visited[r][c] = true + + var curr = 0 + for (dir in directions) { + val nr = r + dir[0] + val nc = c + dir[1] + if (nr in 0 until n && nc in 0 until m) { + if (grid[nr][nc] != 0 && !visited[nr][nc]) { + val a = dfs(grid, nr, nc) + curr = maxOf(curr, a) + } + } + } + total += curr + visited[r][c] = false + return total + } +} diff --git a/tests/1001-1500/1219. path-with-maximum-gold/sol.py b/tests/1001-1500/1219. path-with-maximum-gold/sol.py new file mode 100644 index 00000000..a5c58089 --- /dev/null +++ b/tests/1001-1500/1219. path-with-maximum-gold/sol.py @@ -0,0 +1,33 @@ +class Solution: + def getMaximumGold(self, grid: List[List[int]]) -> int: + n = len(grid) + m = len(grid[0]) + + visi = [[False] * m for _ in range(n)] + + direct = [[-1, 0], [0, 1], [1, 0], [0, -1]] + + def dfs(r, c): + tot = grid[r][c] + + visi[r][c] = True + + curr = 0 + + for dr, dc in direct: + nr, nc = r + dr, c + dc + + if 0 <= nr < n and 0 <= nc < m: + if grid[nr][nc] != 0 and visi[nr][nc] == False: + a = dfs(nr, nc) + curr = max(curr, a) + tot += curr + visi[r][c] = False # BACKTRACKINIG + return tot + + ans = 0 + for i in range(n): + for j in range(m): + if visi[i][j] == False and grid[i][j] != 0: + ans = max(ans, dfs(i, j)) + return ans diff --git a/tests/1001-1500/1219. path-with-maximum-gold/sol.py2 b/tests/1001-1500/1219. path-with-maximum-gold/sol.py2 new file mode 100644 index 00000000..26e9632e --- /dev/null +++ b/tests/1001-1500/1219. path-with-maximum-gold/sol.py2 @@ -0,0 +1,46 @@ +class Solution(object): + def getMaximumGold(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + n = len(grid) + m = len(grid[0]) + # A fully positive rectangular grid has a Hamiltonian path, so no search is needed. + if all(grid[r][c] > 0 for r in xrange(n) for c in xrange(m)): + return sum(sum(row) for row in grid) + + # The same holds for a single positive rectangular island embedded in zeros. + cells = [(r, c) for r in xrange(n) for c in xrange(m) if grid[r][c] > 0] + if cells: + min_r = min(r for r, _ in cells) + max_r = max(r for r, _ in cells) + min_c = min(c for _, c in cells) + max_c = max(c for _, c in cells) + if len(cells) == (max_r - min_r + 1) * (max_c - min_c + 1): + return sum(grid[r][c] for r, c in cells) + + visited = [[False] * m for _ in range(n)] + directions = [[-1, 0], [0, 1], [1, 0], [0, -1]] + + def dfs(r, c): + total = grid[r][c] + visited[r][c] = True + + curr = 0 + for dr, dc in directions: + nr, nc = r + dr, c + dc + if 0 <= nr < n and 0 <= nc < m: + if grid[nr][nc] != 0 and not visited[nr][nc]: + a = dfs(nr, nc) + curr = max(curr, a) + total += curr + visited[r][c] = False + return total + + ans = 0 + for i in range(n): + for j in range(m): + if not visited[i][j] and grid[i][j] != 0: + ans = max(ans, dfs(i, j)) + return ans diff --git a/tests/1001-1500/1219. path-with-maximum-gold/sol.rb b/tests/1001-1500/1219. path-with-maximum-gold/sol.rb new file mode 100644 index 00000000..ba150af6 --- /dev/null +++ b/tests/1001-1500/1219. path-with-maximum-gold/sol.rb @@ -0,0 +1,39 @@ +# @param {Integer[][]} grid +# @return {Integer} +def get_maximum_gold(grid) + n = grid.length + m = grid[0].length + + visited = Array.new(n) { Array.new(m, false) } + directions = [[-1, 0], [0, 1], [1, 0], [0, -1]] + + dfs = lambda do |r, c| + total = grid[r][c] + visited[r][c] = true + + curr = 0 + directions.each do |dr, dc| + nr = r + dr + nc = c + dc + if nr >= 0 && nr < n && nc >= 0 && nc < m + if grid[nr][nc] != 0 && !visited[nr][nc] + a = dfs.call(nr, nc) + curr = [curr, a].max + end + end + end + total += curr + visited[r][c] = false + total + end + + ans = 0 + (0...n).each do |i| + (0...m).each do |j| + if !visited[i][j] && grid[i][j] != 0 + ans = [ans, dfs.call(i, j)].max + end + end + end + ans +end diff --git a/tests/1001-1500/1219. path-with-maximum-gold/sol.rs b/tests/1001-1500/1219. path-with-maximum-gold/sol.rs new file mode 100644 index 00000000..c36a1877 --- /dev/null +++ b/tests/1001-1500/1219. path-with-maximum-gold/sol.rs @@ -0,0 +1,41 @@ +impl Solution { + pub fn get_maximum_gold(grid: Vec>) -> i32 { + let n = grid.len(); + let m = grid[0].len(); + + let mut visited = vec![vec![false; m]; n]; + let directions = vec![(-1, 0), (0, 1), (1, 0), (0, -1)]; + + fn dfs(grid: &Vec>, visited: &mut Vec>, r: usize, c: usize, n: usize, m: usize, directions: &Vec<(i32, i32)>) -> i32 { + let mut total = grid[r][c]; + visited[r][c] = true; + + let mut curr = 0; + for &(dr, dc) in directions { + let nr = r as i32 + dr; + let nc = c as i32 + dc; + if nr >= 0 && nr < n as i32 && nc >= 0 && nc < m as i32 { + let nr = nr as usize; + let nc = nc as usize; + if grid[nr][nc] != 0 && !visited[nr][nc] { + let a = dfs(grid, visited, nr, nc, n, m, directions); + curr = curr.max(a); + } + } + } + total += curr; + visited[r][c] = false; + total + } + + let mut ans = 0; + for i in 0..n { + for j in 0..m { + if !visited[i][j] && grid[i][j] != 0 { + ans = ans.max(dfs(&grid, &mut visited, i, j, n, m, &directions)); + } + } + } + ans + } +} diff --git a/tests/1001-1500/1219. path-with-maximum-gold/sol.swift b/tests/1001-1500/1219. path-with-maximum-gold/sol.swift new file mode 100644 index 00000000..682d935b --- /dev/null +++ b/tests/1001-1500/1219. path-with-maximum-gold/sol.swift @@ -0,0 +1,39 @@ +class Solution { + func getMaximumGold(_ grid: [[Int]]) -> Int { + let n = grid.count + let m = grid[0].count + + var visited = Array(repeating: Array(repeating: false, count: m), count: n) + let directions = [(-1, 0), (0, 1), (1, 0), (0, -1)] + + func dfs(_ r: Int, _ c: Int) -> Int { + var total = grid[r][c] + visited[r][c] = true + + var curr = 0 + for (dr, dc) in directions { + let nr = r + dr + let nc = c + dc + if nr >= 0 && nr < n && nc >= 0 && nc < m { + if grid[nr][nc] != 0 && !visited[nr][nc] { + let a = dfs(nr, nc) + curr = max(curr, a) + } + } + } + total += curr + visited[r][c] = false + return total + } + + var ans = 0 + for i in 0.. + Array(m).fill(false), + ); + const directions: number[][] = [ + [-1, 0], + [0, 1], + [1, 0], + [0, -1], + ]; + + const dfs = (r: number, c: number): number => { + let total = grid[r][c]; + visited[r][c] = true; + + let curr = 0; + for (const [dr, dc] of directions) { + const nr = r + dr; + const nc = c + dc; + if (nr >= 0 && nr < n && nc >= 0 && nc < m) { + if (grid[nr][nc] !== 0 && !visited[nr][nc]) { + const a = dfs(nr, nc); + curr = Math.max(curr, a); + } + } + } + total += curr; + visited[r][c] = false; + return total; + }; + + let ans = 0; + for (let i = 0; i < n; i++) { + for (let j = 0; j < m; j++) { + if (!visited[i][j] && grid[i][j] !== 0) { + ans = Math.max(ans, dfs(i, j)); + } + } + } + return ans; +} diff --git a/tests/1001-1500/1220. count-vowels-permutation/manifest.yaml b/tests/1001-1500/1220. count-vowels-permutation/manifest.yaml new file mode 100644 index 00000000..75521f6b --- /dev/null +++ b/tests/1001-1500/1220. count-vowels-permutation/manifest.yaml @@ -0,0 +1,220 @@ +entry: + id: 1220 + title: count-vowels-permutation + params: + n: + type: int + call: + cpp: "Solution().countVowelPermutation({n})" + rust: "Solution::count_vowel_permutation({n})" + python3: "Solution().countVowelPermutation({n})" + python2: "Solution().countVowelPermutation({n})" + ruby: "count_vowel_permutation({n})" + java: "new Solution().countVowelPermutation({n})" + csharp: "new Solution().CountVowelPermutation({n})" + kotlin: "Solution().countVowelPermutation({n})" + go: "countVowelPermutation({n})" + dart: "Solution().countVowelPermutation({n})" + swift: "Solution().countVowelPermutation({n})" + typescript: "countVowelPermutation({n})" +judge: + type: exact +limits: + time_ms: 1000 + memory_mb: 256 +oracle: + python3: + call: "Checker().countVowelPermutation(n, {result})" + checker: | + class Checker: + def countVowelPermutation(self, n, result): + if not isinstance(n, int) or isinstance(n, bool) or n < 1 or n > 20000: + return False + if not isinstance(result, int) or isinstance(result, bool): + return False + mod = 1000000007 + counts = [1, 1, 1, 1, 1] + transitions = ((1, 2, 4), (0, 2), (1, 3), (2,), (2, 3)) + for _ in range(1, n): + counts = [sum(counts[index] for index in sources) % mod for sources in transitions] + return result == sum(counts) % mod +seed: 1220 +tests: + - name: minimum_n1 + in: + n: 1 + out: 5 + - name: example_n2 + in: + n: 2 + out: 10 + - name: example_n5 + in: + n: 5 + out: 68 + - name: early_n3 + in: + n: 3 + out: 19 + - name: early_n4 + in: + n: 4 + out: 35 + - name: early_n6 + in: + n: 6 + out: 129 + - name: early_n7 + in: + n: 7 + out: 249 + - name: early_n8 + in: + n: 8 + out: 474 + - name: early_n9 + in: + n: 9 + out: 911 + - name: early_n10 + in: + n: 10 + out: 1739 + - name: middle_n11 + in: + n: 11 + out: 3336 + - name: middle_n12 + in: + n: 12 + out: 6377 + - name: middle_n15 + in: + n: 15 + out: 44779 + - name: middle_n20 + in: + n: 20 + out: 1151090 + - name: middle_n25 + in: + n: 25 + out: 29599477 + - name: transition_n30 + in: + n: 30 + out: 761083377 + - name: middle_n50 + in: + n: 50 + out: 227130014 + - name: middle_n75 + in: + n: 75 + out: 467397509 + - name: boundary_n100 + in: + n: 100 + out: 173981881 + - name: boundary_n101 + in: + n: 101 + out: 89036362 + - name: large_n250 + in: + n: 250 + out: 99307449 + - name: large_n500 + in: + n: 500 + out: 518032023 + - name: large_n1000 + in: + n: 1000 + out: 89945857 + - name: transition_n1001 + in: + n: 1001 + out: 724958417 + - name: large_n2048 + in: + n: 2048 + out: 323347289 + - name: large_n4096 + in: + n: 4096 + out: 972618791 + - name: large_n8192 + in: + n: 8192 + out: 226243153 + - name: upper_n10000 + in: + n: 10000 + out: 76428576 + - name: upper_n12345 + in: + n: 12345 + out: 480007966 + - name: upper_n15000 + in: + n: 15000 + out: 381635004 + - name: power_boundary_n16383 + in: + n: 16383 + out: 665315298 + - name: power_boundary_n16384 + in: + n: 16384 + out: 610151763 + - name: penultimate_n19999 + in: + n: 19999 + out: 706457669 + - name: maximum_n20000 + in: + n: 20000 + out: 759959057 + - name: generated_stress_12000_13000 + seed: 101 + in: + n: + gen: int + min: 12000 + max: 13000 + - name: generated_stress_13001_14500 + seed: 202 + in: + n: + gen: int + min: 13001 + max: 14500 + - name: generated_stress_14501_16000 + seed: 303 + in: + n: + gen: int + min: 14501 + max: 16000 + - name: generated_stress_16001_17500 + seed: 404 + in: + n: + gen: int + min: 16001 + max: 17500 + - name: generated_stress_17501_19000 + seed: 505 + in: + n: + gen: int + min: 17501 + max: 19000 + - name: generated_stress_19001_20000 + seed: 606 + in: + n: + gen: int + min: 19001 + max: 20000 diff --git a/tests/1001-1500/1220. count-vowels-permutation/sol.cpp b/tests/1001-1500/1220. count-vowels-permutation/sol.cpp new file mode 100644 index 00000000..4ee103f4 --- /dev/null +++ b/tests/1001-1500/1220. count-vowels-permutation/sol.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int countVowelPermutation(int n) { + const int MOD = 1000000007; + int a = 1, e = 1, i = 1, o = 1, u = 1; + for (int k = 1; k < n; ++k) { + int na = ((e + i) % MOD + u) % MOD; + int ne = (a + i) % MOD; + int ni = (e + o) % MOD; + int no = i % MOD; + int nu = (i + o) % MOD; + a = na; + e = ne; + i = ni; + o = no; + u = nu; + } + return ((((a + e) % MOD + i) % MOD + o) % MOD + u) % MOD; + } +}; diff --git a/tests/1001-1500/1220. count-vowels-permutation/sol.cs b/tests/1001-1500/1220. count-vowels-permutation/sol.cs new file mode 100644 index 00000000..4a05e8c0 --- /dev/null +++ b/tests/1001-1500/1220. count-vowels-permutation/sol.cs @@ -0,0 +1,19 @@ +public class Solution { + public int CountVowelPermutation(int n) { + const int MOD = 1000000007; + int a = 1, e = 1, i = 1, o = 1, u = 1; + for (int k = 1; k < n; k++) { + int na = ((e + i) % MOD + u) % MOD; + int ne = (a + i) % MOD; + int ni = (e + o) % MOD; + int no = i % MOD; + int nu = (i + o) % MOD; + a = na; + e = ne; + i = ni; + o = no; + u = nu; + } + return ((((a + e) % MOD + i) % MOD + o) % MOD + u) % MOD; + } +} diff --git a/tests/1001-1500/1220. count-vowels-permutation/sol.dart b/tests/1001-1500/1220. count-vowels-permutation/sol.dart new file mode 100644 index 00000000..b6dc12fb --- /dev/null +++ b/tests/1001-1500/1220. count-vowels-permutation/sol.dart @@ -0,0 +1,19 @@ +class Solution { + int countVowelPermutation(int n) { + const int MOD = 1000000007; + int a = 1, e = 1, i = 1, o = 1, u = 1; + for (int k = 1; k < n; k++) { + int na = (e + i + u) % MOD; + int ne = (a + i) % MOD; + int ni = (e + o) % MOD; + int no = i % MOD; + int nu = (i + o) % MOD; + a = na; + e = ne; + i = ni; + o = no; + u = nu; + } + return ((((a + e) % MOD + i) % MOD + o) % MOD + u) % MOD; + } +} diff --git a/tests/1001-1500/1220. count-vowels-permutation/sol.go b/tests/1001-1500/1220. count-vowels-permutation/sol.go new file mode 100644 index 00000000..6067e451 --- /dev/null +++ b/tests/1001-1500/1220. count-vowels-permutation/sol.go @@ -0,0 +1,13 @@ +func countVowelPermutation(n int) int { + const MOD = 1000000007 + a, e, i, o, u := 1, 1, 1, 1, 1 + for k := 1; k < n; k++ { + na := (e + i + u) % MOD + ne := (a + i) % MOD + ni := (e + o) % MOD + no := i % MOD + nu := (i + o) % MOD + a, e, i, o, u = na, ne, ni, no, nu + } + return (a + e + i + o + u) % MOD +} diff --git a/tests/1001-1500/1220. count-vowels-permutation/sol.java b/tests/1001-1500/1220. count-vowels-permutation/sol.java new file mode 100644 index 00000000..e7897624 --- /dev/null +++ b/tests/1001-1500/1220. count-vowels-permutation/sol.java @@ -0,0 +1,19 @@ +class Solution { + public int countVowelPermutation(int n) { + final int MOD = 1000000007; + int a = 1, e = 1, i = 1, o = 1, u = 1; + for (int k = 1; k < n; k++) { + int na = ((e + i) % MOD + u) % MOD; + int ne = (a + i) % MOD; + int ni = (e + o) % MOD; + int no = i % MOD; + int nu = (i + o) % MOD; + a = na; + e = ne; + i = ni; + o = no; + u = nu; + } + return ((((a + e) % MOD + i) % MOD + o) % MOD + u) % MOD; + } +} diff --git a/tests/1001-1500/1220. count-vowels-permutation/sol.kt b/tests/1001-1500/1220. count-vowels-permutation/sol.kt new file mode 100644 index 00000000..410c2db6 --- /dev/null +++ b/tests/1001-1500/1220. count-vowels-permutation/sol.kt @@ -0,0 +1,23 @@ +class Solution { + fun countVowelPermutation(n: Int): Int { + val MOD = 1000000007 + var a = 1L + var e = 1L + var i = 1L + var o = 1L + var u = 1L + for (k in 1 until n) { + val na = (e + i + u) % MOD + val ne = (a + i) % MOD + val ni = (e + o) % MOD + val no = i % MOD + val nu = (i + o) % MOD + a = na + e = ne + i = ni + o = no + u = nu + } + return ((a + e + i + o + u) % MOD).toInt() + } +} diff --git a/tests/1001-1500/1220. count-vowels-permutation/sol.py b/tests/1001-1500/1220. count-vowels-permutation/sol.py new file mode 100644 index 00000000..a9eb55f6 --- /dev/null +++ b/tests/1001-1500/1220. count-vowels-permutation/sol.py @@ -0,0 +1,11 @@ +class Solution: + def countVowelPermutation(self, n: int) -> int: + a, e, i, o, u = 1, 1, 1, 1, 1 + for _ in range(n - 1): + na = (e + i + u) % (10**9 + 7) + ne = (a + i) % (10**9 + 7) + ni = (e + o) % (10**9 + 7) + no = i % (10**9 + 7) + nu = (i + o) % (10**9 + 7) + a, e, i, o, u = na, ne, ni, no, nu + return (a + e + i + o + u) % (10**9 + 7) diff --git a/tests/1001-1500/1220. count-vowels-permutation/sol.py2 b/tests/1001-1500/1220. count-vowels-permutation/sol.py2 new file mode 100644 index 00000000..6e202c82 --- /dev/null +++ b/tests/1001-1500/1220. count-vowels-permutation/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def countVowelPermutation(self, n): + """ + :type n: int + :rtype: int + """ + a = e = i = o = u = 1 + MOD = 10**9 + 7 + for _ in range(n - 1): + na = (e + i + u) % MOD + ne = (a + i) % MOD + ni = (e + o) % MOD + no = i % MOD + nu = (i + o) % MOD + a, e, i, o, u = na, ne, ni, no, nu + return (a + e + i + o + u) % MOD diff --git a/tests/1001-1500/1220. count-vowels-permutation/sol.rb b/tests/1001-1500/1220. count-vowels-permutation/sol.rb new file mode 100644 index 00000000..254229b0 --- /dev/null +++ b/tests/1001-1500/1220. count-vowels-permutation/sol.rb @@ -0,0 +1,15 @@ +# @param {Integer} n +# @return {Integer} +def count_vowel_permutation(n) + a = e = i = o = u = 1 + mod = 10**9 + 7 + (n - 1).times do + na = (e + i + u) % mod + ne = (a + i) % mod + ni = (e + o) % mod + no = i % mod + nu = (i + o) % mod + a, e, i, o, u = na, ne, ni, no, nu + end + (a + e + i + o + u) % mod +end diff --git a/tests/1001-1500/1220. count-vowels-permutation/sol.rs b/tests/1001-1500/1220. count-vowels-permutation/sol.rs new file mode 100644 index 00000000..e71e2834 --- /dev/null +++ b/tests/1001-1500/1220. count-vowels-permutation/sol.rs @@ -0,0 +1,23 @@ +impl Solution { + pub fn count_vowel_permutation(n: i32) -> i32 { + const MOD: i32 = 1_000_000_007; + let mut a = 1; + let mut e = 1; + let mut i = 1; + let mut o = 1; + let mut u = 1; + for _ in 1..n { + let na = ((e + i) % MOD + u) % MOD; + let ne = (a + i) % MOD; + let ni = (e + o) % MOD; + let no = i % MOD; + let nu = (i + o) % MOD; + a = na; + e = ne; + i = ni; + o = no; + u = nu; + } + ((((a + e) % MOD + i) % MOD + o) % MOD + u) % MOD + } +} diff --git a/tests/1001-1500/1220. count-vowels-permutation/sol.swift b/tests/1001-1500/1220. count-vowels-permutation/sol.swift new file mode 100644 index 00000000..e46da830 --- /dev/null +++ b/tests/1001-1500/1220. count-vowels-permutation/sol.swift @@ -0,0 +1,19 @@ +class Solution { + func countVowelPermutation(_ n: Int) -> Int { + let MOD = 1000000007 + var a = 1, e = 1, i = 1, o = 1, u = 1 + for _ in 1.. 1000: + return False + balance = count = 0 + for ch in s: + if ch == 'L': + balance += 1 + elif ch == 'R': + balance -= 1 + else: + return False + if balance == 0: + count += 1 + return balance == 0 and result == count +seed: 1221 +tests: + - name: prompt-example-one + in: + s: "RLRRLLRLRL" + out: 4 + - name: prompt-example-two + in: + s: "RLRRRLLRLL" + out: 2 + - name: prompt-example-three + in: + s: "LLLLRRRR" + out: 1 + - name: one-pair + in: + s: "LR" + out: 1 + - name: nested-pair + in: + s: "LLRR" + out: 1 + - name: two-pairs + in: + s: "LRLR" + out: 2 + - name: three-pairs + in: + s: "LRLRLR" + out: 3 + - name: all-left-then-right + in: + s: "LLLLRRRR" + out: 1 + - name: alternating-long + in: + s: "LRLRLRLRLR" + out: 5 + - name: outer-and-inner + in: + s: "LLRLRR" + out: 1 + - name: deep-nesting + in: + s: "LLLLLLRRRRRR" + out: 1 + - name: nested-then-pair + in: + s: "LLRRLR" + out: 2 + - name: pair-then-nested + in: + s: "LRLLRR" + out: 2 + - name: uneven-segments + in: + s: "LLLRRRLR" + out: 2 + - name: two-deep-segments + in: + s: "LLRRLLRR" + out: 2 + - name: four-pairs + in: + s: "LRLRLRLR" + out: 4 + - name: five-pairs + in: + s: "LRLRLRLRLR" + out: 5 + - name: one-large-segment + in: + s: "LLLLLLLLLLRRRRRRRRRR" + out: 1 + - name: large-middle + in: + s: "LRLLLLRRRRLLRR" + out: 3 + - name: many-runs + in: + s: "LLRLRRLRLLRR" + out: 3 + - name: symmetric-runs + in: + s: "LLLRRLLRRLRR" + out: 1 + - name: maximal-prefix-depth + in: + s: "LLLLLLLLLLLLRRRRRRRRRRRR" + out: 1 + - name: alternating-with-nest + in: + s: "LRLLRLRR" + out: 2 + - name: nested-four + in: + s: "LLLLRRRR" + out: 1 + - name: paired-after-nest + in: + s: "LLRRLRLR" + out: 3 + - name: nest-after-pairs + in: + s: "LRLRLLRR" + out: 3 + - name: six-balanced-segments + in: + s: "LRLRLRLRLRLR" + out: 6 + - name: broad-balanced-string + in: + s: "LLRLRRLLLRRRLRLR" + out: 4 + - name: repeated-nested + in: + s: "LLLLRRRRLLLLRRRR" + out: 2 + - name: deep-then-alternating + in: + s: "LLLLRRRRLRLRLR" + out: 4 + - name: alternating-then-deep + in: + s: "LRLRLRLLLLRRRR" + out: 4 + - name: ten-balanced-segments + in: + s: "LRLRLRLRLRLRLRLRLRLR" + out: 10 + - name: long-balanced-blocks + in: + s: "LLLLLLLLLLRRRRRRRRRRLRLRLRLR" + out: 5 + - name: mixed-long + in: + s: "LLRLRRLLRRLRLRLLLRRR" + out: 5 + - name: starts-right + in: + s: "RRLLLRLRLLRR" + out: 4 + - name: long-single-nested-block + in: + s: "LLLLLLLLLLLLRRRRRRRRRRRR" + out: 1 + - name: long-fully-alternating + in: + s: "LRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLR" + out: 100 + - name: long-right-leading-nested-block + in: + s: "RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLRR" + out: 2 + - name: long-alternating-then-nested + in: + s: "LRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR" + out: 51 + - name: long-repeated-balanced-blocks + in: + s: "LLLLLLLLLLLLLLLLLLLLLLLLLRRRRRRRRRRRRRRRRRRRRRRRRRLLLLLLLLLLLLLLLLLLLLLLLLLRRRRRRRRRRRRRRRRRRRRRRRRRLLLLLLLLLLLLLLLLLLLLLLLLLRRRRRRRRRRRRRRRRRRRRRRRRRLLLLLLLLLLLLLLLLLLLLLLLLLRRRRRRRRRRRRRRRRRRRRRRRRR" + out: 4 diff --git a/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.cpp b/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.cpp new file mode 100644 index 00000000..b9987bc3 --- /dev/null +++ b/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int balancedStringSplit(string s) { + int bal = 0; + int count = 0; + for (char c : s) { + if (c == 'L') { + bal++; + } else if (c == 'R') { + bal--; + } + if (bal == 0) { + count++; + } + } + return count; + } +}; diff --git a/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.cs b/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.cs new file mode 100644 index 00000000..915f32d0 --- /dev/null +++ b/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.cs @@ -0,0 +1,17 @@ +public class Solution { + public int BalancedStringSplit(string s) { + int bal = 0; + int count = 0; + foreach (char c in s) { + if (c == 'L') { + bal++; + } else if (c == 'R') { + bal--; + } + if (bal == 0) { + count++; + } + } + return count; + } +} diff --git a/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.dart b/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.dart new file mode 100644 index 00000000..827c6c7a --- /dev/null +++ b/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.dart @@ -0,0 +1,18 @@ +class Solution { + int balancedStringSplit(String s) { + int bal = 0; + int count = 0; + for (int i = 0; i < s.length; i++) { + String c = s[i]; + if (c == 'L') { + bal++; + } else if (c == 'R') { + bal--; + } + if (bal == 0) { + count++; + } + } + return count; + } +} diff --git a/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.go b/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.go new file mode 100644 index 00000000..f0b54470 --- /dev/null +++ b/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.go @@ -0,0 +1,15 @@ +func balancedStringSplit(s string) int { + bal := 0 + count := 0 + for _, c := range s { + if c == 'L' { + bal++ + } else if c == 'R' { + bal-- + } + if bal == 0 { + count++ + } + } + return count +} diff --git a/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.java b/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.java new file mode 100644 index 00000000..41ef8cf3 --- /dev/null +++ b/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.java @@ -0,0 +1,18 @@ +class Solution { + public int balancedStringSplit(String s) { + int bal = 0; + int count = 0; + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (c == 'L') { + bal++; + } else if (c == 'R') { + bal--; + } + if (bal == 0) { + count++; + } + } + return count; + } +} diff --git a/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.kt b/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.kt new file mode 100644 index 00000000..30c95193 --- /dev/null +++ b/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.kt @@ -0,0 +1,17 @@ +class Solution { + fun balancedStringSplit(s: String): Int { + var bal = 0 + var count = 0 + for (c in s) { + if (c == 'L') { + bal++ + } else if (c == 'R') { + bal-- + } + if (bal == 0) { + count++ + } + } + return count + } +} diff --git a/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.py b/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.py new file mode 100644 index 00000000..bd322234 --- /dev/null +++ b/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.py @@ -0,0 +1,12 @@ +class Solution: + def balancedStringSplit(self, s: str) -> int: + Bal = 0 + count = 0 + for i in range(len(s)): + if s[i] == "L": + Bal += 1 + elif s[i] == "R": + Bal -= 1 + if Bal == 0: + count += 1 + return count diff --git a/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.py2 b/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.py2 new file mode 100644 index 00000000..80b0dc33 --- /dev/null +++ b/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def balancedStringSplit(self, s): + """ + :type s: str + :rtype: int + """ + Bal = 0 + count = 0 + for c in s: + if c == 'L': + Bal += 1 + elif c == 'R': + Bal -= 1 + if Bal == 0: + count += 1 + return count diff --git a/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.rb b/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.rb new file mode 100644 index 00000000..706eb709 --- /dev/null +++ b/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.rb @@ -0,0 +1,17 @@ +# @param {String} s +# @return {Integer} +def balanced_string_split(s) + bal = 0 + count = 0 + s.each_char do |c| + if c == 'L' + bal += 1 + elsif c == 'R' + bal -= 1 + end + if bal == 0 + count += 1 + end + end + count +end diff --git a/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.rs b/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.rs new file mode 100644 index 00000000..0f0cfef8 --- /dev/null +++ b/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.rs @@ -0,0 +1,17 @@ +impl Solution { + pub fn balanced_string_split(s: String) -> i32 { + let mut bal = 0; + let mut count = 0; + for c in s.chars() { + if c == 'L' { + bal += 1; + } else if c == 'R' { + bal -= 1; + } + if bal == 0 { + count += 1; + } + } + count + } +} diff --git a/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.swift b/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.swift new file mode 100644 index 00000000..929ad65a --- /dev/null +++ b/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.swift @@ -0,0 +1,17 @@ +class Solution { + func balancedStringSplit(_ s: String) -> Int { + var bal = 0 + var count = 0 + for c in s { + if c == "L" { + bal += 1 + } else if c == "R" { + bal -= 1 + } + if bal == 0 { + count += 1 + } + } + return count + } +} diff --git a/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.ts b/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.ts new file mode 100644 index 00000000..b2b3e2bc --- /dev/null +++ b/tests/1001-1500/1221. split-a-string-in-balanced-strings/sol.ts @@ -0,0 +1,16 @@ +function balancedStringSplit(s: string): number { + let bal = 0; + let count = 0; + for (let i = 0; i < s.length; i++) { + const c = s[i]; + if (c === "L") { + bal++; + } else if (c === "R") { + bal--; + } + if (bal === 0) { + count++; + } + } + return count; +} diff --git a/tests/1001-1500/1222. queens-that-can-attack-the-king/manifest.yaml b/tests/1001-1500/1222. queens-that-can-attack-the-king/manifest.yaml new file mode 100644 index 00000000..2d538c9f --- /dev/null +++ b/tests/1001-1500/1222. queens-that-can-attack-the-king/manifest.yaml @@ -0,0 +1,744 @@ +entry: + id: 1222 + title: "queens-that-can-attack-the-king" + params: + queens: + type: array + items: + type: array + items: + type: int + king: + type: array + items: + type: int + call: + cpp: "Solution().queensAttacktheKing({queens}, {king})" + rust: "Solution::queens_attackthe_king({queens}, {king})" + python3: "Solution().queensAttacktheKing({queens}, {king})" + python2: "Solution().queensAttacktheKing({queens}, {king})" + ruby: "queens_attackthe_king({queens}, {king})" + java: "new Solution().queensAttacktheKing({queens}, {king})" + csharp: "new Solution().QueensAttacktheKing({queens}, {king})" + kotlin: "Solution().queensAttacktheKing({queens}, {king})" + go: "queensAttacktheKing({queens}, {king})" + dart: "Solution().queensAttacktheKing({queens}, {king})" + swift: "Solution().queensAttacktheKing({queens}, {king})" + typescript: "queensAttacktheKing({queens}, {king})" + +judge: + type: "ignore_order" + +limits: + time_ms: 500 + memory_mb: 300 + +oracle: + python3: + call: "Checker().queensAttacktheKing(queens, king, {result})" + checker: | + class Checker: + def queensAttacktheKing(self, queens, king, result): + if not isinstance(result, list): + return False + actual = set() + for queen in result: + if (not isinstance(queen, list) or len(queen) != 2 or + any(type(coord) is not int or not 0 <= coord < 8 + for coord in queen)): + return False + position = tuple(queen) + if position in actual: + return False + actual.add(position) + if not actual.issubset({tuple(queen) for queen in queens}): + return False + occupied = {tuple(q) for q in queens} + expected = set() + directions = ((-1, 0), (1, 0), (0, -1), (0, 1), + (-1, -1), (-1, 1), (1, -1), (1, 1)) + for dr, dc in directions: + r, c = king + while True: + r += dr + c += dc + if not (0 <= r < 8 and 0 <= c < 8): + break + if (r, c) in occupied: + expected.add((r, c)) + break + return actual == expected + +seed: 1222 + +tests: + - name: "example_one" + in: + queens: + - [0, 1] + - [1, 0] + - [4, 0] + - [0, 4] + - [3, 3] + - [2, 4] + king: [0, 0] + - name: "example_two" + in: + queens: + - [0, 0] + - [1, 1] + - [2, 2] + - [3, 4] + - [3, 5] + - [4, 4] + - [4, 5] + king: [3, 3] + - name: "one_queen_same_row" + in: + queens: + - [4, 1] + king: [4, 4] + - name: "one_queen_not_aligned" + in: + queens: + - [1, 2] + king: [4, 4] + - name: "all_eight_adjacent" + in: + queens: + - [2, 3] + - [2, 4] + - [3, 2] + - [3, 4] + - [4, 2] + - [4, 3] + - [4, 4] + king: [3, 3] + - name: "blocked_rays" + in: + queens: + - [3, 4] + - [3, 5] + - [3, 6] + - [0, 0] + - [1, 1] + king: [3, 3] + - name: "corner_king" + in: + queens: + - [0, 7] + - [7, 0] + - [1, 1] + - [2, 2] + - [4, 4] + king: [0, 0] + - name: "opposite_corner_king" + in: + queens: + - [7, 0] + - [0, 7] + - [6, 6] + - [5, 5] + king: [7, 7] + - name: "center_four_rays" + in: + queens: + - [0, 3] + - [7, 3] + - [3, 0] + - [3, 7] + king: [3, 3] + - name: "center_diagonals" + in: + queens: + - [0, 0] + - [0, 6] + - [6, 0] + - [6, 6] + king: [3, 3] + - name: "nearest_wins_horizontal" + in: + queens: + - [4, 5] + - [4, 6] + - [4, 7] + - [4, 2] + king: [4, 4] + - name: "nearest_wins_diagonal" + in: + queens: + - [3, 3] + - [2, 2] + - [1, 1] + - [0, 0] + king: [4, 4] + - name: "vertical_edges" + in: + queens: + - [0, 2] + - [1, 2] + - [7, 2] + - [6, 2] + king: [4, 2] + - name: "no_attackers" + in: + queens: + - [0, 0] + - [1, 3] + - [2, 6] + - [5, 1] + - [7, 7] + king: [3, 3] + - name: "king_edge_row" + in: + queens: + - [0, 0] + - [0, 7] + - [1, 1] + - [2, 2] + - [1, 6] + king: [0, 3] + - name: "king_edge_column" + in: + queens: + - [0, 0] + - [7, 0] + - [1, 1] + - [6, 1] + - [4, 4] + king: [3, 0] + - name: "mixed_blocking" + in: + queens: + - [2, 4] + - [2, 6] + - [6, 2] + - [0, 0] + - [5, 5] + - [1, 3] + king: [2, 2] + - name: "all_same_column" + in: + queens: + - [0, 4] + - [1, 4] + - [2, 4] + - [3, 4] + - [5, 4] + - [6, 4] + - [7, 4] + king: [4, 4] + - name: "all_same_diagonal" + in: + queens: + - [0, 0] + - [1, 1] + - [2, 2] + - [4, 4] + - [5, 5] + - [6, 6] + - [7, 7] + king: [3, 3] + - name: "three_attackers" + in: + queens: + - [0, 3] + - [7, 3] + - [3, 0] + - [0, 0] + - [6, 6] + king: [3, 3] + - name: "far_only_attackers" + in: + queens: + - [0, 3] + - [7, 3] + - [3, 0] + - [3, 7] + - [0, 0] + - [7, 7] + king: [3, 3] + - name: "king_one_one" + in: + queens: + - [1, 0] + - [1, 7] + - [0, 1] + - [7, 1] + - [0, 0] + - [2, 2] + king: [1, 1] + - name: "king_six_six" + in: + queens: + - [6, 0] + - [6, 7] + - [0, 6] + - [7, 6] + - [5, 5] + - [7, 7] + king: [6, 6] + - name: "dense_board_center" + in: + queens: + - [0, 0] + - [0, 1] + - [0, 2] + - [0, 3] + - [1, 0] + - [1, 2] + - [2, 0] + - [2, 1] + - [4, 4] + - [5, 5] + - [6, 6] + - [7, 7] + king: [3, 3] + - name: "dense_board_corner" + in: + queens: + - [0, 1] + - [0, 2] + - [0, 3] + - [1, 0] + - [2, 0] + - [3, 0] + - [1, 1] + - [2, 2] + - [3, 3] + king: [0, 0] + - name: "diagonal_blocked_both" + in: + queens: + - [2, 2] + - [1, 1] + - [0, 0] + - [4, 4] + - [5, 5] + - [6, 6] + king: [3, 3] + - name: "horizontal_and_diagonal" + in: + queens: + - [3, 0] + - [3, 7] + - [0, 0] + - [6, 6] + - [1, 5] + king: [3, 3] + - name: "sparse_corner_rays" + in: + queens: + - [0, 4] + - [4, 0] + - [7, 7] + - [2, 2] + king: [0, 0] + - name: "king_two_two_sparse" + in: + queens: + - [2, 5] + - [5, 2] + - [0, 0] + - [4, 4] + - [1, 6] + king: [2, 2] + - name: "near_boundary_king" + in: + queens: + - [0, 1] + - [1, 0] + - [1, 2] + - [2, 1] + - [2, 2] + king: [0, 0] + - name: "opposite_rays_only" + in: + queens: + - [0, 4] + - [7, 4] + - [4, 0] + - [4, 7] + king: [4, 4] + - name: "all_directions_with_blockers" + in: + queens: + - [2, 3] + - [1, 3] + - [5, 3] + - [6, 3] + - [3, 2] + - [3, 1] + - [3, 5] + - [3, 6] + - [2, 2] + - [1, 1] + - [2, 4] + - [1, 5] + - [4, 2] + - [5, 1] + - [4, 4] + - [5, 5] + king: [3, 3] + - name: "full_ring_near_center" + in: + queens: + - [2, 3] + - [4, 3] + - [3, 2] + - [3, 4] + - [2, 2] + - [2, 4] + - [4, 2] + - [4, 4] + king: [3, 3] + - name: "king_at_seven_one" + in: + queens: + - [7, 0] + - [7, 2] + - [6, 1] + - [5, 1] + - [6, 0] + - [5, 3] + king: [7, 1] + - name: "single_far_diagonal" + in: + queens: + - [7, 7] + king: [0, 0] + - name: "maximum_density_top_left" + in: + queens: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [0, 5] + - [0, 6] + - [0, 7] + - [1, 0] + - [1, 1] + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [1, 6] + - [1, 7] + - [2, 0] + - [2, 1] + - [2, 2] + - [2, 3] + - [2, 4] + - [2, 5] + - [2, 6] + - [2, 7] + - [3, 0] + - [3, 1] + - [3, 2] + - [3, 3] + - [3, 4] + - [3, 5] + - [3, 6] + - [3, 7] + - [4, 0] + - [4, 1] + - [4, 2] + - [4, 3] + - [4, 4] + - [4, 5] + - [4, 6] + - [4, 7] + - [5, 0] + - [5, 1] + - [5, 2] + - [5, 3] + - [5, 4] + - [5, 5] + - [5, 6] + - [5, 7] + - [6, 0] + - [6, 1] + - [6, 2] + - [6, 3] + - [6, 4] + - [6, 5] + - [6, 6] + - [6, 7] + - [7, 0] + - [7, 1] + - [7, 2] + - [7, 3] + - [7, 4] + - [7, 5] + - [7, 6] + - [7, 7] + king: [0, 0] + - name: "maximum_density_bottom_right" + in: + queens: + - [0, 0] + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [0, 5] + - [0, 6] + - [0, 7] + - [1, 0] + - [1, 1] + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [1, 6] + - [1, 7] + - [2, 0] + - [2, 1] + - [2, 2] + - [2, 3] + - [2, 4] + - [2, 5] + - [2, 6] + - [2, 7] + - [3, 0] + - [3, 1] + - [3, 2] + - [3, 3] + - [3, 4] + - [3, 5] + - [3, 6] + - [3, 7] + - [4, 0] + - [4, 1] + - [4, 2] + - [4, 3] + - [4, 4] + - [4, 5] + - [4, 6] + - [4, 7] + - [5, 0] + - [5, 1] + - [5, 2] + - [5, 3] + - [5, 4] + - [5, 5] + - [5, 6] + - [5, 7] + - [6, 0] + - [6, 1] + - [6, 2] + - [6, 3] + - [6, 4] + - [6, 5] + - [6, 6] + - [6, 7] + - [7, 0] + - [7, 1] + - [7, 2] + - [7, 3] + - [7, 4] + - [7, 5] + - [7, 6] + king: [7, 7] + - name: "maximum_density_center" + in: + queens: + - [0, 0] + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [0, 5] + - [0, 6] + - [0, 7] + - [1, 0] + - [1, 1] + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [1, 6] + - [1, 7] + - [2, 0] + - [2, 1] + - [2, 2] + - [2, 3] + - [2, 4] + - [2, 5] + - [2, 6] + - [2, 7] + - [3, 0] + - [3, 1] + - [3, 2] + - [3, 4] + - [3, 5] + - [3, 6] + - [3, 7] + - [4, 0] + - [4, 1] + - [4, 2] + - [4, 3] + - [4, 4] + - [4, 5] + - [4, 6] + - [4, 7] + - [5, 0] + - [5, 1] + - [5, 2] + - [5, 3] + - [5, 4] + - [5, 5] + - [5, 6] + - [5, 7] + - [6, 0] + - [6, 1] + - [6, 2] + - [6, 3] + - [6, 4] + - [6, 5] + - [6, 6] + - [6, 7] + - [7, 0] + - [7, 1] + - [7, 2] + - [7, 3] + - [7, 4] + - [7, 5] + - [7, 6] + - [7, 7] + king: [3, 3] + - name: "maximum_density_top_right" + in: + queens: + - [0, 0] + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [0, 5] + - [0, 6] + - [1, 0] + - [1, 1] + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [1, 6] + - [1, 7] + - [2, 0] + - [2, 1] + - [2, 2] + - [2, 3] + - [2, 4] + - [2, 5] + - [2, 6] + - [2, 7] + - [3, 0] + - [3, 1] + - [3, 2] + - [3, 3] + - [3, 4] + - [3, 5] + - [3, 6] + - [3, 7] + - [4, 0] + - [4, 1] + - [4, 2] + - [4, 3] + - [4, 4] + - [4, 5] + - [4, 6] + - [4, 7] + - [5, 0] + - [5, 1] + - [5, 2] + - [5, 3] + - [5, 4] + - [5, 5] + - [5, 6] + - [5, 7] + - [6, 0] + - [6, 1] + - [6, 2] + - [6, 3] + - [6, 4] + - [6, 5] + - [6, 6] + - [6, 7] + - [7, 0] + - [7, 1] + - [7, 2] + - [7, 3] + - [7, 4] + - [7, 5] + - [7, 6] + - [7, 7] + king: [0, 7] + - name: "maximum_density_bottom_left" + in: + queens: + - [0, 0] + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [0, 5] + - [0, 6] + - [0, 7] + - [1, 0] + - [1, 1] + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [1, 6] + - [1, 7] + - [2, 0] + - [2, 1] + - [2, 2] + - [2, 3] + - [2, 4] + - [2, 5] + - [2, 6] + - [2, 7] + - [3, 0] + - [3, 1] + - [3, 2] + - [3, 3] + - [3, 4] + - [3, 5] + - [3, 6] + - [3, 7] + - [4, 0] + - [4, 1] + - [4, 2] + - [4, 3] + - [4, 4] + - [4, 5] + - [4, 6] + - [4, 7] + - [5, 0] + - [5, 1] + - [5, 2] + - [5, 3] + - [5, 4] + - [5, 5] + - [5, 6] + - [5, 7] + - [6, 0] + - [6, 1] + - [6, 2] + - [6, 3] + - [6, 4] + - [6, 5] + - [6, 6] + - [6, 7] + - [7, 1] + - [7, 2] + - [7, 3] + - [7, 4] + - [7, 5] + - [7, 6] + - [7, 7] + king: [7, 0] diff --git a/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.cpp b/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.cpp new file mode 100644 index 00000000..5bb86c29 --- /dev/null +++ b/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + vector> queensAttacktheKing(vector>& queens, vector& king) { + vector> board(8, vector(8, false)); + for (auto& q : queens) { + board[q[0]][q[1]] = true; + } + + vector> directions = { + {-1, 0}, {1, 0}, {0, 1}, {0, -1}, + {-1, -1}, {-1, 1}, {1, -1}, {1, 1} + }; + + vector> ans; + for (auto& [dr, dc] : directions) { + int r = king[0], c = king[1]; + while (r >= 0 && r < 8 && c >= 0 && c < 8) { + r += dr; + c += dc; + if (r < 0 || r >= 8 || c < 0 || c >= 8) break; + if (board[r][c]) { + ans.push_back({r, c}); + break; + } + } + } + return ans; + } +}; diff --git a/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.cs b/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.cs new file mode 100644 index 00000000..3298f3ab --- /dev/null +++ b/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.cs @@ -0,0 +1,28 @@ +public class Solution { + public IList> QueensAttacktheKing(int[][] queens, int[] king) { + bool[,] board = new bool[8, 8]; + foreach (var q in queens) { + board[q[0], q[1]] = true; + } + + int[][] directions = new int[][] { + new int[] {-1, 0}, new int[] {1, 0}, new int[] {0, 1}, new int[] {0, -1}, + new int[] {-1, -1}, new int[] {-1, 1}, new int[] {1, -1}, new int[] {1, 1} + }; + + IList> ans = new List>(); + foreach (var d in directions) { + int r = king[0], c = king[1]; + while (r >= 0 && r < 8 && c >= 0 && c < 8) { + r += d[0]; + c += d[1]; + if (r < 0 || r >= 8 || c < 0 || c >= 8) break; + if (board[r, c]) { + ans.Add(new List { r, c }); + break; + } + } + } + return ans; + } +} diff --git a/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.dart b/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.dart new file mode 100644 index 00000000..dd4b1170 --- /dev/null +++ b/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.dart @@ -0,0 +1,28 @@ +class Solution { + List> queensAttacktheKing(List> queens, List king) { + var board = List.generate(8, (_) => List.filled(8, false)); + for (var q in queens) { + board[q[0]][q[1]] = true; + } + + var directions = [ + [-1, 0], [1, 0], [0, 1], [0, -1], + [-1, -1], [-1, 1], [1, -1], [1, 1] + ]; + + var ans = >[]; + for (var d in directions) { + int r = king[0], c = king[1]; + while (r >= 0 && r < 8 && c >= 0 && c < 8) { + r += d[0]; + c += d[1]; + if (r < 0 || r >= 8 || c < 0 || c >= 8) break; + if (board[r][c]) { + ans.add([r, c]); + break; + } + } + } + return ans; + } +} diff --git a/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.go b/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.go new file mode 100644 index 00000000..4f73b82d --- /dev/null +++ b/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.go @@ -0,0 +1,31 @@ +func queensAttacktheKing(queens [][]int, king []int) [][]int { + board := make([][]bool, 8) + for i := range board { + board[i] = make([]bool, 8) + } + for _, q := range queens { + board[q[0]][q[1]] = true + } + + directions := [][]int{ + {-1, 0}, {1, 0}, {0, 1}, {0, -1}, + {-1, -1}, {-1, 1}, {1, -1}, {1, 1}, + } + + ans := [][]int{} + for _, d := range directions { + r, c := king[0], king[1] + for r >= 0 && r < 8 && c >= 0 && c < 8 { + r += d[0] + c += d[1] + if r < 0 || r >= 8 || c < 0 || c >= 8 { + break + } + if board[r][c] { + ans = append(ans, []int{r, c}) + break + } + } + } + return ans +} diff --git a/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.java b/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.java new file mode 100644 index 00000000..f1319a67 --- /dev/null +++ b/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.java @@ -0,0 +1,28 @@ +class Solution { + public List> queensAttacktheKing(int[][] queens, int[] king) { + boolean[][] board = new boolean[8][8]; + for (int[] q : queens) { + board[q[0]][q[1]] = true; + } + + int[][] directions = { + {-1, 0}, {1, 0}, {0, 1}, {0, -1}, + {-1, -1}, {-1, 1}, {1, -1}, {1, 1} + }; + + List> ans = new ArrayList<>(); + for (int[] d : directions) { + int r = king[0], c = king[1]; + while (r >= 0 && r < 8 && c >= 0 && c < 8) { + r += d[0]; + c += d[1]; + if (r < 0 || r >= 8 || c < 0 || c >= 8) break; + if (board[r][c]) { + ans.add(List.of(r, c)); + break; + } + } + } + return ans; + } +} diff --git a/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.kt b/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.kt new file mode 100644 index 00000000..307a3014 --- /dev/null +++ b/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.kt @@ -0,0 +1,29 @@ +class Solution { + fun queensAttacktheKing(queens: Array, king: IntArray): List> { + val board = Array(8) { BooleanArray(8) } + for (q in queens) { + board[q[0]][q[1]] = true + } + + val directions = listOf( + -1 to 0, 1 to 0, 0 to 1, 0 to -1, + -1 to -1, -1 to 1, 1 to -1, 1 to 1 + ) + + val ans = mutableListOf>() + for ((dr, dc) in directions) { + var r = king[0] + var c = king[1] + while (r in 0..7 && c in 0..7) { + r += dr + c += dc + if (r !in 0..7 || c !in 0..7) break + if (board[r][c]) { + ans.add(listOf(r, c)) + break + } + } + } + return ans + } +} diff --git a/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.py b/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.py new file mode 100644 index 00000000..c5a006a4 --- /dev/null +++ b/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.py @@ -0,0 +1,30 @@ +class Solution: + def queensAttacktheKing(self, queens, king): + board = [[False] * 8 for _ in range(8)] + for r, c in queens: + board[r][c] = True + + directions = [ + (-1, 0), + (1, 0), + (0, 1), + (0, -1), + (-1, -1), + (-1, 1), + (1, -1), + (1, 1), + ] + + ans = [] + for dr, dc in directions: + r, c = king + while 0 <= r < 8 and 0 <= c < 8: + r += dr + c += dc + if not (0 <= r < 8 and 0 <= c < 8): + break + if board[r][c]: + ans.append([r, c]) + break + + return ans diff --git a/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.py2 b/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.py2 new file mode 100644 index 00000000..04815f1a --- /dev/null +++ b/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.py2 @@ -0,0 +1,29 @@ +class Solution(object): + def queensAttacktheKing(self, queens, king): + """ + :type queens: List[List[int]] + :type king: List[int] + :rtype: List[List[int]] + """ + board = [[False] * 8 for _ in range(8)] + for r, c in queens: + board[r][c] = True + + directions = [ + (-1, 0), (1, 0), (0, 1), (0, -1), + (-1, -1), (-1, 1), (1, -1), (1, 1) + ] + + ans = [] + for dr, dc in directions: + r, c = king + while 0 <= r < 8 and 0 <= c < 8: + r += dr + c += dc + if not (0 <= r < 8 and 0 <= c < 8): + break + if board[r][c]: + ans.append([r, c]) + break + + return ans diff --git a/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.rb b/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.rb new file mode 100644 index 00000000..506abcc3 --- /dev/null +++ b/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.rb @@ -0,0 +1,30 @@ +# @param {Integer[][]} queens +# @param {Integer[]} king +# @return {Integer[][]} +def queens_attackthe_king(queens, king) + board = Array.new(8) { Array.new(8, false) } + queens.each do |r, c| + board[r][c] = true + end + + directions = [ + [-1, 0], [1, 0], [0, 1], [0, -1], + [-1, -1], [-1, 1], [1, -1], [1, 1] + ] + + ans = [] + directions.each do |dr, dc| + r, c = king + while r.between?(0, 7) && c.between?(0, 7) + r += dr + c += dc + break unless r.between?(0, 7) && c.between?(0, 7) + if board[r][c] + ans << [r, c] + break + end + end + end + + ans +end diff --git a/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.rs b/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.rs new file mode 100644 index 00000000..6fe2bc66 --- /dev/null +++ b/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.rs @@ -0,0 +1,31 @@ +impl Solution { + pub fn queens_attackthe_king(queens: Vec>, king: Vec) -> Vec> { + let mut board = [[false; 8]; 8]; + for q in queens { + board[q[0] as usize][q[1] as usize] = true; + } + + let directions = [ + (-1, 0), (1, 0), (0, 1), (0, -1), + (-1, -1), (-1, 1), (1, -1), (1, 1), + ]; + + let mut ans = Vec::new(); + for (dr, dc) in directions { + let mut r = king[0]; + let mut c = king[1]; + while r >= 0 && r < 8 && c >= 0 && c < 8 { + r += dr; + c += dc; + if r < 0 || r >= 8 || c < 0 || c >= 8 { + break; + } + if board[r as usize][c as usize] { + ans.push(vec![r, c]); + break; + } + } + } + ans + } +} diff --git a/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.swift b/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.swift new file mode 100644 index 00000000..aaa12d15 --- /dev/null +++ b/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.swift @@ -0,0 +1,28 @@ +class Solution { + func queensAttacktheKing(_ queens: [[Int]], _ king: [Int]) -> [[Int]] { + var board = Array(repeating: Array(repeating: false, count: 8), count: 8) + for q in queens { + board[q[0]][q[1]] = true + } + + let directions = [ + (-1, 0), (1, 0), (0, 1), (0, -1), + (-1, -1), (-1, 1), (1, -1), (1, 1) + ] + + var ans = [[Int]]() + for (dr, dc) in directions { + var r = king[0], c = king[1] + while r >= 0 && r < 8 && c >= 0 && c < 8 { + r += dr + c += dc + guard r >= 0 && r < 8 && c >= 0 && c < 8 else { break } + if board[r][c] { + ans.append([r, c]) + break + } + } + } + return ans + } +} diff --git a/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.ts b/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.ts new file mode 100644 index 00000000..94da235e --- /dev/null +++ b/tests/1001-1500/1222. queens-that-can-attack-the-king/sol.ts @@ -0,0 +1,35 @@ +function queensAttacktheKing(queens: number[][], king: number[]): number[][] { + const board: boolean[][] = Array.from({ length: 8 }, () => + Array(8).fill(false), + ); + for (const [r, c] of queens) { + board[r][c] = true; + } + + const directions: [number, number][] = [ + [-1, 0], + [1, 0], + [0, 1], + [0, -1], + [-1, -1], + [-1, 1], + [1, -1], + [1, 1], + ]; + + const ans: number[][] = []; + for (const [dr, dc] of directions) { + let r = king[0], + c = king[1]; + while (r >= 0 && r < 8 && c >= 0 && c < 8) { + r += dr; + c += dc; + if (r < 0 || r >= 8 || c < 0 || c >= 8) break; + if (board[r][c]) { + ans.push([r, c]); + break; + } + } + } + return ans; +} diff --git a/tests/1001-1500/1223. dice-roll-simulation/manifest.yaml b/tests/1001-1500/1223. dice-roll-simulation/manifest.yaml new file mode 100644 index 00000000..9a1bde59 --- /dev/null +++ b/tests/1001-1500/1223. dice-roll-simulation/manifest.yaml @@ -0,0 +1,299 @@ +entry: + id: 1223 + title: "dice-roll-simulation" + params: + n: + type: int + rollMax: + type: array + items: + type: int + call: + cpp: "Solution().dieSimulator({n}, {rollMax})" + rust: "Solution::die_simulator({n}, {rollMax})" + python3: "Solution().dieSimulator({n}, {rollMax})" + python2: "Solution().dieSimulator({n}, {rollMax})" + ruby: "die_simulator({n}, {rollMax})" + java: "new Solution().dieSimulator({n}, {rollMax})" + csharp: "new Solution().DieSimulator({n}, {rollMax})" + kotlin: "Solution().dieSimulator({n}, {rollMax})" + go: "dieSimulator({n}, {rollMax})" + dart: "Solution().dieSimulator({n}, {rollMax})" + swift: "Solution().dieSimulator({n}, {rollMax})" + typescript: "dieSimulator({n}, {rollMax})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().dieSimulator(n, rollMax, {result})" + checker: | + class Checker: + def dieSimulator(self, n, rollMax, result): + if not isinstance(n, int) or isinstance(n, bool) or n < 1 or n > 5000: + return False + if not isinstance(rollMax, list) or len(rollMax) != 6: + return False + if any(not isinstance(x, int) or isinstance(x, bool) or x < 1 or x > 15 for x in rollMax): + return False + if not isinstance(result, int) or isinstance(result, bool): + return False + mod = 1000000007 + last = [[0] * (limit + 1) for limit in rollMax] + for face, limit in enumerate(rollMax): + last[face][1] = 1 + for _ in range(1, n): + total = sum(sum(row) for row in last) % mod + nxt = [[0] * (limit + 1) for limit in rollMax] + for face, limit in enumerate(rollMax): + other = (total - sum(last[face])) % mod + nxt[face][1] = other + for run in range(2, limit + 1): + nxt[face][run] = last[face][run - 1] + last = nxt + expected = sum(sum(row) for row in last) % mod + return result == expected + +seed: 1223 + +tests: + - name: "minimum n all minimum limits" + in: + n: 1 + rollMax: [1, 1, 1, 1, 1, 1] + out: 6 + - name: "minimum n all maximum limits" + in: + n: 1 + rollMax: [15, 15, 15, 15, 15, 15] + out: 6 + - name: "example one" + in: + n: 2 + rollMax: [1, 1, 2, 2, 2, 3] + out: 34 + - name: "example two" + in: + n: 2 + rollMax: [1, 1, 1, 1, 1, 1] + out: 30 + - name: "example three" + in: + n: 3 + rollMax: [1, 1, 1, 2, 2, 3] + out: 181 + - name: "large random limits" + seed: 122301 + in: + n: + gen: "int" + min: 4000 + max: 4500 + rollMax: + gen: "array" + len: 6 + of: + gen: "int" + min: 1 + max: 15 + distinct: false + sorted: false + elemType: "int" + - name: "three rolls pairs allowed" + in: + n: 3 + rollMax: [2, 2, 2, 2, 2, 2] + out: 210 + - name: "near maximum random limits" + seed: 122302 + in: + n: + gen: "int" + min: 4900 + max: 5000 + rollMax: + gen: "array" + len: 6 + of: + gen: "int" + min: 1 + max: 15 + distinct: false + sorted: false + elemType: "int" + - name: "four rolls pairs allowed" + in: + n: 4 + rollMax: [2, 2, 2, 2, 2, 2] + out: 1230 + - name: "increasing limits short" + in: + n: 5 + rollMax: [1, 2, 3, 4, 5, 6] + out: 6919 + - name: "one permissive face" + in: + n: 6 + rollMax: [1, 1, 1, 1, 1, 15] + out: 22541 + - name: "increasing limits seven" + in: + n: 7 + rollMax: [2, 3, 4, 5, 6, 7] + out: 273463 + - name: "alternating strict limits" + in: + n: 8 + rollMax: [1, 2, 1, 2, 1, 2] + out: 866886 + - name: "large strict limits" + seed: 122303 + in: + n: + gen: "int" + min: 4000 + max: 5000 + rollMax: [1, 1, 1, 1, 1, 1] + - name: "increasing limits twelve" + in: + n: 12 + rollMax: [1, 2, 3, 4, 5, 6] + out: 572213028 + - name: "uniform pairs fifteen" + in: + n: 15 + rollMax: [2, 2, 2, 2, 2, 2] + out: 360778870 + - name: "mixed strict limits twenty" + in: + n: 20 + rollMax: [1, 1, 2, 2, 3, 3] + out: 386639626 + - name: "moderate increasing limits" + in: + n: 25 + rollMax: [3, 4, 5, 6, 7, 8] + out: 227445080 + - name: "increasing limits thirty" + in: + n: 30 + rollMax: [1, 2, 3, 4, 5, 6] + out: 509437858 + - name: "example limits forty" + in: + n: 40 + rollMax: [1, 1, 1, 2, 2, 3] + out: 974034519 + - name: "alternating permissive limits" + in: + n: 50 + rollMax: [15, 1, 15, 1, 15, 1] + out: 608766176 + - name: "prime-like limits" + in: + n: 75 + rollMax: [2, 3, 5, 7, 11, 13] + out: 262141686 + - name: "large permissive limits" + seed: 122304 + in: + n: + gen: "int" + min: 4500 + max: 5000 + rollMax: [15, 15, 15, 15, 15, 15] + - name: "large asymmetric limits" + seed: 122305 + in: + n: + gen: "int" + min: 4500 + max: 5000 + rollMax: [1, 2, 3, 4, 5, 15] + - name: "maximum n mixed limits" + seed: 122306 + in: + n: + gen: "int" + min: 5000 + max: 5000 + rollMax: + gen: "array" + len: 6 + of: + gen: "int" + min: 1 + max: 15 + distinct: false + sorted: false + elemType: "int" + - name: "hundred unconstrained" + in: + n: 100 + rollMax: [15, 15, 15, 15, 15, 15] + out: 302110769 + - name: "two hundred fifty mixed" + in: + n: 250 + rollMax: [1, 2, 3, 4, 5, 6] + out: 977171803 + - name: "five hundred mixed strict" + in: + n: 500 + rollMax: [1, 1, 2, 2, 3, 3] + out: 101616524 + - name: "thousand no repeats" + in: + n: 1000 + rollMax: [1, 1, 1, 1, 1, 1] + out: 203456550 + - name: "fifteen hundred increasing" + in: + n: 1500 + rollMax: [2, 3, 4, 5, 6, 7] + out: 123669470 + - name: "two thousand unconstrained limits" + in: + n: 2000 + rollMax: [15, 15, 15, 15, 15, 15] + out: 947231106 + - name: "three thousand increasing" + in: + n: 3000 + rollMax: [1, 2, 3, 4, 5, 6] + out: 581026725 + - name: "four thousand one permissive" + in: + n: 4000 + rollMax: [1, 1, 1, 1, 1, 15] + out: 386000099 + - name: "maximum n mixed strict" + in: + n: 5000 + rollMax: [1, 1, 2, 2, 3, 3] + out: 225223927 + - name: "maximum n asymmetric" + in: + n: 5000 + rollMax: [15, 1, 2, 3, 4, 5] + out: 241209934 + - name: "alternating extremes" + in: + n: 17 + rollMax: [1, 15, 2, 14, 3, 13] + out: 152293170 + - name: "uniform fours" + in: + n: 64 + rollMax: [4, 4, 4, 4, 4, 4] + out: 193787109 + - name: "reversed limits" + in: + n: 321 + rollMax: [6, 5, 4, 3, 2, 1] + out: 895489651 diff --git a/tests/1001-1500/1223. dice-roll-simulation/sol.cpp b/tests/1001-1500/1223. dice-roll-simulation/sol.cpp new file mode 100644 index 00000000..c5a2f524 --- /dev/null +++ b/tests/1001-1500/1223. dice-roll-simulation/sol.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + int dieSimulator(int n, vector& rollMax) { + const int MOD = 1e9 + 7; + int faces = 6; + + vector> f(n, vector(faces, 0)); + vector s(n, 0); + + for (int j = 0; j < faces; j++) { + f[0][j] = 1; + } + s[0] = faces; + + for (int i = 1; i < n; i++) { + for (int j = 0; j < faces; j++) { + int maxRepeat = rollMax[j]; + long long res = s[i - 1]; + + if (i > maxRepeat) { + res -= (s[i - maxRepeat - 1] - f[i - maxRepeat - 1][j]); + } else if (i == maxRepeat) { + res -= 1; + } + + f[i][j] = ((res % MOD) + MOD) % MOD; + } + + long long sum = 0; + for (int j = 0; j < faces; j++) { + sum = (sum + f[i][j]) % MOD; + } + s[i] = sum; + } + + return s[n - 1]; + } +}; diff --git a/tests/1001-1500/1223. dice-roll-simulation/sol.cs b/tests/1001-1500/1223. dice-roll-simulation/sol.cs new file mode 100644 index 00000000..cedd23f0 --- /dev/null +++ b/tests/1001-1500/1223. dice-roll-simulation/sol.cs @@ -0,0 +1,37 @@ +public class Solution { + public int DieSimulator(int n, int[] rollMax) { + const int MOD = 1_000_000_007; + int faces = 6; + + long[,] f = new long[n, faces]; + long[] s = new long[n]; + + for (int j = 0; j < faces; j++) { + f[0, j] = 1; + } + s[0] = faces; + + for (int i = 1; i < n; i++) { + for (int j = 0; j < faces; j++) { + int maxRepeat = rollMax[j]; + long res = s[i - 1]; + + if (i > maxRepeat) { + res -= (s[i - maxRepeat - 1] - f[i - maxRepeat - 1, j]); + } else if (i == maxRepeat) { + res -= 1; + } + + f[i, j] = ((res % MOD) + MOD) % MOD; + } + + long sum = 0; + for (int j = 0; j < faces; j++) { + sum = (sum + f[i, j]) % MOD; + } + s[i] = sum; + } + + return (int)s[n - 1]; + } +} diff --git a/tests/1001-1500/1223. dice-roll-simulation/sol.dart b/tests/1001-1500/1223. dice-roll-simulation/sol.dart new file mode 100644 index 00000000..8fff8e83 --- /dev/null +++ b/tests/1001-1500/1223. dice-roll-simulation/sol.dart @@ -0,0 +1,37 @@ +class Solution { + int dieSimulator(int n, List rollMax) { + const int MOD = 1000000007; + int faces = 6; + + List> f = List.generate(n, (_) => List.filled(faces, 0)); + List s = List.filled(n, 0); + + for (int j = 0; j < faces; j++) { + f[0][j] = 1; + } + s[0] = faces; + + for (int i = 1; i < n; i++) { + for (int j = 0; j < faces; j++) { + int maxRepeat = rollMax[j]; + int res = s[i - 1]; + + if (i > maxRepeat) { + res -= (s[i - maxRepeat - 1] - f[i - maxRepeat - 1][j]); + } else if (i == maxRepeat) { + res -= 1; + } + + f[i][j] = ((res % MOD) + MOD) % MOD; + } + + int sum = 0; + for (int j = 0; j < faces; j++) { + sum = (sum + f[i][j]) % MOD; + } + s[i] = sum; + } + + return s[n - 1]; + } +} diff --git a/tests/1001-1500/1223. dice-roll-simulation/sol.go b/tests/1001-1500/1223. dice-roll-simulation/sol.go new file mode 100644 index 00000000..cb404d47 --- /dev/null +++ b/tests/1001-1500/1223. dice-roll-simulation/sol.go @@ -0,0 +1,38 @@ +func dieSimulator(n int, rollMax []int) int { + const MOD = 1_000_000_007 + faces := 6 + + f := make([][]int, n) + for i := range f { + f[i] = make([]int, faces) + } + s := make([]int, n) + + for j := 0; j < faces; j++ { + f[0][j] = 1 + } + s[0] = faces + + for i := 1; i < n; i++ { + for j := 0; j < faces; j++ { + maxRepeat := rollMax[j] + res := s[i-1] + + if i > maxRepeat { + res -= (s[i-maxRepeat-1] - f[i-maxRepeat-1][j]) + } else if i == maxRepeat { + res -= 1 + } + + f[i][j] = ((res % MOD) + MOD) % MOD + } + + sum := 0 + for j := 0; j < faces; j++ { + sum = (sum + f[i][j]) % MOD + } + s[i] = sum + } + + return s[n-1] +} diff --git a/tests/1001-1500/1223. dice-roll-simulation/sol.java b/tests/1001-1500/1223. dice-roll-simulation/sol.java new file mode 100644 index 00000000..de77a6d9 --- /dev/null +++ b/tests/1001-1500/1223. dice-roll-simulation/sol.java @@ -0,0 +1,37 @@ +class Solution { + public int dieSimulator(int n, int[] rollMax) { + final int MOD = 1_000_000_007; + int faces = 6; + + long[][] f = new long[n][faces]; + long[] s = new long[n]; + + for (int j = 0; j < faces; j++) { + f[0][j] = 1; + } + s[0] = faces; + + for (int i = 1; i < n; i++) { + for (int j = 0; j < faces; j++) { + int maxRepeat = rollMax[j]; + long res = s[i - 1]; + + if (i > maxRepeat) { + res -= (s[i - maxRepeat - 1] - f[i - maxRepeat - 1][j]); + } else if (i == maxRepeat) { + res -= 1; + } + + f[i][j] = ((res % MOD) + MOD) % MOD; + } + + long sum = 0; + for (int j = 0; j < faces; j++) { + sum = (sum + f[i][j]) % MOD; + } + s[i] = sum; + } + + return (int) s[n - 1]; + } +} diff --git a/tests/1001-1500/1223. dice-roll-simulation/sol.kt b/tests/1001-1500/1223. dice-roll-simulation/sol.kt new file mode 100644 index 00000000..bd8a714f --- /dev/null +++ b/tests/1001-1500/1223. dice-roll-simulation/sol.kt @@ -0,0 +1,36 @@ +class Solution { + fun dieSimulator(n: Int, rollMax: IntArray): Int { + val MOD = 1_000_000_007 + val faces = 6 + + val f = Array(n) { LongArray(faces) } + val s = LongArray(n) + + for (j in 0 until faces) { + f[0][j] = 1 + } + s[0] = faces.toLong() + + for (i in 1 until n) { + for (j in 0 until faces) { + val maxRepeat = rollMax[j] + var res = s[i - 1] + + if (i > maxRepeat) { + res -= (s[i - maxRepeat - 1] - f[i - maxRepeat - 1][j]) + } else if (i == maxRepeat) { + res -= 1 + } + + f[i][j] = ((res % MOD) + MOD) % MOD + } + var sum = 0L + for (j in 0 until faces) { + sum = (sum + f[i][j]) % MOD + } + s[i] = sum + } + + return s[n - 1].toInt() + } +} diff --git a/tests/1001-1500/1223. dice-roll-simulation/sol.py b/tests/1001-1500/1223. dice-roll-simulation/sol.py new file mode 100644 index 00000000..efe9b15a --- /dev/null +++ b/tests/1001-1500/1223. dice-roll-simulation/sol.py @@ -0,0 +1,37 @@ +from typing import List + + +class Solution: + def dieSimulator(self, n: int, rollMax: List[int]) -> int: + MOD = 10**9 + 7 + faces = 6 + + # f[i][j] = number of valid sequences of length i+1 ending with face j + f = [[0] * faces for _ in range(n)] + s = [0] * n # s[i] = total number of valid sequences of length i+1 + + # Base case: 1 roll → one way for each face + for j in range(faces): + f[0][j] = 1 + s[0] = faces + + for i in range(1, n): + for j in range(faces): # current face + max_repeat = rollMax[j] + + res = s[i - 1] # total ways to extend sequences of length i + + if i > max_repeat: + # Remove sequences where appending j would cause j to appear more than allowed + # s[i - max_repeat - 1] = total sequences of length i - max_repeat + # f[i - max_repeat - 1][j] = those that already ended in j + res -= s[i - max_repeat - 1] - f[i - max_repeat - 1][j] + elif i == max_repeat: + # Prevent the one sequence where all i+1 rolls are j + res -= 1 + + f[i][j] = res % MOD + + s[i] = sum(f[i]) % MOD + + return s[n - 1] diff --git a/tests/1001-1500/1223. dice-roll-simulation/sol.py2 b/tests/1001-1500/1223. dice-roll-simulation/sol.py2 new file mode 100644 index 00000000..b801e135 --- /dev/null +++ b/tests/1001-1500/1223. dice-roll-simulation/sol.py2 @@ -0,0 +1,32 @@ +class Solution(object): + def dieSimulator(self, n, rollMax): + """ + :type n: int + :type rollMax: List[int] + :rtype: int + """ + MOD = 10**9 + 7 + faces = 6 + + f = [[0] * faces for _ in range(n)] + s = [0] * n + + for j in range(faces): + f[0][j] = 1 + s[0] = faces + + for i in range(1, n): + for j in range(faces): + max_repeat = rollMax[j] + res = s[i - 1] + + if i > max_repeat: + res -= s[i - max_repeat - 1] - f[i - max_repeat - 1][j] + elif i == max_repeat: + res -= 1 + + f[i][j] = res % MOD + + s[i] = sum(f[i]) % MOD + + return s[n - 1] diff --git a/tests/1001-1500/1223. dice-roll-simulation/sol.rb b/tests/1001-1500/1223. dice-roll-simulation/sol.rb new file mode 100644 index 00000000..2ec1ff09 --- /dev/null +++ b/tests/1001-1500/1223. dice-roll-simulation/sol.rb @@ -0,0 +1,31 @@ +# @param {Integer} n +# @param {Integer[]} roll_max +# @return {Integer} +def die_simulator(n, roll_max) + mod = 10**9 + 7 + faces = 6 + + f = Array.new(n) { Array.new(faces, 0) } + s = Array.new(n, 0) + + faces.times { |j| f[0][j] = 1 } + s[0] = faces + + (1...n).each do |i| + faces.times do |j| + max_repeat = roll_max[j] + res = s[i - 1] + + if i > max_repeat + res -= s[i - max_repeat - 1] - f[i - max_repeat - 1][j] + elsif i == max_repeat + res -= 1 + end + + f[i][j] = res % mod + end + s[i] = f[i].sum % mod + end + + s[n - 1] +end diff --git a/tests/1001-1500/1223. dice-roll-simulation/sol.rs b/tests/1001-1500/1223. dice-roll-simulation/sol.rs new file mode 100644 index 00000000..fa3df47f --- /dev/null +++ b/tests/1001-1500/1223. dice-roll-simulation/sol.rs @@ -0,0 +1,38 @@ +impl Solution { + pub fn die_simulator(n: i32, roll_max: Vec) -> i32 { + const MOD: i64 = 1_000_000_007; + let faces = 6; + let n = n as usize; + + let mut f = vec![vec![0i64; faces]; n]; + let mut s = vec![0i64; n]; + + for j in 0..faces { + f[0][j] = 1; + } + s[0] = faces as i64; + + for i in 1..n { + for j in 0..faces { + let max_repeat = roll_max[j] as usize; + let mut res = s[i - 1]; + + if i > max_repeat { + res -= s[i - max_repeat - 1] - f[i - max_repeat - 1][j]; + } else if i == max_repeat { + res -= 1; + } + + f[i][j] = ((res % MOD) + MOD) % MOD; + } + + let mut sum: i64 = 0; + for j in 0..faces { + sum = (sum + f[i][j]) % MOD; + } + s[i] = sum; + } + + s[n - 1] as i32 + } +} diff --git a/tests/1001-1500/1223. dice-roll-simulation/sol.swift b/tests/1001-1500/1223. dice-roll-simulation/sol.swift new file mode 100644 index 00000000..ed0089bd --- /dev/null +++ b/tests/1001-1500/1223. dice-roll-simulation/sol.swift @@ -0,0 +1,37 @@ +class Solution { + func dieSimulator(_ n: Int, _ rollMax: [Int]) -> Int { + let MOD = 1_000_000_007 + let faces = 6 + + var f = Array(repeating: Array(repeating: 0, count: faces), count: n) + var s = Array(repeating: 0, count: n) + + for j in 0.. maxRepeat { + res -= (s[i - maxRepeat - 1] - f[i - maxRepeat - 1][j]) + } else if i == maxRepeat { + res -= 1 + } + + f[i][j] = ((res % MOD) + MOD) % MOD + } + + var sum = 0 + for j in 0.. Array(faces).fill(0)); + const s: number[] = Array(n).fill(0); + + for (let j = 0; j < faces; j++) { + f[0][j] = 1; + } + s[0] = faces; + + for (let i = 1; i < n; i++) { + for (let j = 0; j < faces; j++) { + const maxRepeat = rollMax[j]; + let res = s[i - 1]; + + if (i > maxRepeat) { + res -= s[i - maxRepeat - 1] - f[i - maxRepeat - 1][j]; + } else if (i === maxRepeat) { + res -= 1; + } + + f[i][j] = ((res % MOD) + MOD) % MOD; + } + + let sum = 0; + for (let j = 0; j < faces; j++) { + sum = (sum + f[i][j]) % MOD; + } + s[i] = sum; + } + + return s[n - 1]; +} diff --git a/tests/1001-1500/1224. maximum-equal-frequency/manifest.yaml b/tests/1001-1500/1224. maximum-equal-frequency/manifest.yaml new file mode 100644 index 00000000..ff1a290d --- /dev/null +++ b/tests/1001-1500/1224. maximum-equal-frequency/manifest.yaml @@ -0,0 +1,276 @@ +entry: + id: 1224 + title: "maximum-equal-frequency" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().maxEqualFreq({nums})" + rust: "Solution::max_equal_freq({nums})" + python3: "Solution().maxEqualFreq({nums})" + python2: "Solution().maxEqualFreq({nums})" + ruby: "max_equal_freq({nums})" + java: "new Solution().maxEqualFreq({nums})" + csharp: "new Solution().MaxEqualFreq({nums})" + kotlin: "Solution().maxEqualFreq({nums})" + go: "maxEqualFreq({nums})" + dart: "Solution().maxEqualFreq({nums})" + swift: "Solution().maxEqualFreq({nums})" + typescript: "maxEqualFreq({nums})" + +judge: + type: "exact" + +limits: + time_ms: 700 + memory_mb: 300 + +oracle: + python3: + call: "Checker().maxEqualFreq(nums, {result})" + checker: | + from collections import defaultdict + + class Checker: + def maxEqualFreq(self, nums, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + + counts = defaultdict(int) + frequency_counts = defaultdict(int) + best = 0 + for length, value in enumerate(nums, 1): + old = counts[value] + if old: + frequency_counts[old] -= 1 + if frequency_counts[old] == 0: + del frequency_counts[old] + counts[value] = old + 1 + current = old + 1 + frequency_counts[current] += 1 + + if len(frequency_counts) == 1: + only_frequency, value_count = next(iter(frequency_counts.items())) + if only_frequency == 1 or value_count == 1: + best = length + elif len(frequency_counts) == 2: + low, high = sorted(frequency_counts) + if (low == 1 and frequency_counts[low] == 1) or ( + high == low + 1 and frequency_counts[high] == 1 + ): + best = length + return result == best + +seed: 122400 + +tests: + - name: "example_one" + in: + nums: [2, 2, 1, 1, 5, 3, 3, 5] + out: 7 + - name: "example_two" + in: + nums: [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5] + out: 13 + - name: "two_distinct" + in: + nums: [1, 100000] + out: 2 + - name: "two_equal" + in: + nums: [100000, 100000] + out: 2 + - name: "three_distinct" + in: + nums: [1, 50000, 100000] + out: 3 + - name: "pair_then_new_value" + in: + nums: [1, 1, 2] + out: 3 + - name: "new_value_then_pair" + in: + nums: [1, 2, 2] + out: 3 + - name: "three_equal" + in: + nums: [7, 7, 7] + out: 3 + - name: "triple_and_single" + in: + nums: [1, 1, 1, 2] + out: 4 + - name: "two_complete_pairs" + in: + nums: [1, 1, 2, 2] + out: 3 + - name: "interleaved_pairs" + in: + nums: [1, 2, 1, 2] + out: 3 + - name: "one_double_among_singletons" + in: + nums: [1, 2, 3, 1] + out: 4 + - name: "three_equal_groups_plus_single" + in: + nums: [2, 2, 2, 1, 1, 1, 3] + out: 7 + - name: "three_pairs_plus_single" + in: + nums: [1, 1, 2, 2, 3, 3, 4] + out: 7 + - name: "permuted_three_pairs" + in: + nums: [1, 2, 3, 2, 1, 3] + out: 5 + - name: "descending_pairs_plus_single" + in: + nums: [5, 5, 4, 4, 3, 3, 2] + out: 7 + - name: "four_pairs_plus_single" + in: + nums: [1, 1, 2, 2, 3, 3, 4, 4, 5] + out: 9 + - name: "increasing_frequency_staircase" + in: + nums: [1, 2, 2, 3, 3, 3] + out: 5 + - name: "four_and_three" + in: + nums: [1, 1, 1, 1, 2, 2, 2] + out: 7 + - name: "four_balanced_pairs" + in: + nums: [1, 2, 3, 4, 1, 2, 3, 4] + out: 7 + - name: "three_two_one_distribution" + in: + nums: [7, 7, 7, 8, 8, 9] + out: 5 + - name: "three_two_one_low_values" + in: + nums: [1, 1, 1, 2, 2, 3] + out: 5 + - name: "majority_interleaved" + in: + nums: [1, 2, 1, 2, 1, 3] + out: 5 + - name: "four_pairs_with_two_singletons" + in: + nums: [1, 1, 2, 2, 3, 3, 4, 5] + out: 7 + - name: "five_balanced_pairs" + in: + nums: [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] + out: 9 + - name: "four_pairs_no_removable_final" + in: + nums: [2, 2, 1, 1, 3, 3, 4, 4] + out: 7 + - name: "three_balanced_triples" + in: + nums: [1, 2, 3, 1, 2, 3, 1, 2, 3] + out: 7 + - name: "five_and_four" + in: + nums: [1, 1, 1, 1, 1, 2, 2, 2, 2] + out: 9 + - name: "four_three_two_one" + in: + nums: [1, 2, 2, 2, 3, 3, 3, 4, 4] + out: 7 + - name: "mixed_triples" + in: + nums: [1, 1, 2, 3, 3, 4, 4, 4] + out: 7 + - name: "late_new_value" + in: + nums: [1, 1, 2, 3, 3, 4, 4, 4, 5] + out: 7 + - name: "all_distinct_eight" + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8] + out: 8 + - name: "one_frequency_outlier_at_end" + in: + nums: [9, 9, 8, 8, 7, 7, 6, 6, 6] + out: 9 + - name: "high_frequency_outlier_at_end" + in: + nums: [1, 2, 3, 4, 1, 2, 3, 4, 1] + out: 9 + - name: "generated_dense_50k" + seed: 122401 + in: + nums: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 25 + distinct: false + sorted: false + - name: "generated_wide_65k" + seed: 122402 + in: + nums: + gen: "array" + len: 65000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + - name: "generated_medium_alphabet_80k" + seed: 122403 + in: + nums: + gen: "array" + len: 80000 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + sorted: false + - name: "generated_near_max_90k" + seed: 122404 + in: + nums: + gen: "array" + len: 90000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + - name: "generated_near_max_99999" + seed: 122405 + in: + nums: + gen: "array" + len: 99999 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + - name: "generated_maximum_100k" + seed: 122406 + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false diff --git a/tests/1001-1500/1224. maximum-equal-frequency/sol.cpp b/tests/1001-1500/1224. maximum-equal-frequency/sol.cpp new file mode 100644 index 00000000..53ca34c7 --- /dev/null +++ b/tests/1001-1500/1224. maximum-equal-frequency/sol.cpp @@ -0,0 +1,43 @@ +class Solution { +public: + int maxEqualFreq(vector& nums) { + unordered_map counts; + unordered_map frequencyCounts; + int best = 0; + + for (int i = 0; i < nums.size(); i++) { + int value = nums[i]; + int index = i + 1; + int previous = counts[value]; + if (previous > 0) { + frequencyCounts[previous]--; + if (frequencyCounts[previous] == 0) { + frequencyCounts.erase(previous); + } + } + counts[value] = previous + 1; + int frequency = previous + 1; + frequencyCounts[frequency]++; + + if (frequencyCounts.size() == 1) { + auto it = frequencyCounts.begin(); + int onlyFrequency = it->first; + int valueCount = it->second; + if (onlyFrequency == 1 || valueCount == 1) { + best = index; + } + } else if (frequencyCounts.size() == 2) { + auto it = frequencyCounts.begin(); + int first = it->first; + int second = (++it)->first; + int low = min(first, second); + int high = max(first, second); + if ((low == 1 && frequencyCounts[low] == 1) || (high == low + 1 && frequencyCounts[high] == 1)) { + best = index; + } + } + } + + return best; + } +}; diff --git a/tests/1001-1500/1224. maximum-equal-frequency/sol.cs b/tests/1001-1500/1224. maximum-equal-frequency/sol.cs new file mode 100644 index 00000000..e17340d3 --- /dev/null +++ b/tests/1001-1500/1224. maximum-equal-frequency/sol.cs @@ -0,0 +1,40 @@ +public class Solution { + public int MaxEqualFreq(int[] nums) { + var counts = new Dictionary(); + var frequencyCounts = new Dictionary(); + int best = 0; + + for (int i = 0; i < nums.Length; i++) { + int value = nums[i]; + int index = i + 1; + int previous = counts.GetValueOrDefault(value, 0); + if (previous > 0) { + frequencyCounts[previous]--; + if (frequencyCounts[previous] == 0) { + frequencyCounts.Remove(previous); + } + } + counts[value] = previous + 1; + int frequency = previous + 1; + frequencyCounts[frequency] = frequencyCounts.GetValueOrDefault(frequency, 0) + 1; + + if (frequencyCounts.Count == 1) { + var entry = frequencyCounts.First(); + int onlyFrequency = entry.Key; + int valueCount = entry.Value; + if (onlyFrequency == 1 || valueCount == 1) { + best = index; + } + } else if (frequencyCounts.Count == 2) { + var keys = frequencyCounts.Keys.OrderBy(k => k).ToArray(); + int low = keys[0]; + int high = keys[1]; + if ((low == 1 && frequencyCounts[low] == 1) || (high == low + 1 && frequencyCounts[high] == 1)) { + best = index; + } + } + } + + return best; + } +} diff --git a/tests/1001-1500/1224. maximum-equal-frequency/sol.dart b/tests/1001-1500/1224. maximum-equal-frequency/sol.dart new file mode 100644 index 00000000..92e08f52 --- /dev/null +++ b/tests/1001-1500/1224. maximum-equal-frequency/sol.dart @@ -0,0 +1,40 @@ +class Solution { + int maxEqualFreq(List nums) { + var counts = {}; + var frequencyCounts = {}; + int best = 0; + + for (int i = 0; i < nums.length; i++) { + int value = nums[i]; + int index = i + 1; + int previous = counts[value] ?? 0; + if (previous > 0) { + frequencyCounts[previous] = frequencyCounts[previous]! - 1; + if (frequencyCounts[previous] == 0) { + frequencyCounts.remove(previous); + } + } + counts[value] = previous + 1; + int frequency = previous + 1; + frequencyCounts[frequency] = (frequencyCounts[frequency] ?? 0) + 1; + + if (frequencyCounts.length == 1) { + var entry = frequencyCounts.entries.first; + int onlyFrequency = entry.key; + int valueCount = entry.value; + if (onlyFrequency == 1 || valueCount == 1) { + best = index; + } + } else if (frequencyCounts.length == 2) { + var keys = frequencyCounts.keys.toList()..sort(); + int low = keys[0]; + int high = keys[1]; + if ((low == 1 && frequencyCounts[low] == 1) || (high == low + 1 && frequencyCounts[high] == 1)) { + best = index; + } + } + } + + return best; + } +} diff --git a/tests/1001-1500/1224. maximum-equal-frequency/sol.go b/tests/1001-1500/1224. maximum-equal-frequency/sol.go new file mode 100644 index 00000000..d0705eb6 --- /dev/null +++ b/tests/1001-1500/1224. maximum-equal-frequency/sol.go @@ -0,0 +1,42 @@ +func maxEqualFreq(nums []int) int { + counts := make(map[int]int) + frequencyCounts := make(map[int]int) + best := 0 + + for i, value := range nums { + index := i + 1 + previous := counts[value] + if previous > 0 { + frequencyCounts[previous]-- + if frequencyCounts[previous] == 0 { + delete(frequencyCounts, previous) + } + } + counts[value] = previous + 1 + frequency := previous + 1 + frequencyCounts[frequency]++ + + if len(frequencyCounts) == 1 { + for onlyFrequency, valueCount := range frequencyCounts { + if onlyFrequency == 1 || valueCount == 1 { + best = index + } + break + } + } else if len(frequencyCounts) == 2 { + keys := make([]int, 0, 2) + for k := range frequencyCounts { + keys = append(keys, k) + } + low, high := keys[0], keys[1] + if low > high { + low, high = high, low + } + if (low == 1 && frequencyCounts[low] == 1) || (high == low+1 && frequencyCounts[high] == 1) { + best = index + } + } + } + + return best +} diff --git a/tests/1001-1500/1224. maximum-equal-frequency/sol.java b/tests/1001-1500/1224. maximum-equal-frequency/sol.java new file mode 100644 index 00000000..55d18689 --- /dev/null +++ b/tests/1001-1500/1224. maximum-equal-frequency/sol.java @@ -0,0 +1,41 @@ +class Solution { + public int maxEqualFreq(int[] nums) { + java.util.Map counts = new java.util.HashMap<>(); + java.util.Map frequencyCounts = new java.util.HashMap<>(); + int best = 0; + + for (int i = 0; i < nums.length; i++) { + int value = nums[i]; + int index = i + 1; + int previous = counts.getOrDefault(value, 0); + if (previous > 0) { + frequencyCounts.put(previous, frequencyCounts.get(previous) - 1); + if (frequencyCounts.get(previous) == 0) { + frequencyCounts.remove(previous); + } + } + counts.put(value, previous + 1); + int frequency = previous + 1; + frequencyCounts.put(frequency, frequencyCounts.getOrDefault(frequency, 0) + 1); + + if (frequencyCounts.size() == 1) { + java.util.Map.Entry entry = frequencyCounts.entrySet().iterator().next(); + int onlyFrequency = entry.getKey(); + int valueCount = entry.getValue(); + if (onlyFrequency == 1 || valueCount == 1) { + best = index; + } + } else if (frequencyCounts.size() == 2) { + Integer[] keys = frequencyCounts.keySet().toArray(new Integer[0]); + java.util.Arrays.sort(keys); + int low = keys[0]; + int high = keys[1]; + if ((low == 1 && frequencyCounts.get(low) == 1) || (high == low + 1 && frequencyCounts.get(high) == 1)) { + best = index; + } + } + } + + return best; + } +} diff --git a/tests/1001-1500/1224. maximum-equal-frequency/sol.kt b/tests/1001-1500/1224. maximum-equal-frequency/sol.kt new file mode 100644 index 00000000..9f904ff6 --- /dev/null +++ b/tests/1001-1500/1224. maximum-equal-frequency/sol.kt @@ -0,0 +1,40 @@ +class Solution { + fun maxEqualFreq(nums: IntArray): Int { + val counts = mutableMapOf() + val frequencyCounts = mutableMapOf() + var best = 0 + + for ((i, value) in nums.withIndex()) { + val index = i + 1 + val previous = counts.getOrDefault(value, 0) + if (previous > 0) { + frequencyCounts[previous] = frequencyCounts[previous]!! - 1 + if (frequencyCounts[previous] == 0) { + frequencyCounts.remove(previous) + } + } + counts[value] = previous + 1 + val frequency = previous + 1 + frequencyCounts[frequency] = frequencyCounts.getOrDefault(frequency, 0) + 1 + + when { + frequencyCounts.size == 1 -> { + val (onlyFrequency, valueCount) = frequencyCounts.entries.first() + if (onlyFrequency == 1 || valueCount == 1) { + best = index + } + } + frequencyCounts.size == 2 -> { + val sorted = frequencyCounts.keys.sorted() + val low = sorted[0] + val high = sorted[1] + if ((low == 1 && frequencyCounts[low] == 1) || (high == low + 1 && frequencyCounts[high] == 1)) { + best = index + } + } + } + } + + return best + } +} diff --git a/tests/1001-1500/1224. maximum-equal-frequency/sol.py b/tests/1001-1500/1224. maximum-equal-frequency/sol.py new file mode 100644 index 00000000..0b26a234 --- /dev/null +++ b/tests/1001-1500/1224. maximum-equal-frequency/sol.py @@ -0,0 +1,31 @@ +from collections import defaultdict + + +class Solution: + def maxEqualFreq(self, nums): + counts = defaultdict(int) + frequency_counts = defaultdict(int) + best = 0 + + for index, value in enumerate(nums, 1): + previous = counts[value] + if previous: + frequency_counts[previous] -= 1 + if frequency_counts[previous] == 0: + del frequency_counts[previous] + counts[value] = previous + 1 + frequency = previous + 1 + frequency_counts[frequency] += 1 + + if len(frequency_counts) == 1: + only_frequency, value_count = next(iter(frequency_counts.items())) + if only_frequency == 1 or value_count == 1: + best = index + elif len(frequency_counts) == 2: + low, high = sorted(frequency_counts) + if (low == 1 and frequency_counts[low] == 1) or ( + high == low + 1 and frequency_counts[high] == 1 + ): + best = index + + return best diff --git a/tests/1001-1500/1224. maximum-equal-frequency/sol.py2 b/tests/1001-1500/1224. maximum-equal-frequency/sol.py2 new file mode 100644 index 00000000..377bf7eb --- /dev/null +++ b/tests/1001-1500/1224. maximum-equal-frequency/sol.py2 @@ -0,0 +1,34 @@ +class Solution(object): + def maxEqualFreq(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + from collections import defaultdict + + counts = defaultdict(int) + frequency_counts = defaultdict(int) + best = 0 + + for index, value in enumerate(nums, 1): + previous = counts[value] + if previous: + frequency_counts[previous] -= 1 + if frequency_counts[previous] == 0: + del frequency_counts[previous] + counts[value] = previous + 1 + frequency = previous + 1 + frequency_counts[frequency] += 1 + + if len(frequency_counts) == 1: + only_frequency, value_count = next(iter(frequency_counts.items())) + if only_frequency == 1 or value_count == 1: + best = index + elif len(frequency_counts) == 2: + low, high = sorted(frequency_counts) + if (low == 1 and frequency_counts[low] == 1) or ( + high == low + 1 and frequency_counts[high] == 1 + ): + best = index + + return best diff --git a/tests/1001-1500/1224. maximum-equal-frequency/sol.rb b/tests/1001-1500/1224. maximum-equal-frequency/sol.rb new file mode 100644 index 00000000..7263d9fb --- /dev/null +++ b/tests/1001-1500/1224. maximum-equal-frequency/sol.rb @@ -0,0 +1,35 @@ +# @param {Integer[]} nums +# @return {Integer} +def max_equal_freq(nums) + counts = Hash.new(0) + frequency_counts = Hash.new(0) + best = 0 + + nums.each_with_index do |value, i| + index = i + 1 + previous = counts[value] + if previous != 0 + frequency_counts[previous] -= 1 + if frequency_counts[previous] == 0 + frequency_counts.delete(previous) + end + end + counts[value] = previous + 1 + frequency = previous + 1 + frequency_counts[frequency] = (frequency_counts[frequency] || 0) + 1 + + if frequency_counts.length == 1 + only_frequency, value_count = frequency_counts.first + if only_frequency == 1 || value_count == 1 + best = index + end + elsif frequency_counts.length == 2 + low, high = frequency_counts.keys.sort + if (low == 1 && frequency_counts[low] == 1) || (high == low + 1 && frequency_counts[high] == 1) + best = index + end + end + end + + best +end diff --git a/tests/1001-1500/1224. maximum-equal-frequency/sol.rs b/tests/1001-1500/1224. maximum-equal-frequency/sol.rs new file mode 100644 index 00000000..979e926b --- /dev/null +++ b/tests/1001-1500/1224. maximum-equal-frequency/sol.rs @@ -0,0 +1,43 @@ +impl Solution { + pub fn max_equal_freq(nums: Vec) -> i32 { + use std::collections::HashMap; + + let mut counts: HashMap = HashMap::new(); + let mut frequency_counts: HashMap = HashMap::new(); + let mut best: i32 = 0; + + for (i, &value) in nums.iter().enumerate() { + let index = (i + 1) as i32; + let previous = *counts.get(&value).unwrap_or(&0); + if previous > 0 { + let fc = frequency_counts.get_mut(&previous).unwrap(); + *fc -= 1; + if *fc == 0 { + frequency_counts.remove(&previous); + } + } + counts.insert(value, previous + 1); + let frequency = previous + 1; + *frequency_counts.entry(frequency).or_insert(0) += 1; + + if frequency_counts.len() == 1 { + let (&only_frequency, &value_count) = frequency_counts.iter().next().unwrap(); + if only_frequency == 1 || value_count == 1 { + best = index; + } + } else if frequency_counts.len() == 2 { + let mut keys: Vec = frequency_counts.keys().cloned().collect(); + keys.sort_unstable(); + let low = keys[0]; + let high = keys[1]; + if (low == 1 && *frequency_counts.get(&low).unwrap() == 1) + || (high == low + 1 && *frequency_counts.get(&high).unwrap() == 1) + { + best = index; + } + } + } + + best + } +} diff --git a/tests/1001-1500/1224. maximum-equal-frequency/sol.swift b/tests/1001-1500/1224. maximum-equal-frequency/sol.swift new file mode 100644 index 00000000..156b833d --- /dev/null +++ b/tests/1001-1500/1224. maximum-equal-frequency/sol.swift @@ -0,0 +1,37 @@ +class Solution { + func maxEqualFreq(_ nums: [Int]) -> Int { + var counts = [Int: Int]() + var frequencyCounts = [Int: Int]() + var best = 0 + + for (i, value) in nums.enumerated() { + let index = i + 1 + let previous = counts[value] ?? 0 + if previous > 0 { + frequencyCounts[previous, default: 0] -= 1 + if frequencyCounts[previous] == 0 { + frequencyCounts.removeValue(forKey: previous) + } + } + counts[value] = previous + 1 + let frequency = previous + 1 + frequencyCounts[frequency, default: 0] += 1 + + if frequencyCounts.count == 1 { + let (onlyFrequency, valueCount) = frequencyCounts.first! + if onlyFrequency == 1 || valueCount == 1 { + best = index + } + } else if frequencyCounts.count == 2 { + let sorted = frequencyCounts.keys.sorted() + let low = sorted[0] + let high = sorted[1] + if (low == 1 && frequencyCounts[low] == 1) || (high == low + 1 && frequencyCounts[high] == 1) { + best = index + } + } + } + + return best + } +} diff --git a/tests/1001-1500/1224. maximum-equal-frequency/sol.ts b/tests/1001-1500/1224. maximum-equal-frequency/sol.ts new file mode 100644 index 00000000..b18274f4 --- /dev/null +++ b/tests/1001-1500/1224. maximum-equal-frequency/sol.ts @@ -0,0 +1,41 @@ +function maxEqualFreq(nums: number[]): number { + const counts = new Map(); + const frequencyCounts = new Map(); + let best = 0; + + for (let i = 0; i < nums.length; i++) { + const value = nums[i]; + const index = i + 1; + const previous = counts.get(value) || 0; + if (previous > 0) { + frequencyCounts.set(previous, (frequencyCounts.get(previous) || 0) - 1); + if (frequencyCounts.get(previous) === 0) { + frequencyCounts.delete(previous); + } + } + counts.set(value, previous + 1); + const frequency = previous + 1; + frequencyCounts.set(frequency, (frequencyCounts.get(frequency) || 0) + 1); + + if (frequencyCounts.size === 1) { + const [onlyFrequency, valueCount] = frequencyCounts + .entries() + .next().value!; + if (onlyFrequency === 1 || valueCount === 1) { + best = index; + } + } else if (frequencyCounts.size === 2) { + const keys = Array.from(frequencyCounts.keys()).sort((a, b) => a - b); + const low = keys[0]; + const high = keys[1]; + if ( + (low === 1 && frequencyCounts.get(low) === 1) || + (high === low + 1 && frequencyCounts.get(high) === 1) + ) { + best = index; + } + } + } + + return best; +} diff --git a/tests/1001-1500/1227. airplane-seat-assignment-probability/manifest.yaml b/tests/1001-1500/1227. airplane-seat-assignment-probability/manifest.yaml new file mode 100644 index 00000000..89bb2402 --- /dev/null +++ b/tests/1001-1500/1227. airplane-seat-assignment-probability/manifest.yaml @@ -0,0 +1,221 @@ +entry: + id: 1227 + title: airplane-seat-assignment-probability + params: + n: + type: int + call: + cpp: "Solution().nthPersonGetsNthSeat({n})" + rust: "Solution::nth_person_gets_nth_seat({n})" + python3: "Solution().nthPersonGetsNthSeat({n})" + python2: "Solution().nthPersonGetsNthSeat({n})" + ruby: "nth_person_gets_nth_seat({n})" + java: "new Solution().nthPersonGetsNthSeat({n})" + csharp: "new Solution().NthPersonGetsNthSeat({n})" + kotlin: "Solution().nthPersonGetsNthSeat({n})" + go: "nthPersonGetsNthSeat({n})" + dart: "Solution().nthPersonGetsNthSeat({n})" + swift: "Solution().nthPersonGetsNthSeat({n})" + typescript: "nthPersonGetsNthSeat({n})" +judge: + type: "exact" +limits: + time_ms: 500 + memory_mb: 256 +oracle: + python3: + call: "Checker().nthPersonGetsNthSeat(n, {result})" + checker: | + import math + + class Checker: + def nthPersonGetsNthSeat(self, n, result): + if not isinstance(n, int) or isinstance(n, bool) or not 1 <= n <= 100000: + return False + if not isinstance(result, (int, float)) or isinstance(result, bool): + return False + value = float(result) + if not math.isfinite(value): + return False + expected = 1.0 if n == 1 else 0.5 + return value == expected +seed: 1227 +tests: + - name: example_single_passenger + in: + n: 1 + out: 1.0 + - name: example_two_passengers + in: + n: 2 + out: 0.5 + - name: smallest_nontrivial_odd + in: + n: 3 + out: 0.5 + - name: smallest_nontrivial_even + in: + n: 4 + out: 0.5 + - name: generated_large_midrange + seed: 50001 + in: + n: + gen: "int" + min: 40000 + max: 60000 + - name: generated_large_upper_midrange + seed: 50002 + in: + n: + gen: "int" + min: 60000 + max: 80000 + - name: generated_large_highrange + seed: 50003 + in: + n: + gen: "int" + min: 80000 + max: 90000 + - name: generated_large_near_limit + seed: 50004 + in: + n: + gen: "int" + min: 95000 + max: 99900 + - name: generated_large_upper_boundary + seed: 50005 + in: + n: + gen: "int" + min: 99901 + max: 100000 + - name: generated_large_maximum_band + seed: 50006 + in: + n: + gen: "int" + min: 99990 + max: 100000 + - name: first_two_digit + in: + n: 11 + out: 0.5 + - name: dozen_passengers + in: + n: 12 + out: 0.5 + - name: prime_thirteen + in: + n: 13 + out: 0.5 + - name: power_of_two_sixteen + in: + n: 16 + out: 0.5 + - name: prime_seventeen + in: + n: 17 + out: 0.5 + - name: twenty_passengers + in: + n: 20 + out: 0.5 + - name: power_of_two_thirty_two + in: + n: 32 + out: 0.5 + - name: prime_thirty_seven + in: + n: 37 + out: 0.5 + - name: power_of_two_sixty_four + in: + n: 64 + out: 0.5 + - name: near_hundred + in: + n: 99 + out: 0.5 + - name: hundred_passengers + in: + n: 100 + out: 0.5 + - name: just_above_hundred + in: + n: 101 + out: 0.5 + - name: power_of_two_two_fifty_six + in: + n: 256 + out: 0.5 + - name: prime_two_fifty_seven + in: + n: 257 + out: 0.5 + - name: five_hundred + in: + n: 500 + out: 0.5 + - name: power_of_two_five_twelve + in: + n: 512 + out: 0.5 + - name: thousand_passengers + in: + n: 1000 + out: 0.5 + - name: just_above_thousand + in: + n: 1001 + out: 0.5 + - name: power_of_two_two_thousand_forty_eight + in: + n: 2048 + out: 0.5 + - name: five_thousand + in: + n: 5000 + out: 0.5 + - name: power_of_two_eight_thousand_one_ninety_two + in: + n: 8192 + out: 0.5 + - name: ten_thousand + in: + n: 10000 + out: 0.5 + - name: power_of_two_sixteen_thousand_three_eighty_four + in: + n: 16384 + out: 0.5 + - name: midrange_fifty_thousand + in: + n: 50000 + out: 0.5 + - name: power_of_two_sixty_five_thousand_five_thirty_six + in: + n: 65536 + out: 0.5 + - name: large_ninety_thousand + in: + n: 90000 + out: 0.5 + - name: near_upper_bound_ninety_nine_thousand_nine_ninety_eight + in: + n: 99998 + out: 0.5 + - name: near_upper_bound_ninety_nine_thousand_nine_ninety_nine + in: + n: 99999 + out: 0.5 + - name: maximum_constraint + in: + n: 100000 + out: 0.5 + - name: large_prime_below_limit + in: + n: 99991 + out: 0.5 diff --git a/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.cpp b/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.cpp new file mode 100644 index 00000000..2b8b4423 --- /dev/null +++ b/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.cpp @@ -0,0 +1,6 @@ +class Solution { +public: + double nthPersonGetsNthSeat(int n) { + return n == 1 ? 1 : 0.5; + } +}; diff --git a/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.cs b/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.cs new file mode 100644 index 00000000..e416184c --- /dev/null +++ b/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.cs @@ -0,0 +1,5 @@ +public class Solution { + public double NthPersonGetsNthSeat(int n) { + return n == 1 ? 1 : 0.5; + } +} diff --git a/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.dart b/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.dart new file mode 100644 index 00000000..666cc2cb --- /dev/null +++ b/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.dart @@ -0,0 +1,5 @@ +class Solution { + double nthPersonGetsNthSeat(int n) { + return n == 1 ? 1 : 0.5; + } +} diff --git a/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.go b/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.go new file mode 100644 index 00000000..eb1ca6b8 --- /dev/null +++ b/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.go @@ -0,0 +1,6 @@ +func nthPersonGetsNthSeat(n int) float64 { + if n == 1 { + return 1 + } + return 0.5 +} diff --git a/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.java b/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.java new file mode 100644 index 00000000..9ce50be8 --- /dev/null +++ b/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.java @@ -0,0 +1,5 @@ +class Solution { + public double nthPersonGetsNthSeat(int n) { + return n == 1 ? 1 : 0.5; + } +} diff --git a/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.kt b/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.kt new file mode 100644 index 00000000..90d91546 --- /dev/null +++ b/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.kt @@ -0,0 +1,5 @@ +class Solution { + fun nthPersonGetsNthSeat(n: Int): Double { + return if (n == 1) 1.0 else 0.5 + } +} diff --git a/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.py b/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.py new file mode 100644 index 00000000..5c0752aa --- /dev/null +++ b/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.py @@ -0,0 +1,3 @@ +class Solution: + def nthPersonGetsNthSeat(self, n: int) -> float: + return 1 if n == 1 else 0.5 diff --git a/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.py2 b/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.py2 new file mode 100644 index 00000000..f356bd98 --- /dev/null +++ b/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.py2 @@ -0,0 +1,7 @@ +class Solution(object): + def nthPersonGetsNthSeat(self, n): + """ + :type n: int + :rtype: float + """ + return 1 if n == 1 else 0.5 diff --git a/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.rb b/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.rb new file mode 100644 index 00000000..f31404ef --- /dev/null +++ b/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.rb @@ -0,0 +1,5 @@ +# @param {Integer} n +# @return {Float} +def nth_person_gets_nth_seat(n) + n == 1 ? 1.0 : 0.5 +end diff --git a/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.rs b/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.rs new file mode 100644 index 00000000..ecc9846f --- /dev/null +++ b/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.rs @@ -0,0 +1,5 @@ +impl Solution { + pub fn nth_person_gets_nth_seat(n: i32) -> f64 { + if n == 1 { 1.0 } else { 0.5 } + } +} diff --git a/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.swift b/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.swift new file mode 100644 index 00000000..411ea8e9 --- /dev/null +++ b/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.swift @@ -0,0 +1,5 @@ +class Solution { + func nthPersonGetsNthSeat(_ n: Int) -> Double { + return n == 1 ? 1 : 0.5 + } +} diff --git a/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.ts b/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.ts new file mode 100644 index 00000000..a23c0f6e --- /dev/null +++ b/tests/1001-1500/1227. airplane-seat-assignment-probability/sol.ts @@ -0,0 +1,3 @@ +function nthPersonGetsNthSeat(n: number): number { + return n === 1 ? 1 : 0.5; +} diff --git a/tests/1001-1500/1232. check-if-it-is-a-straight-line/manifest.yaml b/tests/1001-1500/1232. check-if-it-is-a-straight-line/manifest.yaml new file mode 100644 index 00000000..96da19bb --- /dev/null +++ b/tests/1001-1500/1232. check-if-it-is-a-straight-line/manifest.yaml @@ -0,0 +1,414 @@ +entry: + id: 1232 + title: check-if-it-is-a-straight-line + params: + coordinates: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().checkStraightLine({coordinates})" + rust: "Solution::check_straight_line({coordinates})" + python3: "Solution().checkStraightLine({coordinates})" + python2: "Solution().checkStraightLine({coordinates})" + ruby: "check_straight_line({coordinates})" + java: "new Solution().checkStraightLine({coordinates})" + csharp: "new Solution().CheckStraightLine({coordinates})" + kotlin: "Solution().checkStraightLine({coordinates})" + go: "checkStraightLine({coordinates})" + dart: "Solution().checkStraightLine({coordinates})" + swift: "Solution().checkStraightLine({coordinates})" + typescript: "checkStraightLine({coordinates})" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().checkStraightLine(coordinates, {result})" + checker: | + class Checker: + def checkStraightLine(self, coordinates, result): + if type(result) is not bool or len(coordinates) < 2: + return False + x0, y0 = coordinates[0] + x1, y1 = coordinates[1] + dx, dy = x1 - x0, y1 - y0 + expected = True + for x, y in coordinates[2:]: + if (x - x0) * dy != (y - y0) * dx: + expected = False + break + return result == expected +seed: 1232 +tests: + - name: prompt-example-one + in: + coordinates: + elemType: "int" + value: + - [1, 2] + - [2, 3] + - [3, 4] + - name: prompt-example-two + in: + coordinates: + elemType: "int" + value: + - [1, 1] + - [2, 2] + - [3, 4] + - name: horizontal + in: + coordinates: + elemType: "int" + value: + - [0, 5] + - [1, 5] + - [7, 5] + - name: vertical + in: + coordinates: + elemType: "int" + value: + - [4, 0] + - [4, 1] + - [4, 9] + - name: positive-slope + in: + coordinates: + elemType: "int" + value: + - [-2, -4] + - [0, 0] + - [3, 6] + - [8, 16] + - name: negative-slope + in: + coordinates: + elemType: "int" + value: + - [-2, 4] + - [0, 0] + - [3, -6] + - [8, -16] + - name: two-points + in: + coordinates: + elemType: "int" + value: + - [100, -100] + - [-50, 50] + - name: three-collinear + in: + coordinates: + elemType: "int" + value: + - [0, 0] + - [2, 4] + - [4, 8] + - name: one-off-point + in: + coordinates: + elemType: "int" + value: + - [0, 0] + - [2, 4] + - [4, 9] + - name: vertical-break + in: + coordinates: + elemType: "int" + value: + - [3, -2] + - [3, 0] + - [4, 2] + - name: horizontal-break + in: + coordinates: + elemType: "int" + value: + - [-4, 7] + - [0, 7] + - [1, 8] + - name: steep-line + in: + coordinates: + elemType: "int" + value: + - [0, 0] + - [1, 10] + - [2, 20] + - [3, 30] + - name: fractional-slope + in: + coordinates: + elemType: "int" + value: + - [0, 0] + - [2, 1] + - [4, 2] + - [10, 5] + - name: fractional-break + in: + coordinates: + elemType: "int" + value: + - [0, 0] + - [2, 1] + - [4, 3] + - name: negative-coordinates + in: + coordinates: + elemType: "int" + value: + - [-10, -10] + - [-5, -5] + - [0, 0] + - [5, 5] + - name: origin-crossing + in: + coordinates: + elemType: "int" + value: + - [-3, 6] + - [-1, 2] + - [0, 0] + - [4, -8] + - name: repeated-direction + in: + coordinates: + elemType: "int" + value: + - [1, 1] + - [2, 2] + - [3, 3] + - [4, 5] + - name: many-horizontal + in: + coordinates: + elemType: "int" + value: + - [-5, -2] + - [-3, -2] + - [0, -2] + - [4, -2] + - [9, -2] + - name: many-vertical + in: + coordinates: + elemType: "int" + value: + - [8, -5] + - [8, -1] + - [8, 0] + - [8, 6] + - [8, 12] + - name: large-random-full-range-a + seed: 123201 + in: + coordinates: + gen: "array" + len: 1000 + distinct: true + sorted: false + elemType: "int" + of: + gen: "array" + len: 2 + distinct: false + sorted: false + elemType: "int" + of: + gen: "int" + min: -10000 + max: 10000 + - name: large-random-full-range-b + seed: 123202 + in: + coordinates: + gen: "array" + len: 1000 + distinct: true + sorted: false + elemType: "int" + of: + gen: "array" + len: 2 + distinct: false + sorted: false + elemType: "int" + of: + gen: "int" + min: -10000 + max: 10000 + - name: large-random-full-range-c + seed: 123203 + in: + coordinates: + gen: "array" + len: 1000 + distinct: true + sorted: false + elemType: "int" + of: + gen: "array" + len: 2 + distinct: false + sorted: false + elemType: "int" + of: + gen: "int" + min: -10000 + max: 10000 + - name: large-random-full-range-d + seed: 123204 + in: + coordinates: + gen: "array" + len: 1000 + distinct: true + sorted: false + elemType: "int" + of: + gen: "array" + len: 2 + distinct: false + sorted: false + elemType: "int" + of: + gen: "int" + min: -10000 + max: 10000 + - name: large-random-full-range-e + seed: 123205 + in: + coordinates: + gen: "array" + len: 1000 + distinct: true + sorted: false + elemType: "int" + of: + gen: "array" + len: 2 + distinct: false + sorted: false + elemType: "int" + of: + gen: "int" + min: -10000 + max: 10000 + - name: large-random-full-range-f + seed: 123206 + in: + coordinates: + gen: "array" + len: 1000 + distinct: true + sorted: false + elemType: "int" + of: + gen: "array" + len: 2 + distinct: false + sorted: false + elemType: "int" + of: + gen: "int" + min: -10000 + max: 10000 + - name: descending-x + in: + coordinates: + elemType: "int" + value: + - [10, 10] + - [5, 5] + - [0, 0] + - [-5, -5] + - name: descending-y + in: + coordinates: + elemType: "int" + value: + - [10, -10] + - [5, -5] + - [0, 0] + - [-5, 5] + - name: slope-one-break + in: + coordinates: + elemType: "int" + value: + - [-3, -3] + - [-2, -2] + - [-1, 0] + - name: slope-two-break + in: + coordinates: + elemType: "int" + value: + - [1, 2] + - [2, 4] + - [3, 7] + - name: five-collinear + in: + coordinates: + elemType: "int" + value: + - [-4, 9] + - [-2, 6] + - [0, 3] + - [2, 0] + - [4, -3] + - name: five-noncollinear + in: + coordinates: + elemType: "int" + value: + - [-4, 9] + - [-2, 6] + - [0, 4] + - [2, 0] + - [4, -3] + - name: endpoint-outlier + in: + coordinates: + elemType: "int" + value: + - [0, 1] + - [1, 2] + - [2, 3] + - [4, 4] + - name: shallow-negative + in: + coordinates: + elemType: "int" + value: + - [-6, 3] + - [-2, 2] + - [2, 1] + - [10, -1] + - name: shallow-break + in: + coordinates: + elemType: "int" + value: + - [-6, 3] + - [-2, 2] + - [2, 2] + - name: six-collinear + in: + coordinates: + elemType: "int" + value: + - [-5, -10] + - [-4, -8] + - [-1, -2] + - [0, 0] + - [3, 6] + - [5, 10] diff --git a/tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.cpp b/tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.cpp new file mode 100644 index 00000000..b2578710 --- /dev/null +++ b/tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + bool checkStraightLine(vector>& coordinates) { + int x1 = coordinates[0][0]; + int y1 = coordinates[0][1]; + int x2 = coordinates[1][0]; + int y2 = coordinates[1][1]; + + double slope; + if (x2 == x1) { + slope = HUGE_VAL; + } else { + slope = (double)(y2 - y1) / (x2 - x1); + } + + int n = coordinates.size(); + for (int i = 1; i < n - 1; i++) { + x1 = coordinates[i][0]; + y1 = coordinates[i][1]; + x2 = coordinates[i + 1][0]; + y2 = coordinates[i + 1][1]; + + double currSlope; + if (x2 == x1) { + currSlope = HUGE_VAL; + } else { + currSlope = (double)(y2 - y1) / (x2 - x1); + } + + if (currSlope != slope) { + return false; + } + } + + return true; + } +}; diff --git a/tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.cs b/tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.cs new file mode 100644 index 00000000..96ca3af9 --- /dev/null +++ b/tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.cs @@ -0,0 +1,36 @@ +public class Solution { + public bool CheckStraightLine(int[][] coordinates) { + int x1 = coordinates[0][0]; + int y1 = coordinates[0][1]; + int x2 = coordinates[1][0]; + int y2 = coordinates[1][1]; + + double slope; + if (x2 == x1) { + slope = double.PositiveInfinity; + } else { + slope = (double)(y2 - y1) / (x2 - x1); + } + + int n = coordinates.Length; + for (int i = 1; i < n - 1; i++) { + x1 = coordinates[i][0]; + y1 = coordinates[i][1]; + x2 = coordinates[i + 1][0]; + y2 = coordinates[i + 1][1]; + + double currSlope; + if (x2 == x1) { + currSlope = double.PositiveInfinity; + } else { + currSlope = (double)(y2 - y1) / (x2 - x1); + } + + if (currSlope != slope) { + return false; + } + } + + return true; + } +} diff --git a/tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.dart b/tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.dart new file mode 100644 index 00000000..371bc1f0 --- /dev/null +++ b/tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.dart @@ -0,0 +1,36 @@ +class Solution { + bool checkStraightLine(List> coordinates) { + int x1 = coordinates[0][0]; + int y1 = coordinates[0][1]; + int x2 = coordinates[1][0]; + int y2 = coordinates[1][1]; + + double slope; + if (x2 == x1) { + slope = double.infinity; + } else { + slope = (y2 - y1) / (x2 - x1); + } + + int n = coordinates.length; + for (int i = 1; i < n - 1; i++) { + x1 = coordinates[i][0]; + y1 = coordinates[i][1]; + x2 = coordinates[i + 1][0]; + y2 = coordinates[i + 1][1]; + + double currSlope; + if (x2 == x1) { + currSlope = double.infinity; + } else { + currSlope = (y2 - y1) / (x2 - x1); + } + + if (currSlope != slope) { + return false; + } + } + + return true; + } +} diff --git a/tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.go b/tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.go new file mode 100644 index 00000000..3c29a8c1 --- /dev/null +++ b/tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.go @@ -0,0 +1,30 @@ +func checkStraightLine(coordinates [][]int) bool { + x1, y1 := coordinates[0][0], coordinates[0][1] + x2, y2 := coordinates[1][0], coordinates[1][1] + + var slope float64 + if x2 == x1 { + slope = float64(1<<63 - 1) // infinity-like + } else { + slope = float64(y2 - y1) / float64(x2 - x1) + } + + n := len(coordinates) + for i := 1; i < n - 1; i++ { + x1, y1 = coordinates[i][0], coordinates[i][1] + x2, y2 = coordinates[i+1][0], coordinates[i+1][1] + + var currSlope float64 + if x2 == x1 { + currSlope = float64(1<<63 - 1) + } else { + currSlope = float64(y2 - y1) / float64(x2 - x1) + } + + if currSlope != slope { + return false + } + } + + return true +} diff --git a/tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.java b/tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.java new file mode 100644 index 00000000..3428d8b8 --- /dev/null +++ b/tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.java @@ -0,0 +1,36 @@ +class Solution { + public boolean checkStraightLine(int[][] coordinates) { + int x1 = coordinates[0][0]; + int y1 = coordinates[0][1]; + int x2 = coordinates[1][0]; + int y2 = coordinates[1][1]; + + double slope; + if (x2 == x1) { + slope = Double.POSITIVE_INFINITY; + } else { + slope = (double)(y2 - y1) / (x2 - x1); + } + + int n = coordinates.length; + for (int i = 1; i < n - 1; i++) { + x1 = coordinates[i][0]; + y1 = coordinates[i][1]; + x2 = coordinates[i + 1][0]; + y2 = coordinates[i + 1][1]; + + double currSlope; + if (x2 == x1) { + currSlope = Double.POSITIVE_INFINITY; + } else { + currSlope = (double)(y2 - y1) / (x2 - x1); + } + + if (currSlope != slope) { + return false; + } + } + + return true; + } +} diff --git a/tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.kt b/tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.kt new file mode 100644 index 00000000..f0530ae6 --- /dev/null +++ b/tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.kt @@ -0,0 +1,36 @@ +class Solution { + fun checkStraightLine(coordinates: Array): Boolean { + var x1 = coordinates[0][0] + var y1 = coordinates[0][1] + var x2 = coordinates[1][0] + var y2 = coordinates[1][1] + + val slope: Double + if (x2 == x1) { + slope = Double.POSITIVE_INFINITY + } else { + slope = (y2 - y1).toDouble() / (x2 - x1) + } + + val n = coordinates.size + for (i in 1 until n - 1) { + x1 = coordinates[i][0] + y1 = coordinates[i][1] + x2 = coordinates[i + 1][0] + y2 = coordinates[i + 1][1] + + val currSlope: Double + if (x2 == x1) { + currSlope = Double.POSITIVE_INFINITY + } else { + currSlope = (y2 - y1).toDouble() / (x2 - x1) + } + + if (currSlope != slope) { + return false + } + } + + return true + } +} diff --git a/tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.py b/tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.py new file mode 100644 index 00000000..dc23a425 --- /dev/null +++ b/tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.py @@ -0,0 +1,29 @@ +class Solution: + def findSlope(self, diff2, diff1): + return diff2 / diff1 + + def checkStraightLine(self, coordinates): + + x1, y1 = coordinates[0] + x2, y2 = coordinates[1] + + if x2 == x1: + slope = float("inf") + else: + slope = self.findSlope(y2 - y1, x2 - x1) + + n = len(coordinates) + + for i in range(1, n - 1): + x1, y1 = coordinates[i] + x2, y2 = coordinates[i + 1] + + if x2 == x1: + currSlope = float("inf") + else: + currSlope = self.findSlope(y2 - y1, x2 - x1) + + if currSlope != slope: + return False + + return True diff --git a/tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.py2 b/tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.py2 new file mode 100644 index 00000000..1c70e9f5 --- /dev/null +++ b/tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.py2 @@ -0,0 +1,28 @@ +class Solution(object): + def checkStraightLine(self, coordinates): + """ + :type coordinates: List[List[int]] + :rtype: bool + """ + x1, y1 = coordinates[0] + x2, y2 = coordinates[1] + + if x2 == x1: + slope = float('inf') + else: + slope = float(y2 - y1) / (x2 - x1) + + n = len(coordinates) + for i in range(1, n - 1): + x1, y1 = coordinates[i] + x2, y2 = coordinates[i + 1] + + if x2 == x1: + currSlope = float('inf') + else: + currSlope = float(y2 - y1) / (x2 - x1) + + if currSlope != slope: + return False + + return True diff --git a/tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.rb b/tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.rb new file mode 100644 index 00000000..56f754bd --- /dev/null +++ b/tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.rb @@ -0,0 +1,28 @@ +# @param {Integer[][]} coordinates +# @return {Boolean} +def check_straight_line(coordinates) + x1, y1 = coordinates[0] + x2, y2 = coordinates[1] + + if x2 == x1 + slope = Float::INFINITY + else + slope = (y2 - y1).to_f / (x2 - x1) + end + + n = coordinates.length + (1...n - 1).each do |i| + x1, y1 = coordinates[i] + x2, y2 = coordinates[i + 1] + + if x2 == x1 + curr_slope = Float::INFINITY + else + curr_slope = (y2 - y1).to_f / (x2 - x1) + end + + return false if curr_slope != slope + end + + true +end diff --git a/tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.rs b/tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.rs new file mode 100644 index 00000000..fbc346ec --- /dev/null +++ b/tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.rs @@ -0,0 +1,36 @@ +impl Solution { + pub fn check_straight_line(coordinates: Vec>) -> bool { + let x1 = coordinates[0][0]; + let y1 = coordinates[0][1]; + let x2 = coordinates[1][0]; + let y2 = coordinates[1][1]; + + let slope: f64; + if x2 == x1 { + slope = f64::INFINITY; + } else { + slope = (y2 - y1) as f64 / (x2 - x1) as f64; + } + + let n = coordinates.len(); + for i in 1..n - 1 { + let x1 = coordinates[i][0]; + let y1 = coordinates[i][1]; + let x2 = coordinates[i + 1][0]; + let y2 = coordinates[i + 1][1]; + + let curr_slope: f64; + if x2 == x1 { + curr_slope = f64::INFINITY; + } else { + curr_slope = (y2 - y1) as f64 / (x2 - x1) as f64; + } + + if curr_slope != slope { + return false; + } + } + + true + } +} diff --git a/tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.swift b/tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.swift new file mode 100644 index 00000000..a761ff50 --- /dev/null +++ b/tests/1001-1500/1232. check-if-it-is-a-straight-line/sol.swift @@ -0,0 +1,36 @@ +class Solution { + func checkStraightLine(_ coordinates: [[Int]]) -> Bool { + var x1 = coordinates[0][0] + var y1 = coordinates[0][1] + var x2 = coordinates[1][0] + var y2 = coordinates[1][1] + + var slope: Double + if x2 == x1 { + slope = Double.infinity + } else { + slope = Double(y2 - y1) / Double(x2 - x1) + } + + let n = coordinates.count + for i in 1.. removeSubfolders(vector& folder) { + sort(folder.begin(), folder.end()); + vector res; + for (const string& f : folder) { + if (res.empty()) { + res.push_back(f); + } else { + string prev = res.back(); + if (f.find(prev) == 0 && f.size() > prev.size() && f[prev.size()] == '/') { + continue; + } else { + res.push_back(f); + } + } + } + return res; + } +}; diff --git a/tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.cs b/tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.cs new file mode 100644 index 00000000..0949d140 --- /dev/null +++ b/tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.cs @@ -0,0 +1,19 @@ +public class Solution { + public IList RemoveSubfolders(string[] folder) { + Array.Sort(folder); + var res = new List(); + foreach (string f in folder) { + if (res.Count == 0) { + res.Add(f); + } else { + string prev = res[res.Count - 1]; + if (f.StartsWith(prev) && f.Length > prev.Length && f[prev.Length] == '/') { + continue; + } else { + res.Add(f); + } + } + } + return res; + } +} diff --git a/tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.dart b/tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.dart new file mode 100644 index 00000000..91fa408c --- /dev/null +++ b/tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.dart @@ -0,0 +1,19 @@ +class Solution { + List removeSubfolders(List folder) { + folder.sort(); + List res = []; + for (String f in folder) { + if (res.isEmpty) { + res.add(f); + } else { + String prev = res.last; + if (f.startsWith(prev) && f.length > prev.length && f[prev.length] == '/') { + continue; + } else { + res.add(f); + } + } + } + return res; + } +} diff --git a/tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.go b/tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.go new file mode 100644 index 00000000..55b211ac --- /dev/null +++ b/tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.go @@ -0,0 +1,17 @@ +func removeSubfolders(folder []string) []string { + sort.Strings(folder) + res := []string{} + for _, f := range folder { + if len(res) == 0 { + res = append(res, f) + } else { + prev := res[len(res)-1] + if strings.HasPrefix(f, prev) && len(f) > len(prev) && f[len(prev)] == '/' { + continue + } else { + res = append(res, f) + } + } + } + return res +} diff --git a/tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.java b/tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.java new file mode 100644 index 00000000..48f2edef --- /dev/null +++ b/tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.java @@ -0,0 +1,19 @@ +class Solution { + public List removeSubfolders(String[] folder) { + Arrays.sort(folder); + List res = new ArrayList<>(); + for (String f : folder) { + if (res.isEmpty()) { + res.add(f); + } else { + String prev = res.get(res.size() - 1); + if (f.startsWith(prev) && f.length() > prev.length() && f.charAt(prev.length()) == '/') { + continue; + } else { + res.add(f); + } + } + } + return res; + } +} diff --git a/tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.kt b/tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.kt new file mode 100644 index 00000000..94829aab --- /dev/null +++ b/tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.kt @@ -0,0 +1,19 @@ +class Solution { + fun removeSubfolders(folder: Array): List { + folder.sort() + val res = mutableListOf() + for (f in folder) { + if (res.isEmpty()) { + res.add(f) + } else { + val prev = res.last() + if (f.startsWith(prev) && f.length > prev.length && f[prev.length] == '/') { + continue + } else { + res.add(f) + } + } + } + return res + } +} diff --git a/tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.py b/tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.py new file mode 100644 index 00000000..6ab9aa5a --- /dev/null +++ b/tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.py @@ -0,0 +1,14 @@ +class Solution: + def removeSubfolders(self, folder: List[str]) -> List[str]: + folder.sort() + res = [] + for f in folder: + if not res: + res.append(f) + else: + prev = res[-1] + if f.startswith(prev) and len(f) > len(prev) and f[len(prev)] == "/": + continue + else: + res.append(f) + return res diff --git a/tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.py2 b/tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.py2 new file mode 100644 index 00000000..1e9a8354 --- /dev/null +++ b/tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.py2 @@ -0,0 +1,18 @@ +class Solution(object): + def removeSubfolders(self, folder): + """ + :type folder: List[str] + :rtype: List[str] + """ + folder.sort() + res = [] + for f in folder: + if not res: + res.append(f) + else: + prev = res[-1] + if f.startswith(prev) and len(f) > len(prev) and f[len(prev)] == '/': + continue + else: + res.append(f) + return res diff --git a/tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.rb b/tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.rb new file mode 100644 index 00000000..21efb243 --- /dev/null +++ b/tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.rb @@ -0,0 +1,19 @@ +# @param {String[]} folder +# @return {String[]} +def remove_subfolders(folder) + folder.sort! + res = [] + folder.each do |f| + if res.empty? + res << f + else + prev = res[-1] + if f.start_with?(prev) && f.length > prev.length && f[prev.length] == '/' + next + else + res << f + end + end + end + res +end diff --git a/tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.rs b/tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.rs new file mode 100644 index 00000000..a0c78a96 --- /dev/null +++ b/tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.rs @@ -0,0 +1,20 @@ +impl Solution { + pub fn remove_subfolders(folder: Vec) -> Vec { + let mut folder = folder; + folder.sort(); + let mut res: Vec = Vec::new(); + for f in folder { + if res.is_empty() { + res.push(f); + } else { + let prev = res.last().unwrap(); + if f.starts_with(prev) && f.len() > prev.len() && f.as_bytes()[prev.len()] == b'/' { + continue; + } else { + res.push(f); + } + } + } + res + } +} diff --git a/tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.swift b/tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.swift new file mode 100644 index 00000000..030ee7b3 --- /dev/null +++ b/tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.swift @@ -0,0 +1,21 @@ +class Solution { + func removeSubfolders(_ folder: [String]) -> [String] { + let folder = folder.sorted() + var res: [String] = [] + for f in folder { + if res.isEmpty { + res.append(f) + } else { + let prev = res.last! + if f.hasPrefix(prev) && f.count > prev.count { + let index = f.index(f.startIndex, offsetBy: prev.count) + if f[index] == "/" { + continue + } + } + res.append(f) + } + } + return res + } +} diff --git a/tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.ts b/tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.ts new file mode 100644 index 00000000..8a709654 --- /dev/null +++ b/tests/1001-1500/1233. remove-sub-folders-from-the-filesystem/sol.ts @@ -0,0 +1,21 @@ +function removeSubfolders(folder: string[]): string[] { + folder.sort(); + const res: string[] = []; + for (const f of folder) { + if (res.length === 0) { + res.push(f); + } else { + const prev = res[res.length - 1]; + if ( + f.startsWith(prev) && + f.length > prev.length && + f[prev.length] === "/" + ) { + continue; + } else { + res.push(f); + } + } + } + return res; +} diff --git a/tests/1001-1500/1234. replace-the-substring-for-balanced-string/manifest.yaml b/tests/1001-1500/1234. replace-the-substring-for-balanced-string/manifest.yaml new file mode 100644 index 00000000..0e265483 --- /dev/null +++ b/tests/1001-1500/1234. replace-the-substring-for-balanced-string/manifest.yaml @@ -0,0 +1,220 @@ +entry: + id: 1234 + title: "replace-the-substring-for-balanced-string" + params: + s: + type: string + call: + cpp: "Solution().balancedString({s})" + rust: "Solution::balanced_string({s})" + python3: "Solution().balancedString({s})" + python2: "Solution().balancedString({s})" + ruby: "balanced_string({s})" + java: "new Solution().balancedString({s})" + csharp: "new Solution().BalancedString({s})" + kotlin: "Solution().balancedString({s})" + go: "balancedString({s})" + dart: "Solution().balancedString({s})" + swift: "Solution().balancedString({s})" + typescript: "balancedString({s})" + +judge: + type: "exact" + +limits: + time_ms: 700 + memory_mb: 300 + +oracle: + python3: + call: "Checker().balancedString(s, {result})" + checker: | + class Checker: + def balancedString(self, s, result): + if not isinstance(result, int) or isinstance(result, bool) or len(s) < 4 or len(s) % 4 != 0: + return False + target = len(s) // 4 + total = {ch: s.count(ch) for ch in 'QWER'} + if all(total[ch] == target for ch in total): + return result == 0 + left = 0 + window = {ch: 0 for ch in 'QWER'} + best = len(s) + for right, ch in enumerate(s): + window[ch] += 1 + while left <= right and all(total[x] - window[x] <= target for x in 'QWER'): + best = min(best, right - left + 1) + window[s[left]] -= 1 + left += 1 + return result == best + +seed: 123400 + +tests: + - name: "example_balanced" + in: + s: "QWER" + out: 0 + - name: "example_one_excess" + in: + s: "QQWE" + out: 1 + - name: "example_two_excess" + in: + s: "QQQW" + out: 2 + - name: "all_q_minimum" + in: + s: "QQQQ" + out: 3 + - name: "all_w_minimum" + in: + s: "WWWW" + out: 3 + - name: "all_e_minimum" + in: + s: "EEEE" + out: 3 + - name: "all_r_minimum" + in: + s: "RRRR" + out: 3 + - name: "two_q_two_w" + in: + s: "QQWW" + out: 2 + - name: "two_q_two_e" + in: + s: "QQEE" + out: 2 + - name: "two_q_two_r" + in: + s: "QQRR" + out: 2 + - name: "three_w_one_q" + in: + s: "QWWW" + out: 2 + - name: "three_e_one_r" + in: + s: "EEER" + out: 2 + - name: "alternating_two" + in: + s: "QWQW" + out: 2 + - name: "balanced_twice" + in: + s: "QWERQWER" + out: 0 + - name: "balanced_permuted" + in: + s: "QQWWEERR" + out: 0 + - name: "two_heavy_blocks" + in: + s: "QQQQWWWW" + out: 4 + - name: "one_each_extra" + in: + s: "QQQWEERR" + out: 1 + - name: "two_q_blocks" + in: + s: "QQQWQQQW" + out: 5 + - name: "mixed_excess" + in: + s: "QWERRRQQ" + out: 2 + - name: "balanced_scrambled" + in: + s: "QWQEQWER" + out: 1 + - name: "eight_q" + in: + s: "QQQQQQQQ" + out: 6 + - name: "balanced_thrice" + in: + s: "QWERQWERQWER" + out: 0 + - name: "three_q_three_r_excess" + in: + s: "QQQQWWEERRQQ" + out: 3 + - name: "alternating_long" + in: + s: "QWQWQWQW" + out: 4 + - name: "three_overrepresented" + in: + s: "QQQQWWWWEEEE" + out: 6 + - name: "one_q_excess_long" + in: + s: "QQQWEEER" + out: 3 + - name: "many_e" + in: + s: "QWEEEEEE" + out: 4 + - name: "q_w_r_mix" + in: + s: "QQWWRRRR" + out: 2 + - name: "five_q_three_w" + in: + s: "QQQQQWWW" + out: 4 + - name: "five_q_one_w_two_e" + in: + s: "QQQQQWEE" + out: 3 + - name: "large_q_r_blocks" + in: + s: "QQQQQQQWRRRRRRRR" + out: 8 + - name: "balanced_four_times" + in: + s: "QWERQWERQWERQWER" + out: 0 + - name: "balanced_six_times" + in: + s: "QWERQWERQWERQWERQWERQWER" + out: 0 + - name: "generated_small" + seed: 123401 + in: + s: + gen: "str" + len: 20 + alphabet: "QWER" + - name: "generated_medium" + seed: 123402 + in: + s: + gen: "str" + len: 100 + alphabet: "QWER" + - name: "generated_large" + seed: 123403 + in: + s: + gen: "str" + len: 1000 + alphabet: "QWER" + - name: "generated_maximum_a" + seed: 123404 + in: + s: + gen: "str" + len: 100000 + alphabet: "QWER" + - name: "generated_maximum_b" + seed: 123405 + in: + s: + gen: "str" + len: 100000 + alphabet: "QWER" diff --git a/tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.cpp b/tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.cpp new file mode 100644 index 00000000..fbc88593 --- /dev/null +++ b/tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.cpp @@ -0,0 +1,45 @@ +class Solution { +public: + int balancedString(string s) { + int n = s.size(); + int each = n / 4; + unordered_map count; + for (char c : s) { + count[c]++; + } + unordered_map extra; + for (auto& [k, v] : count) { + if (v > each) { + extra[k] = v - each; + } + } + if (extra.empty()) return 0; + int left = 0; + int res = INT_MAX; + unordered_map curr; + for (int right = 0; right < n; right++) { + char rc = s[right]; + if (extra.count(rc)) { + curr[rc]++; + } + auto allMet = [&]() { + for (auto& [k, v] : extra) { + if (curr[k] < v) return false; + } + return true; + }; + while (allMet() && left <= right) { + res = min(res, right - left + 1); + char lc = s[left]; + if (curr.count(lc)) { + curr[lc]--; + if (curr[lc] == 0) { + curr.erase(lc); + } + } + left++; + } + } + return res; + } +}; diff --git a/tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.cs b/tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.cs new file mode 100644 index 00000000..9ab42726 --- /dev/null +++ b/tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.cs @@ -0,0 +1,44 @@ +public class Solution { + public int BalancedString(string s) { + int n = s.Length; + int each = n / 4; + var count = new Dictionary(); + foreach (char c in s) { + if (count.ContainsKey(c)) count[c]++; + else count[c] = 1; + } + var extra = new Dictionary(); + foreach (var kv in count) { + if (kv.Value > each) { + extra[kv.Key] = kv.Value - each; + } + } + if (extra.Count == 0) return 0; + int left = 0; + int res = int.MaxValue; + var curr = new Dictionary(); + for (int right = 0; right < n; right++) { + char rc = s[right]; + if (extra.ContainsKey(rc)) { + if (curr.ContainsKey(rc)) curr[rc]++; + else curr[rc] = 1; + } + bool AllMet() { + foreach (var kv in extra) { + if (!curr.ContainsKey(kv.Key) || curr[kv.Key] < kv.Value) return false; + } + return true; + } + while (AllMet() && left <= right) { + res = Math.Min(res, right - left + 1); + char lc = s[left]; + if (curr.ContainsKey(lc)) { + curr[lc]--; + if (curr[lc] == 0) curr.Remove(lc); + } + left++; + } + } + return res; + } +} diff --git a/tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.dart b/tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.dart new file mode 100644 index 00000000..73cb2434 --- /dev/null +++ b/tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.dart @@ -0,0 +1,47 @@ +class Solution { + int balancedString(String s) { + int n = s.length; + int each = n ~/ 4; + Map count = {}; + for (int i = 0; i < n; i++) { + String c = s[i]; + count[c] = (count[c] ?? 0) + 1; + } + Map extra = {}; + for (var entry in count.entries) { + if (entry.value > each) { + extra[entry.key] = entry.value - each; + } + } + if (extra.isEmpty) return 0; + int left = 0; + int res = 1 << 60; + Map curr = {}; + for (int right = 0; right < n; right++) { + String rc = s[right]; + if (extra.containsKey(rc)) { + curr[rc] = (curr[rc] ?? 0) + 1; + } + bool allMet() { + for (var e in extra.entries) { + if ((curr[e.key] ?? 0) < e.value) return false; + } + return true; + } + while (allMet() && left <= right) { + if (right - left + 1 < res) { + res = right - left + 1; + } + String lc = s[left]; + if (curr.containsKey(lc)) { + curr[lc] = curr[lc]! - 1; + if (curr[lc] == 0) { + curr.remove(lc); + } + } + left++; + } + } + return res; + } +} diff --git a/tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.go b/tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.go new file mode 100644 index 00000000..b0196e69 --- /dev/null +++ b/tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.go @@ -0,0 +1,52 @@ +func balancedString(s string) int { + n := len(s) + each := n / 4 + count := make(map[byte]int) + for i := 0; i < n; i++ { + count[s[i]]++ + } + extra := make(map[byte]int) + for k, v := range count { + if v > each { + extra[k] = v - each + } + } + if len(extra) == 0 { + return 0 + } + left := 0 + res := int(^uint(0) >> 1) + curr := make(map[byte]int) + for right := 0; right < n; right++ { + if _, ok := extra[s[right]]; ok { + curr[s[right]]++ + } + allMet := true + for k, v := range extra { + if curr[k] < v { + allMet = false + break + } + } + for allMet && left <= right { + if right-left+1 < res { + res = right - left + 1 + } + if _, ok := curr[s[left]]; ok { + curr[s[left]]-- + if curr[s[left]] == 0 { + delete(curr, s[left]) + } + } + left++ + allMet = true + for k, v := range extra { + if curr[k] < v { + allMet = false + break + } + } + } + } + return res +} diff --git a/tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.java b/tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.java new file mode 100644 index 00000000..55c6f5ee --- /dev/null +++ b/tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.java @@ -0,0 +1,52 @@ +class Solution { + public int balancedString(String s) { + int n = s.length(); + int each = n / 4; + java.util.Map count = new java.util.HashMap<>(); + for (char c : s.toCharArray()) { + count.put(c, count.getOrDefault(c, 0) + 1); + } + java.util.Map extra = new java.util.HashMap<>(); + for (char c : count.keySet()) { + if (count.get(c) > each) { + extra.put(c, count.get(c) - each); + } + } + if (extra.isEmpty()) return 0; + int left = 0; + int res = Integer.MAX_VALUE; + java.util.Map curr = new java.util.HashMap<>(); + for (int right = 0; right < n; right++) { + char rc = s.charAt(right); + if (extra.containsKey(rc)) { + curr.put(rc, curr.getOrDefault(rc, 0) + 1); + } + boolean allMet = true; + for (char k : extra.keySet()) { + if (curr.getOrDefault(k, 0) < extra.get(k)) { + allMet = false; + break; + } + } + while (allMet && left <= right) { + res = Math.min(res, right - left + 1); + char lc = s.charAt(left); + if (curr.containsKey(lc)) { + curr.put(lc, curr.get(lc) - 1); + if (curr.get(lc) == 0) { + curr.remove(lc); + } + } + left++; + allMet = true; + for (char k : extra.keySet()) { + if (curr.getOrDefault(k, 0) < extra.get(k)) { + allMet = false; + break; + } + } + } + } + return res; + } +} diff --git a/tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.kt b/tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.kt new file mode 100644 index 00000000..d7f19bce --- /dev/null +++ b/tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.kt @@ -0,0 +1,38 @@ +class Solution { + fun balancedString(s: String): Int { + val n = s.length + val each = n / 4 + val count = mutableMapOf() + for (c in s) { + count[c] = count.getOrDefault(c, 0) + 1 + } + val extra = mutableMapOf() + for ((k, v) in count) { + if (v > each) { + extra[k] = v - each + } + } + if (extra.isEmpty()) return 0 + var left = 0 + var res = Int.MAX_VALUE + val curr = mutableMapOf() + for (right in 0 until n) { + val rc = s[right] + if (rc in extra) { + curr[rc] = curr.getOrDefault(rc, 0) + 1 + } + while (extra.all { curr.getOrDefault(it.key, 0) >= it.value } && left <= right) { + res = minOf(res, right - left + 1) + val lc = s[left] + if (lc in curr) { + curr[lc] = curr[lc]!! - 1 + if (curr[lc] == 0) { + curr.remove(lc) + } + } + left++ + } + } + return res + } +} diff --git a/tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.py b/tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.py new file mode 100644 index 00000000..11e05caf --- /dev/null +++ b/tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.py @@ -0,0 +1,27 @@ +class Solution: + def balancedString(self, s: str) -> int: + n = len(s) + each = n // 4 + count = {} + for i in s: + count[i] = count.get(i, 0) + 1 + extra = {} + for i in count: + if count[i] > each: + extra[i] = count[i] - each + if not extra: + return 0 + left = 0 + res = float("inf") + curr = {} + for right in range(n): + if s[right] in extra: + curr[s[right]] = curr.get(s[right], 0) + 1 + while all(curr.get(i, 0) >= extra[i] for i in extra) and left <= right: + res = min(res, right - left + 1) + if s[left] in curr: + curr[s[left]] -= 1 + if curr[s[left]] == 0: + del curr[s[left]] + left += 1 + return res diff --git a/tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.py2 b/tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.py2 new file mode 100644 index 00000000..1dff095b --- /dev/null +++ b/tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.py2 @@ -0,0 +1,31 @@ +class Solution(object): + def balancedString(self, s): + """ + :type s: str + :rtype: int + """ + n = len(s) + each = n // 4 + count = {} + for i in s: + count[i] = count.get(i, 0) + 1 + extra = {} + for i in count: + if count[i] > each: + extra[i] = count[i] - each + if not extra: + return 0 + left = 0 + res = float('inf') + curr = {} + for right in range(n): + if s[right] in extra: + curr[s[right]] = curr.get(s[right], 0) + 1 + while all(curr.get(i, 0) >= extra[i] for i in extra) and left <= right: + res = min(res, right - left + 1) + if s[left] in curr: + curr[s[left]] -= 1 + if curr[s[left]] == 0: + del curr[s[left]] + left += 1 + return res diff --git a/tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.rb b/tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.rb new file mode 100644 index 00000000..a83ea499 --- /dev/null +++ b/tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.rb @@ -0,0 +1,30 @@ +# @param {String} s +# @return {Integer} +def balanced_string(s) + n = s.length + each = n / 4 + count = Hash.new(0) + s.each_char { |c| count[c] += 1 } + extra = {} + count.each do |k, v| + extra[k] = v - each if v > each + end + return 0 if extra.empty? + left = 0 + res = Float::INFINITY + curr = Hash.new(0) + (0...n).each do |right| + if extra.key?(s[right]) + curr[s[right]] += 1 + end + while extra.all? { |k, v| curr.fetch(k, 0) >= v } && left <= right + res = [res, right - left + 1].min + if curr.key?(s[left]) + curr[s[left]] -= 1 + curr.delete(s[left]) if curr[s[left]] == 0 + end + left += 1 + end + end + res +end diff --git a/tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.rs b/tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.rs new file mode 100644 index 00000000..7189fa56 --- /dev/null +++ b/tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.rs @@ -0,0 +1,41 @@ +impl Solution { + pub fn balanced_string(s: String) -> i32 { + let n = s.len(); + let each = n / 4; + let mut count = std::collections::HashMap::new(); + for c in s.chars() { + *count.entry(c).or_insert(0) += 1; + } + let mut extra = std::collections::HashMap::new(); + for (&k, &v) in &count { + if v > each { + extra.insert(k, v - each); + } + } + if extra.is_empty() { + return 0; + } + let s_chars: Vec = s.chars().collect(); + let mut left = 0; + let mut res = i32::MAX as usize; + let mut curr = std::collections::HashMap::new(); + for right in 0..n { + let rc = s_chars[right]; + if extra.contains_key(&rc) { + *curr.entry(rc).or_insert(0) += 1; + } + while extra.iter().all(|(k, v)| curr.get(k).unwrap_or(&0) >= v) && left <= right { + res = res.min(right - left + 1); + let lc = s_chars[left]; + if let Some(val) = curr.get_mut(&lc) { + *val -= 1; + if *val == 0 { + curr.remove(&lc); + } + } + left += 1; + } + } + res as i32 + } +} diff --git a/tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.swift b/tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.swift new file mode 100644 index 00000000..2ad35290 --- /dev/null +++ b/tests/1001-1500/1234. replace-the-substring-for-balanced-string/sol.swift @@ -0,0 +1,45 @@ +class Solution { + func balancedString(_ s: String) -> Int { + let n = s.count + let each = n / 4 + let chars = Array(s) + var count = [Character: Int]() + for c in chars { + count[c, default: 0] += 1 + } + var extra = [Character: Int]() + for (k, v) in count { + if v > each { + extra[k] = v - each + } + } + if extra.isEmpty { return 0 } + var left = 0 + var res = Int.max + var curr = [Character: Int]() + for right in 0.. each) { + extra[k] = count[k] - each; + } + } + if (Object.keys(extra).length === 0) return 0; + let left = 0; + let res = Infinity; + const curr: { [key: string]: number } = {}; + for (let right = 0; right < n; right++) { + const rc = s[right]; + if (rc in extra) { + curr[rc] = (curr[rc] || 0) + 1; + } + while ( + Object.keys(extra).every((k) => (curr[k] || 0) >= extra[k]) && + left <= right + ) { + res = Math.min(res, right - left + 1); + const lc = s[left]; + if (lc in curr) { + curr[lc]--; + if (curr[lc] === 0) { + delete curr[lc]; + } + } + left++; + } + } + return res; +} diff --git a/tests/1001-1500/1235. maximum-profit-in-job-scheduling/manifest.yaml b/tests/1001-1500/1235. maximum-profit-in-job-scheduling/manifest.yaml new file mode 100644 index 00000000..9b20fe9d --- /dev/null +++ b/tests/1001-1500/1235. maximum-profit-in-job-scheduling/manifest.yaml @@ -0,0 +1,335 @@ +entry: + id: 1235 + title: "maximum-profit-in-job-scheduling" + params: + startTime: + type: array + items: + type: int + endTime: + type: array + items: + type: int + profit: + type: array + items: + type: int + call: + cpp: "Solution().jobScheduling({startTime}, {endTime}, {profit})" + rust: "Solution::job_scheduling({startTime}, {endTime}, {profit})" + python3: "Solution().jobScheduling({startTime}, {endTime}, {profit})" + python2: "Solution().jobScheduling({startTime}, {endTime}, {profit})" + ruby: "job_scheduling({startTime}, {endTime}, {profit})" + java: "new Solution().jobScheduling({startTime}, {endTime}, {profit})" + csharp: "new Solution().JobScheduling({startTime}, {endTime}, {profit})" + kotlin: "Solution().jobScheduling({startTime}, {endTime}, {profit})" + go: "jobScheduling({startTime}, {endTime}, {profit})" + dart: "Solution().jobScheduling({startTime}, {endTime}, {profit})" + swift: "Solution().jobScheduling({startTime}, {endTime}, {profit})" + typescript: "jobScheduling({startTime}, {endTime}, {profit})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().jobScheduling(startTime, endTime, profit, {result})" + checker: | + from bisect import bisect_left + class Checker: + def jobScheduling(self, startTime, endTime, profit, result): + jobs = sorted(zip(startTime, endTime, profit)) + starts = [job[0] for job in jobs] + dp = [0] * (len(jobs) + 1) + for i in range(len(jobs) - 1, -1, -1): + nxt = bisect_left(starts, jobs[i][1], i + 1) + dp[i] = max(dp[i + 1], jobs[i][2] + dp[nxt]) + return result == dp[0] + +seed: 1235 + +tests: + - name: "example-one" + in: + startTime: [1, 2, 3, 3] + endTime: [3, 4, 5, 6] + profit: [50, 10, 40, 70] + - name: "example-two" + in: + startTime: [1, 2, 3, 4, 6] + endTime: [3, 5, 10, 6, 9] + profit: [20, 20, 100, 70, 60] + - name: "example-three" + in: + startTime: [1, 1, 1] + endTime: [2, 3, 4] + profit: [5, 6, 4] + - name: "single-job" + in: + startTime: [1] + endTime: [2] + profit: [100] + - name: "two-touching" + in: + startTime: [1, 3] + endTime: [3, 5] + profit: [5, 7] + - name: "two-overlapping" + in: + startTime: [1, 2] + endTime: [4, 5] + profit: [10, 20] + - name: "choose-longer-profit" + in: + startTime: [1, 2, 3] + endTime: [10, 4, 5] + profit: [50, 30, 30] + - name: "nested-jobs" + in: + startTime: [1, 2, 3, 4] + endTime: [10, 5, 6, 7] + profit: [100, 20, 20, 20] + - name: "same-starts" + in: + startTime: [1, 1, 1, 1] + endTime: [2, 3, 4, 5] + profit: [3, 7, 8, 6] + - name: "same-ends" + in: + startTime: [1, 2, 3, 4] + endTime: [5, 5, 5, 5] + profit: [3, 8, 6, 7] + - name: "all-compatible" + in: + startTime: [1, 3, 5, 7, 9] + endTime: [3, 5, 7, 9, 11] + profit: [1, 2, 3, 4, 5] + - name: "all-overlap" + in: + startTime: [1, 1, 1, 1, 1] + endTime: [10, 10, 10, 10, 10] + profit: [1, 2, 100, 4, 5] + - name: "zero-gap-touching" + in: + startTime: [5, 10, 15] + endTime: [10, 15, 20] + profit: [20, 30, 40] + - name: "late-starts" + in: + startTime: [100, 200, 300] + endTime: [150, 250, 350] + profit: [10, 20, 30] + - name: "large-time-values" + in: + startTime: [1, 500000000, 999999998] + endTime: [500000000, 999999999, 1000000000] + profit: [1000, 2000, 3000] + - name: "large-profit-choice" + in: + startTime: [1, 2, 4] + endTime: [5, 3, 6] + profit: [10000, 9999, 10000] + - name: "chain-with-detour" + in: + startTime: [1, 2, 4, 6] + endTime: [2, 4, 6, 8] + profit: [10, 1, 10, 10] + - name: "overlap-high-middle" + in: + startTime: [1, 2, 3, 4, 5] + endTime: [4, 5, 6, 7, 8] + profit: [10, 20, 100, 20, 10] + - name: "independent-blocks" + in: + startTime: [1, 2, 10, 11, 20] + endTime: [2, 3, 11, 12, 21] + profit: [5, 8, 6, 7, 9] + - name: "duplicate-intervals" + in: + startTime: [1, 1, 3, 3] + endTime: [3, 3, 5, 5] + profit: [10, 20, 30, 40] + - name: "short-jobs-vs-long" + in: + startTime: [1, 2, 3, 4, 5] + endTime: [6, 3, 4, 5, 6] + profit: [15, 5, 5, 5, 5] + - name: "unsorted-input" + in: + startTime: [5, 1, 3, 8] + endTime: [7, 3, 5, 10] + profit: [20, 10, 15, 25] + - name: "equal-boundary-many" + in: + startTime: [1, 4, 4, 7, 7, 10] + endTime: [4, 7, 6, 10, 9, 12] + profit: [5, 8, 3, 6, 20, 4] + - name: "profit-priority" + in: + startTime: [1, 2, 5, 6] + endTime: [6, 5, 7, 10] + profit: [30, 10, 20, 100] + - name: "long-compatible-chain" + in: + startTime: [1, 2, 3, 4, 5, 6, 7, 8] + endTime: [2, 3, 4, 5, 6, 7, 8, 9] + profit: [1, 1, 1, 1, 1, 1, 1, 1] + - name: "late-high-profit" + in: + startTime: [1, 2, 3, 10] + endTime: [9, 4, 5, 11] + profit: [20, 5, 5, 100] + - name: "max-time-single" + in: + startTime: [999999999] + endTime: [1000000000] + profit: [10000] + - name: "many-overlap-choice" + in: + startTime: [1, 2, 3, 4, 5, 6] + endTime: [7, 8, 9, 10, 11, 12] + profit: [5, 6, 7, 8, 100, 10] + - name: "alternating-gaps" + in: + startTime: [1, 3, 4, 8, 9, 12] + endTime: [3, 4, 8, 9, 12, 15] + profit: [4, 3, 20, 2, 30, 5] + - name: "exact-touch-high-followup" + in: + startTime: [1, 5] + endTime: [5, 6] + profit: [10, 100] + - name: "generated-small" + in: + startTime: + gen: "array" + len: 10 + of: + gen: "int" + min: 1 + max: 100 + elemType: "int" + endTime: + gen: "array" + len: 10 + of: + gen: "int" + min: 101 + max: 200 + elemType: "int" + profit: + gen: "array" + len: 10 + of: + gen: "int" + min: 1 + max: 10000 + elemType: "int" + - name: "generated-medium" + in: + startTime: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 10000 + elemType: "int" + endTime: + gen: "array" + len: 100 + of: + gen: "int" + min: 10001 + max: 20000 + elemType: "int" + profit: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 10000 + elemType: "int" + - name: "generated-large" + in: + startTime: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 100000000 + elemType: "int" + endTime: + gen: "array" + len: 50000 + of: + gen: "int" + min: 100000001 + max: 1000000000 + elemType: "int" + profit: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 10000 + elemType: "int" + - name: "generated-narrow-time" + in: + startTime: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 100 + elemType: "int" + endTime: + gen: "array" + len: 1000 + of: + gen: "int" + min: 101 + max: 200 + elemType: "int" + profit: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 10000 + elemType: "int" + - name: "generated-valid-short-range" + in: + startTime: + gen: "array" + len: 5000 + of: + gen: "int" + min: 1 + max: 100 + elemType: "int" + endTime: + gen: "array" + len: 5000 + of: + gen: "int" + min: 101 + max: 200 + elemType: "int" + profit: + gen: "array" + len: 5000 + of: + gen: "int" + min: 1 + max: 10000 + elemType: "int" diff --git a/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.cpp b/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.cpp new file mode 100644 index 00000000..fa5619ee --- /dev/null +++ b/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int jobScheduling(vector& startTime, vector& endTime, vector& profit) { + int n = startTime.size(); + vector> jobs(n); + for (int i = 0; i < n; ++i) { + jobs[i] = {startTime[i], endTime[i], profit[i]}; + } + sort(jobs.begin(), jobs.end(), [](auto& a, auto& b) { + return a[0] < b[0]; + }); + + vector starts(n); + for (int i = 0; i < n; ++i) { + starts[i] = jobs[i][0]; + } + + vector dp(n + 1, 0); + for (int i = n - 1; i >= 0; --i) { + int target = jobs[i][1]; + int idx = lower_bound(starts.begin() + i + 1, starts.end(), target) - starts.begin(); + int take = jobs[i][2] + dp[idx]; + int notTake = dp[i + 1]; + dp[i] = max(take, notTake); + } + return dp[0]; + } +}; diff --git a/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.cs b/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.cs new file mode 100644 index 00000000..34743e29 --- /dev/null +++ b/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.cs @@ -0,0 +1,26 @@ +public class Solution { + public int JobScheduling(int[] startTime, int[] endTime, int[] profit) { + int n = startTime.Length; + int[][] jobs = new int[n][]; + for (int i = 0; i < n; i++) { + jobs[i] = new int[] { startTime[i], endTime[i], profit[i] }; + } + Array.Sort(jobs, (a, b) => a[0].CompareTo(b[0])); + + int[] starts = new int[n]; + for (int i = 0; i < n; i++) { + starts[i] = jobs[i][0]; + } + + int[] dp = new int[n + 1]; + for (int i = n - 1; i >= 0; i--) { + int target = jobs[i][1]; + int idx = Array.BinarySearch(starts, i + 1, n - i - 1, target); + if (idx < 0) idx = ~idx; + int take = jobs[i][2] + dp[idx]; + int notTake = dp[i + 1]; + dp[i] = Math.Max(take, notTake); + } + return dp[0]; + } +} diff --git a/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.dart b/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.dart new file mode 100644 index 00000000..aeae4b9d --- /dev/null +++ b/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.dart @@ -0,0 +1,31 @@ +class Solution { + int jobScheduling(List startTime, List endTime, List profit) { + int n = startTime.length; + List> jobs = List.generate(n, (i) => [startTime[i], endTime[i], profit[i]]); + jobs.sort((a, b) => a[0].compareTo(b[0])); + + List starts = jobs.map((j) => j[0]).toList(); + List dp = List.filled(n + 1, 0); + + int binarySearch(List arr, int target, int left) { + int lo = left, hi = arr.length; + while (lo < hi) { + int mid = lo + (hi - lo) ~/ 2; + if (arr[mid] >= target) { + hi = mid; + } else { + lo = mid + 1; + } + } + return lo; + } + + for (int i = n - 1; i >= 0; i--) { + int idx = binarySearch(starts, jobs[i][1], i + 1); + int take = jobs[i][2] + dp[idx]; + int notTake = dp[i + 1]; + dp[i] = take > notTake ? take : notTake; + } + return dp[0]; + } +} diff --git a/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.go b/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.go new file mode 100644 index 00000000..7d77fc43 --- /dev/null +++ b/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.go @@ -0,0 +1,31 @@ +func jobScheduling(startTime []int, endTime []int, profit []int) int { + n := len(startTime) + type Job struct { + start, end, profit int + } + jobs := make([]Job, n) + for i := 0; i < n; i++ { + jobs[i] = Job{startTime[i], endTime[i], profit[i]} + } + sort.Slice(jobs, func(i, j int) bool { + return jobs[i].start < jobs[j].start + }) + + starts := make([]int, n) + for i := 0; i < n; i++ { + starts[i] = jobs[i].start + } + + dp := make([]int, n+1) + for i := n - 1; i >= 0; i-- { + idx := sort.SearchInts(starts[i+1:], jobs[i].end) + i + 1 + take := jobs[i].profit + dp[idx] + notTake := dp[i+1] + if take > notTake { + dp[i] = take + } else { + dp[i] = notTake + } + } + return dp[0] +} diff --git a/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.java b/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.java new file mode 100644 index 00000000..b14c071b --- /dev/null +++ b/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.java @@ -0,0 +1,29 @@ +class Solution { + public int jobScheduling(int[] startTime, int[] endTime, int[] profit) { + int n = startTime.length; + int[][] jobs = new int[n][3]; + for (int i = 0; i < n; i++) { + jobs[i][0] = startTime[i]; + jobs[i][1] = endTime[i]; + jobs[i][2] = profit[i]; + } + java.util.Arrays.sort(jobs, (a, b) -> Integer.compare(a[0], b[0])); + + int[] starts = new int[n]; + for (int i = 0; i < n; i++) { + starts[i] = jobs[i][0]; + } + + int[] dp = new int[n + 1]; + for (int i = n - 1; i >= 0; i--) { + int idx = java.util.Arrays.binarySearch(starts, i + 1, n, jobs[i][1]); + if (idx < 0) { + idx = -idx - 1; + } + int take = jobs[i][2] + dp[idx]; + int notTake = dp[i + 1]; + dp[i] = Math.max(take, notTake); + } + return dp[0]; + } +} diff --git a/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.kt b/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.kt new file mode 100644 index 00000000..6fd0b789 --- /dev/null +++ b/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.kt @@ -0,0 +1,19 @@ +class Solution { + fun jobScheduling(startTime: IntArray, endTime: IntArray, profit: IntArray): Int { + val n = startTime.size + val jobs = Array(n) { i -> intArrayOf(startTime[i], endTime[i], profit[i]) } + jobs.sortBy { it[0] } + + val starts = IntArray(n) { jobs[it][0] } + val dp = IntArray(n + 1) + + for (i in n - 1 downTo 0) { + var idx = starts.binarySearch(jobs[i][1], fromIndex = i + 1, toIndex = n) + if (idx < 0) idx = -idx - 1 + val take = jobs[i][2] + dp[idx] + val notTake = dp[i + 1] + dp[i] = maxOf(take, notTake) + } + return dp[0] + } +} diff --git a/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.py b/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.py new file mode 100644 index 00000000..a42a4f0f --- /dev/null +++ b/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.py @@ -0,0 +1,48 @@ +class Pair: + def __init__(self, start, end, profit): + self.start = start + self.end = end + self.profit = profit + + +class Solution: + def BS(self, index, n, arr): + l, h = index + 1, n - 1 + idx = -1 + + while l <= h: + mid = l + (h - l) // 2 + + if arr[mid].start >= arr[index].end: + idx = mid + h = mid - 1 + else: + l = mid + 1 + + return idx + + def dfs(self, index, n, arr): + if index >= n or index == -1: + return 0 + if self.dp[index] != -1: + return self.dp[index] + + notTake = self.dfs(index + 1, n, arr) + + # next index whose start time is just greater than endTime of current index + nextIndex = self.BS(index, n, arr) + take = arr[index].profit + self.dfs(nextIndex, n, arr) + + self.dp[index] = max(take, notTake) + return self.dp[index] + + def jobScheduling(self, start, end, profit): + n = len(start) + arr = [] + self.dp = [-1] * (n + 1) + + for i in range(n): + arr.append(Pair(start[i], end[i], profit[i])) + + arr.sort(key=lambda x: x.start) + return self.dfs(0, n, arr) diff --git a/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.py2 b/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.py2 new file mode 100644 index 00000000..117c0fe8 --- /dev/null +++ b/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.py2 @@ -0,0 +1,22 @@ +class Solution(object): + def jobScheduling(self, startTime, endTime, profit): + """ + :type startTime: List[int] + :type endTime: List[int] + :type profit: List[int] + :rtype: int + """ + n = len(startTime) + jobs = sorted(zip(startTime, endTime, profit), key=lambda x: x[0]) + startTime = [j[0] for j in jobs] + endTime = [j[1] for j in jobs] + profit = [j[2] for j in jobs] + + import bisect + dp = [0] * (n + 1) + for i in range(n - 1, -1, -1): + idx = bisect.bisect_left(startTime, endTime[i], i + 1) + take = profit[i] + dp[idx] + notTake = dp[i + 1] + dp[i] = max(take, notTake) + return dp[0] diff --git a/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.rb b/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.rb new file mode 100644 index 00000000..3e1c8eac --- /dev/null +++ b/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.rb @@ -0,0 +1,22 @@ +# @param {Integer[]} start_time +# @param {Integer[]} end_time +# @param {Integer[]} profit +# @return {Integer} +def job_scheduling(start_time, end_time, profit) + n = start_time.length + jobs = (0...n).map { |i| [start_time[i], end_time[i], profit[i]] } + jobs.sort_by! { |j| j[0] } + start_time = jobs.map { |j| j[0] } + end_time = jobs.map { |j| j[1] } + profit = jobs.map { |j| j[2] } + + dp = Array.new(n + 1, 0) + (n - 1).downto(0) do |i| + idx = start_time.bsearch_index { |s| s >= end_time[i] } + idx = n if idx.nil? + take = profit[i] + dp[idx] + not_take = dp[i + 1] + dp[i] = [take, not_take].max + end + dp[0] +end diff --git a/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.rs b/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.rs new file mode 100644 index 00000000..06a0939c --- /dev/null +++ b/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.rs @@ -0,0 +1,21 @@ +impl Solution { + pub fn job_scheduling(start_time: Vec, end_time: Vec, profit: Vec) -> i32 { + let n = start_time.len(); + let mut jobs: Vec<(i32, i32, i32)> = (0..n) + .map(|i| (start_time[i], end_time[i], profit[i])) + .collect(); + jobs.sort_by_key(|j| j.0); + + let starts: Vec = jobs.iter().map(|j| j.0).collect(); + let mut dp = vec![0; n + 1]; + + for i in (0..n).rev() { + let target = jobs[i].1; + let idx = starts.partition_point(|&start| start < target); + let take = jobs[i].2 + dp[idx]; + let not_take = dp[i + 1]; + dp[i] = take.max(not_take); + } + dp[0] + } +} diff --git a/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.swift b/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.swift new file mode 100644 index 00000000..14bcec01 --- /dev/null +++ b/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.swift @@ -0,0 +1,34 @@ +class Solution { + func jobScheduling(_ startTime: [Int], _ endTime: [Int], _ profit: [Int]) -> Int { + let n = startTime.count + var jobs = [(Int, Int, Int)]() + for i in 0.. Int { + var lo = from, hi = n + while lo < hi { + let mid = lo + (hi - lo) / 2 + if starts[mid] >= target { + hi = mid + } else { + lo = mid + 1 + } + } + return lo + } + + for i in stride(from: n - 1, through: 0, by: -1) { + let idx = binarySearch(jobs[i].1, i + 1) + let take = jobs[i].2 + dp[idx] + let notTake = dp[i + 1] + dp[i] = max(take, notTake) + } + return dp[0] + } +} diff --git a/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.ts b/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.ts new file mode 100644 index 00000000..a5b7e1d6 --- /dev/null +++ b/tests/1001-1500/1235. maximum-profit-in-job-scheduling/sol.ts @@ -0,0 +1,37 @@ +function jobScheduling( + startTime: number[], + endTime: number[], + profit: number[], +): number { + const n = startTime.length; + const jobs: [number, number, number][] = []; + for (let i = 0; i < n; i++) { + jobs.push([startTime[i], endTime[i], profit[i]]); + } + jobs.sort((a, b) => a[0] - b[0]); + + const starts = jobs.map((j) => j[0]); + const dp: number[] = new Array(n + 1).fill(0); + + const binarySearch = (target: number, from: number): number => { + let lo = from, + hi = n; + while (lo < hi) { + const mid = lo + Math.floor((hi - lo) / 2); + if (starts[mid] >= target) { + hi = mid; + } else { + lo = mid + 1; + } + } + return lo; + }; + + for (let i = n - 1; i >= 0; i--) { + const idx = binarySearch(jobs[i][1], i + 1); + const take = jobs[i][2] + dp[idx]; + const notTake = dp[i + 1]; + dp[i] = Math.max(take, notTake); + } + return dp[0]; +} diff --git a/tests/1001-1500/1238. circular-permutation-in-binary-representation/manifest.yaml b/tests/1001-1500/1238. circular-permutation-in-binary-representation/manifest.yaml new file mode 100644 index 00000000..a6104819 --- /dev/null +++ b/tests/1001-1500/1238. circular-permutation-in-binary-representation/manifest.yaml @@ -0,0 +1,228 @@ +entry: + id: 1238 + title: circular-permutation-in-binary-representation + params: + n: + type: int + start_value: + type: int + call: + cpp: "Solution().circularPermutation({n}, {start_value})" + rust: "Solution::circular_permutation({n}, {start_value})" + python3: "Solution().circularPermutation({n}, {start_value})" + python2: "Solution().circularPermutation({n}, {start_value})" + ruby: "circular_permutation({n}, {start_value})" + java: "new Solution().circularPermutation({n}, {start_value})" + csharp: "new Solution().CircularPermutation({n}, {start_value})" + kotlin: "Solution().circularPermutation({n}, {start_value})" + go: "circularPermutation({n}, {start_value})" + dart: "Solution().circularPermutation({n}, {start_value})" + swift: "Solution().circularPermutation({n}, {start_value})" + typescript: "circularPermutation({n}, {start_value})" +judge: + type: exact +limits: + time_ms: 1500 + memory_mb: 256 +oracle: + python3: + call: "Checker().circularPermutation(n, start_value, {result})" + checker: | + class Checker: + def circularPermutation(self, n, start_value, result): + if type(n) is not int or not 1 <= n <= 16: + return False + if type(start_value) is not int or not 0 <= start_value < (1 << n): + return False + if not isinstance(result, list) or len(result) != (1 << n): + return False + if not all(type(value) is int for value in result): + return False + if result[0] != start_value or set(result) != set(range(1 << n)): + return False + return all( + (result[index] ^ result[(index + 1) % len(result)]).bit_count() == 1 + for index in range(len(result)) + ) +seed: 1238 +tests: + - name: example_n2_start3 + in: + n: 2 + start_value: 3 + - name: example_n3_start2 + in: + n: 3 + start_value: 2 + - name: n1_start0 + in: + n: 1 + start_value: 0 + - name: n1_start1 + in: + n: 1 + start_value: 1 + - name: n2_start0 + in: + n: 2 + start_value: 0 + - name: n3_start0 + in: + n: 3 + start_value: 0 + - name: n3_start7 + in: + n: 3 + start_value: 7 + - name: n4_start0 + in: + n: 4 + start_value: 0 + - name: n4_start9 + in: + n: 4 + start_value: 9 + - name: n4_start15 + in: + n: 4 + start_value: 15 + - name: n5_start16 + in: + n: 5 + start_value: 16 + - name: n5_start31 + in: + n: 5 + start_value: 31 + - name: n6_start0 + in: + n: 6 + start_value: 0 + - name: n6_start21 + in: + n: 6 + start_value: 21 + - name: n6_start63 + in: + n: 6 + start_value: 63 + - name: n7_start42 + in: + n: 7 + start_value: 42 + - name: n7_start127 + in: + n: 7 + start_value: 127 + - name: n8_start1 + in: + n: 8 + start_value: 1 + - name: n8_start128 + in: + n: 8 + start_value: 128 + - name: n8_start255 + in: + n: 8 + start_value: 255 + - name: n9_start73 + in: + n: 9 + start_value: 73 + - name: n9_start511 + in: + n: 9 + start_value: 511 + - name: n10_start0 + in: + n: 10 + start_value: 0 + - name: n10_start700 + in: + n: 10 + start_value: 700 + - name: n10_start1023 + in: + n: 10 + start_value: 1023 + - name: n11_start1365 + in: + n: 11 + start_value: 1365 + - name: n12_start2048 + in: + n: 12 + start_value: 2048 + - name: n12_start4095 + in: + n: 12 + start_value: 4095 + - name: n13_start4096 + in: + n: 13 + start_value: 4096 + - name: n13_start8191 + in: + n: 13 + start_value: 8191 + - name: n14_start12345 + in: + n: 14 + start_value: 12345 + - name: n15_start16384 + in: + n: 15 + start_value: 16384 + - name: n15_start32767 + in: + n: 15 + start_value: 32767 + - name: n16_start0_stress + in: + n: 16 + start_value: 0 + - name: n16_start65535_stress + in: + n: 16 + start_value: 65535 + - name: generated_n11_stress + seed: 101 + in: + n: 11 + start_value: + gen: int + min: 0 + max: 2047 + - name: generated_n12_stress + seed: 202 + in: + n: 12 + start_value: + gen: int + min: 0 + max: 4095 + - name: generated_n13_stress + seed: 303 + in: + n: 13 + start_value: + gen: int + min: 0 + max: 8191 + - name: generated_n14_stress + seed: 404 + in: + n: 14 + start_value: + gen: int + min: 0 + max: 16383 + - name: generated_n15_stress + seed: 505 + in: + n: 15 + start_value: + gen: int + min: 0 + max: 32767 diff --git a/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.cpp b/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.cpp new file mode 100644 index 00000000..ac4db70b --- /dev/null +++ b/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + vector circularPermutation(int n, int start) { + vector result; + for (int i = 0; i < (1 << n); i++) { + result.push_back(start ^ (i ^ (i >> 1))); + } + return result; + } +}; diff --git a/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.cs b/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.cs new file mode 100644 index 00000000..0c9dca2c --- /dev/null +++ b/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.cs @@ -0,0 +1,9 @@ +public class Solution { + public IList CircularPermutation(int n, int start) { + IList result = new List(); + for (int i = 0; i < (1 << n); i++) { + result.Add(start ^ (i ^ (i >> 1))); + } + return result; + } +} diff --git a/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.dart b/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.dart new file mode 100644 index 00000000..ad8fc669 --- /dev/null +++ b/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.dart @@ -0,0 +1,6 @@ +class Solution { + List circularPermutation(int n, int start) { + final int size = 1 << n; + return List.generate(size, (int i) => start ^ (i ^ (i >> 1))); + } +} diff --git a/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.go b/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.go new file mode 100644 index 00000000..c9651e7e --- /dev/null +++ b/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.go @@ -0,0 +1,8 @@ +func circularPermutation(n int, start int) []int { + size := 1 << n + result := make([]int, size) + for i := 0; i < size; i++ { + result[i] = start ^ (i ^ (i >> 1)) + } + return result +} diff --git a/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.java b/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.java new file mode 100644 index 00000000..b1ffc8e2 --- /dev/null +++ b/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.java @@ -0,0 +1,9 @@ +class Solution { + public List circularPermutation(int n, int start) { + List result = new ArrayList<>(); + for (int i = 0; i < (1 << n); i++) { + result.add(start ^ (i ^ (i >> 1))); + } + return result; + } +} diff --git a/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.kt b/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.kt new file mode 100644 index 00000000..abf24262 --- /dev/null +++ b/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.kt @@ -0,0 +1,5 @@ +class Solution { + fun circularPermutation(n: Int, start: Int): List { + return (0 until (1 shl n)).map { i -> start xor (i xor (i shr 1)) } + } +} diff --git a/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.py b/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.py new file mode 100644 index 00000000..069c5dc0 --- /dev/null +++ b/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.py @@ -0,0 +1,8 @@ +class Solution(object): + def circularPermutation(self, n, start): + """ + :type n: int + :type start: int + :rtype: List[int] + """ + return [start ^ (i ^ (i >> 1)) for i in range(1 << n)] diff --git a/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.py2 b/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.py2 new file mode 100644 index 00000000..069c5dc0 --- /dev/null +++ b/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.py2 @@ -0,0 +1,8 @@ +class Solution(object): + def circularPermutation(self, n, start): + """ + :type n: int + :type start: int + :rtype: List[int] + """ + return [start ^ (i ^ (i >> 1)) for i in range(1 << n)] diff --git a/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.rb b/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.rb new file mode 100644 index 00000000..426f7ce5 --- /dev/null +++ b/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.rb @@ -0,0 +1,6 @@ +# @param {Integer} n +# @param {Integer} start +# @return {Integer[]} +def circular_permutation(n, start) + (0...(1 << n)).map { |i| start ^ (i ^ (i >> 1)) } +end diff --git a/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.rs b/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.rs new file mode 100644 index 00000000..dca74e97 --- /dev/null +++ b/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.rs @@ -0,0 +1,5 @@ +impl Solution { + pub fn circular_permutation(n: i32, start: i32) -> Vec { + (0..(1 << n)).map(|i| start ^ (i ^ (i >> 1))).collect() + } +} diff --git a/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.swift b/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.swift new file mode 100644 index 00000000..c81f2486 --- /dev/null +++ b/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.swift @@ -0,0 +1,9 @@ +class Solution { + func circularPermutation(_ n: Int, _ start: Int) -> [Int] { + var result = [Int]() + for i in 0..<(1 << n) { + result.append(start ^ (i ^ (i >> 1))) + } + return result + } +} diff --git a/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.ts b/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.ts new file mode 100644 index 00000000..359a3040 --- /dev/null +++ b/tests/1001-1500/1238. circular-permutation-in-binary-representation/sol.ts @@ -0,0 +1,7 @@ +function circularPermutation(n: number, start: number): number[] { + const result: number[] = []; + for (let i = 0; i < 1 << n; i++) { + result.push(start ^ (i ^ (i >> 1))); + } + return result; +} diff --git a/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/manifest.yaml b/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/manifest.yaml new file mode 100644 index 00000000..fbead94a --- /dev/null +++ b/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/manifest.yaml @@ -0,0 +1,344 @@ +entry: + id: 1239 + title: "maximum-length-of-a-concatenated-string-with-unique-characters" + params: + arr: + type: array + items: + type: string + call: + cpp: "Solution().maxLength({arr})" + rust: "Solution::max_length({arr})" + python3: "Solution().maxLength({arr})" + python2: "Solution().maxLength({arr})" + ruby: "max_length({arr})" + java: "new Solution().maxLength({arr})" + csharp: "new Solution().MaxLength({arr})" + kotlin: "Solution().maxLength({arr})" + go: "maxLength({arr})" + dart: "Solution().maxLength({arr})" + swift: "Solution().maxLength({arr})" + typescript: "maxLength({arr})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().maxLength(arr, {result})" + checker: | + class Checker: + def maxLength(self, arr, result): + masks = [] + for word in arr: + mask = 0 + for ch in word: + bit = 1 << (ord(ch) - 97) + if mask & bit: + break + mask |= bit + else: + masks.append(mask) + best = 0 + def dfs(i, used, length): + nonlocal best + best = max(best, length) + for j in range(i, len(masks)): + if not used & masks[j]: + dfs(j + 1, used | masks[j], length + masks[j].bit_count()) + dfs(0, 0, 0) + return result == best + +seed: 1239 + +tests: + - name: "example-un-iq-ue" + in: + arr: ["un", "iq", "ue"] + out: 4 + - name: "example-cha-r-act-ers" + in: + arr: ["cha", "r", "act", "ers"] + out: 6 + - name: "example-alphabet" + in: + arr: ["abcdefghijklmnopqrstuvwxyz"] + out: 26 + - name: "single-letter" + in: + arr: ["a"] + out: 1 + - name: "single-duplicate-word" + in: + arr: ["aa"] + out: 0 + - name: "single-max-word" + in: + arr: ["abcdefghijklmnopqrstuvwxy"] + out: 25 + - name: "all-duplicate-items" + in: + arr: ["a", "a", "a"] + out: 1 + - name: "disjoint-pair" + in: + arr: ["abc", "def"] + out: 6 + - name: "overlap-forces-choice" + in: + arr: ["abc", "cde", "fgh"] + out: 6 + - name: "later-best-subsequence" + in: + arr: ["ab", "bc", "def", "gh"] + out: 7 + - name: "invalid-between-valid" + in: + arr: ["ab", "cc", "de"] + out: 4 + - name: "invalid-longer-than-valid" + in: + arr: ["abcdefghijkl", "mmmmmmmmmm", "nopqrstuvw"] + out: 22 + - name: "one-character-chain" + in: + arr: ["a", "b", "c", "d", "e"] + out: 5 + - name: "reverse-overlap-chain" + in: + arr: ["ab", "cd", "bc", "ef"] + out: 6 + - name: "nested-words" + in: + arr: ["a", "ab", "abc", "def"] + out: 6 + - name: "same-character-blocks" + in: + arr: + [ + "ab", + "cd", + "ef", + "gh", + "ij", + "kl", + "mn", + "op", + "qr", + "st", + "uv", + "wx", + "yz", + ] + out: 26 + - name: "alternating-overlaps" + in: + arr: ["ab", "bc", "cd", "de", "ef", "fg"] + out: 6 + - name: "three-way-optimum" + in: + arr: ["abc", "def", "adg", "hij", "klm"] + out: 12 + - name: "shorter-compatible-after-long" + in: + arr: ["abcd", "ef", "ghij", "a", "kl"] + out: 12 + - name: "empty-effective-set" + in: + arr: ["aa", "bb", "cc", "dd"] + out: 0 + - name: "case-lowercase-boundary" + in: + arr: + [ + "az", + "by", + "cx", + "dw", + "ev", + "fu", + "gt", + "hs", + "ir", + "jq", + "kp", + "lo", + "mn", + ] + out: 26 + - name: "best-skips-first" + in: + arr: ["abcdef", "abc", "ghijkl", "mnop"] + out: 16 + - name: "best-skips-middle" + in: + arr: ["ab", "bcdef", "gh", "c", "ijk"] + out: 10 + - name: "best-skips-last" + in: + arr: ["abc", "def", "ghi", "abcdefghi"] + out: 9 + - name: "duplicate-inside-late-word" + in: + arr: ["ab", "cdef", "gg", "hijk"] + out: 10 + - name: "four-compatible-groups" + in: + arr: ["ab", "cd", "ef", "gh", "ai", "jk"] + out: 10 + - name: "long-overlap-options" + in: + arr: ["abcdefgh", "ijklmnop", "abcdefgq", "rstuvwxy"] + out: 24 + - name: "sixteen-singletons" + in: + arr: + [ + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + ] + out: 16 + - name: "sixteen-mixed-overlaps" + in: + arr: + [ + "ab", + "cd", + "ef", + "gh", + "ij", + "kl", + "mn", + "op", + "aq", + "cr", + "es", + "gt", + "iu", + "kv", + "mw", + "nx", + ] + out: 18 + - name: "long-valid-plus-singletons" + in: + arr: + [ + "abcdefghijkl", + "m", + "n", + "o", + "p", + "q", + "r", + "s", + "t", + "u", + "v", + "w", + "x", + "y", + "z", + "aa", + ] + out: 26 + - name: "partitioned-alphabet" + in: + arr: ["abc", "defg", "hijkl", "mnopq", "rstuv", "wxyz"] + out: 26 + - name: "competing-partitions" + in: + arr: + [ + "abcd", + "efgh", + "ijkl", + "mnop", + "qrst", + "uvwx", + "aceg", + "bdfh", + "ikmo", + "jlnp", + ] + out: 24 + - name: "many-invalid-words" + in: + arr: ["zz", "yy", "xx", "ww", "ab", "cc", "de", "ff", "gh"] + out: 6 + - name: "single-best-combination" + in: + arr: ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "az"] + out: 25 + - name: "full-alphabet-two-halves" + in: + arr: ["abcdefghijklm", "nopqrstuvwxyz"] + out: 26 + - name: "generated-max-full-alphabet-1" + seed: 1240 + in: + arr: + gen: "array" + len: 16 + of: + gen: "str" + len: 26 + alphabet: "abcdefghijklmnopqrstuvwxyz" + - name: "generated-max-full-alphabet-2" + seed: 1241 + in: + arr: + gen: "array" + len: 16 + of: + gen: "str" + len: 26 + alphabet: "abcdefghijklmnopqrstuvwxyz" + - name: "generated-max-dense-small-alphabet" + seed: 1242 + in: + arr: + gen: "array" + len: 16 + of: + gen: "str" + len: 26 + alphabet: "abcd" + - name: "generated-max-half-alphabet" + seed: 1243 + in: + arr: + gen: "array" + len: 16 + of: + gen: "str" + len: 26 + alphabet: "abcdefghijklm" + - name: "generated-max-sparse-alphabet" + seed: 1244 + in: + arr: + gen: "array" + len: 16 + of: + gen: "str" + len: 26 + alphabet: "acegikmoqsuwy" diff --git a/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.cpp b/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.cpp new file mode 100644 index 00000000..46c8c5be --- /dev/null +++ b/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int maxLength(vector& arr) { + int ans = 0; + int n = arr.size(); + + function dfs = [&](int i, string path) { + ans = max(ans, (int)path.size()); + for (int j = i; j < n; j++) { + string s = arr[j]; + unordered_set us(s.begin(), s.end()); + if (us.size() != s.size()) continue; + bool hasCommon = false; + for (char c : s) { + if (path.find(c) != string::npos) { + hasCommon = true; + break; + } + } + if (hasCommon) continue; + dfs(j + 1, path + s); + } + }; + + dfs(0, ""); + return ans; + } +}; diff --git a/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.cs b/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.cs new file mode 100644 index 00000000..878e2989 --- /dev/null +++ b/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.cs @@ -0,0 +1,26 @@ +public class Solution { + public int MaxLength(IList arr) { + int ans = 0; + int n = arr.Count; + + void dfs(int i, string path) { + ans = Math.Max(ans, path.Length); + for (int j = i; j < n; j++) { + string s = arr[j]; + if (new HashSet(s).Count != s.Length) continue; + bool hasCommon = false; + foreach (char c in s) { + if (path.IndexOf(c) != -1) { + hasCommon = true; + break; + } + } + if (hasCommon) continue; + dfs(j + 1, path + s); + } + } + + dfs(0, ""); + return ans; + } +} diff --git a/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.dart b/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.dart new file mode 100644 index 00000000..abbe3315 --- /dev/null +++ b/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.dart @@ -0,0 +1,34 @@ +class Solution { + int maxLength(List arr) { + int ans = 0; + + bool isUnique(String s) { + int mask = 0; + for (int i = 0; i < s.length; i++) { + int bit = 1 << (s.codeUnitAt(i) - 'a'.codeUnitAt(0)); + if ((mask & bit) != 0) return false; + mask |= bit; + } + return true; + } + + bool hasCommon(String a, String b) { + for (int i = 0; i < b.length; i++) { + if (a.contains(b[i])) return true; + } + return false; + } + + void dfs(int i, String path) { + if (path.length > ans) ans = path.length; + for (int j = i; j < arr.length; j++) { + String s = arr[j]; + if (!isUnique(s) || hasCommon(path, s)) continue; + dfs(j + 1, path + s); + } + } + + dfs(0, ""); + return ans; + } +} diff --git a/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.go b/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.go new file mode 100644 index 00000000..aed8e944 --- /dev/null +++ b/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.go @@ -0,0 +1,43 @@ +func maxLength(arr []string) int { + ans := 0 + + isUnique := func(s string) bool { + mask := 0 + for _, c := range s { + bit := 1 << (c - 'a') + if mask&bit != 0 { + return false + } + mask |= bit + } + return true + } + + hasCommon := func(a, b string) bool { + for _, c := range b { + for _, d := range a { + if c == d { + return true + } + } + } + return false + } + + var dfs func(int, string) + dfs = func(i int, path string) { + if len(path) > ans { + ans = len(path) + } + for j := i; j < len(arr); j++ { + s := arr[j] + if !isUnique(s) || hasCommon(path, s) { + continue + } + dfs(j+1, path+s) + } + } + + dfs(0, "") + return ans +} diff --git a/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.java b/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.java new file mode 100644 index 00000000..df41d2f1 --- /dev/null +++ b/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.java @@ -0,0 +1,35 @@ +class Solution { + private int ans; + + public int maxLength(String[] arr) { + ans = 0; + dfs(0, "", arr); + return ans; + } + + private void dfs(int i, String path, String[] arr) { + ans = Math.max(ans, path.length()); + for (int j = i; j < arr.length; j++) { + String s = arr[j]; + if (!isUnique(s) || hasCommon(path, s)) continue; + dfs(j + 1, path + s, arr); + } + } + + private boolean isUnique(String s) { + int mask = 0; + for (char c : s.toCharArray()) { + int bit = 1 << (c - 'a'); + if ((mask & bit) != 0) return false; + mask |= bit; + } + return true; + } + + private boolean hasCommon(String a, String b) { + for (char c : b.toCharArray()) { + if (a.indexOf(c) != -1) return true; + } + return false; + } +} diff --git a/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.kt b/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.kt new file mode 100644 index 00000000..f2bb8372 --- /dev/null +++ b/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.kt @@ -0,0 +1,18 @@ +class Solution { + private var ans = 0 + + fun maxLength(arr: Array): Int { + ans = 0 + dfs(0, "", arr) + return ans + } + + private fun dfs(i: Int, path: String, arr: Array) { + ans = maxOf(ans, path.length) + for (j in i until arr.size) { + val s = arr[j] + if (s.toSet().size != s.length || path.toSet().intersect(s.toSet()).isNotEmpty()) continue + dfs(j + 1, path + s, arr) + } + } +} diff --git a/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.py b/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.py new file mode 100644 index 00000000..de6a081e --- /dev/null +++ b/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.py @@ -0,0 +1,15 @@ +class Solution: + def maxLength(self, arr: List[str]) -> int: + n = len(arr) + ans = 0 + + def dfs(i, path): + nonlocal ans + ans = max(ans, len(path)) + for j in range(i, n): + if len(set(arr[j])) != len(arr[j]) or set(path) & set(arr[j]): + continue + dfs(j + 1, path + arr[j]) + + dfs(0, "") + return ans diff --git a/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.py2 b/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.py2 new file mode 100644 index 00000000..e4837c69 --- /dev/null +++ b/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.py2 @@ -0,0 +1,18 @@ +class Solution(object): + def maxLength(self, arr): + """ + :type arr: List[str] + :rtype: int + """ + n = len(arr) + self.ans = 0 + + def dfs(i, path): + self.ans = max(self.ans, len(path)) + for j in range(i, n): + if len(set(arr[j])) != len(arr[j]) or set(path) & set(arr[j]): + continue + dfs(j + 1, path + arr[j]) + + dfs(0, "") + return self.ans diff --git a/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.rb b/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.rb new file mode 100644 index 00000000..e1880d12 --- /dev/null +++ b/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.rb @@ -0,0 +1,18 @@ +# @param {String[]} arr +# @return {Integer} +def max_length(arr) + n = arr.length + @ans = 0 + + dfs = lambda do |i, path| + @ans = [@ans, path.length].max + (i...n).each do |j| + s = arr[j] + next if s.chars.uniq.length != s.length || (path.chars & s.chars).any? + dfs.call(j + 1, path + s) + end + end + + dfs.call(0, "") + @ans +end diff --git a/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.rs b/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.rs new file mode 100644 index 00000000..4ed23d8f --- /dev/null +++ b/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.rs @@ -0,0 +1,36 @@ +impl Solution { + pub fn max_length(arr: Vec) -> i32 { + let mut ans = 0; + + fn is_unique(s: &str) -> bool { + let mut mask = 0u32; + for c in s.chars() { + let bit = 1 << (c as u32 - 'a' as u32); + if mask & bit != 0 { + return false; + } + mask |= bit; + } + true + } + + fn has_common(a: &str, b: &str) -> bool { + b.chars().any(|c| a.contains(c)) + } + + fn dfs(i: usize, path: &str, arr: &Vec, ans: &mut i32) { + *ans = (*ans).max(path.len() as i32); + for j in i..arr.len() { + let s = &arr[j]; + if !is_unique(s) || has_common(path, s) { + continue; + } + let new_path = format!("{}{}", path, s); + dfs(j + 1, &new_path, arr, ans); + } + } + + dfs(0, "", &arr, &mut ans); + ans + } +} diff --git a/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.swift b/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.swift new file mode 100644 index 00000000..5c37813a --- /dev/null +++ b/tests/1001-1500/1239. maximum-length-of-a-concatenated-string-with-unique-characters/sol.swift @@ -0,0 +1,26 @@ +class Solution { + func maxLength(_ arr: [String]) -> Int { + var ans = 0 + let n = arr.count + + func isUnique(_ s: String) -> Bool { + return Set(s).count == s.count + } + + func hasCommon(_ a: String, _ b: String) -> Bool { + return !Set(a).intersection(Set(b)).isEmpty + } + + func dfs(_ i: Int, _ path: String) { + ans = max(ans, path.count) + for j in i..= best[0]: + return + level = min(skyline) + if level == height: + best[0] = used + return + start = skyline.index(level) + end = start + while end < width and skyline[end] == level: + end += 1 + for side in range(min(end - start, height - level), 0, -1): + for column in range(start, start + side): + skyline[column] += side + search(used + 1) + for column in range(start, start + side): + skyline[column] -= side + + search(0) + return result == best[0] +seed: 1240 +tests: + - name: unit-square + in: + n: 1 + m: 1 + out: 1 + - name: horizontal-strip-maximum + in: + n: 1 + m: 13 + out: 13 + - name: vertical-strip-maximum + in: + n: 13 + m: 1 + out: 13 + - name: two-by-three-example + in: + n: 2 + m: 3 + out: 3 + - name: two-by-four-half-squares + in: + n: 2 + m: 4 + out: 2 + - name: two-by-five-remainder + in: + n: 2 + m: 5 + out: 4 + - name: two-by-thirteen-strip-pattern + in: + n: 2 + m: 13 + out: 8 + - name: three-by-four-coprime + in: + n: 3 + m: 4 + out: 4 + - name: three-by-five-coprime + in: + n: 3 + m: 5 + out: 4 + - name: three-by-six-equal-halves + in: + n: 3 + m: 6 + out: 2 + - name: three-by-nine-thirds + in: + n: 3 + m: 9 + out: 3 + - name: four-by-five-near-square + in: + n: 4 + m: 5 + out: 5 + - name: four-by-twelve-thirds + in: + n: 4 + m: 12 + out: 3 + - name: five-by-eight-example + in: + n: 5 + m: 8 + out: 5 + - name: five-by-eleven-coprime + in: + n: 5 + m: 11 + out: 6 + - name: five-by-thirteen-large-coprime + in: + n: 5 + m: 13 + out: 6 + - name: six-by-seven-near-square + in: + n: 6 + m: 7 + out: 5 + - name: six-by-eleven-large-coprime + in: + n: 6 + m: 11 + out: 6 + - name: seven-by-eight-near-square + in: + n: 7 + m: 8 + out: 7 + - name: seven-by-ten-coprime + in: + n: 7 + m: 10 + out: 6 + - name: seven-by-thirteen-maximum-width + in: + n: 7 + m: 13 + out: 6 + - name: eight-by-nine-near-square + in: + n: 8 + m: 9 + out: 7 + - name: eight-by-twelve-common-divisor + in: + n: 8 + m: 12 + out: 3 + - name: eight-by-thirteen-maximum-width + in: + n: 8 + m: 13 + out: 6 + - name: nine-by-ten-near-square + in: + n: 9 + m: 10 + out: 6 + - name: nine-by-twelve-common-divisor + in: + n: 9 + m: 12 + out: 4 + - name: nine-by-thirteen-maximum-width + in: + n: 9 + m: 13 + out: 7 + - name: ten-by-eleven-near-square + in: + n: 10 + m: 11 + out: 6 + - name: ten-by-twelve-common-divisor + in: + n: 10 + m: 12 + out: 5 + - name: ten-by-thirteen-maximum-width + in: + n: 10 + m: 13 + out: 7 + - name: eleven-by-thirteen-example + in: + n: 11 + m: 13 + out: 6 + - name: thirteen-by-eleven-example-reversed + in: + n: 13 + m: 11 + out: 6 + - name: eleven-by-twelve-near-maximum + in: + n: 11 + m: 12 + out: 7 + - name: twelve-by-thirteen-maximum-near-square + in: + n: 12 + m: 13 + out: 7 + - name: maximum-square + in: + n: 13 + m: 13 + out: 1 + - name: generated-large-both-dimensions + seed: 124001 + in: + n: + gen: "int" + min: 8 + max: 13 + m: + gen: "int" + min: 8 + max: 13 + - name: generated-large-wide-rectangle + seed: 124002 + in: + n: + gen: "int" + min: 8 + max: 12 + m: + gen: "int" + min: 13 + max: 13 + - name: generated-large-tall-rectangle + seed: 124003 + in: + n: + gen: "int" + min: 13 + max: 13 + m: + gen: "int" + min: 8 + max: 12 + - name: generated-maximum-range + seed: 124004 + in: + n: + gen: "int" + min: 10 + max: 13 + m: + gen: "int" + min: 10 + max: 13 + - name: generated-large-asymmetric + seed: 124005 + in: + n: + gen: "int" + min: 7 + max: 10 + m: + gen: "int" + min: 11 + max: 13 diff --git a/tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.cpp b/tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.cpp new file mode 100644 index 00000000..46091d93 --- /dev/null +++ b/tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + int tilingRectangle(int n, int m) { + if (max(m, n) == 13 && min(m, n) == 11) { + return 6; + } + + vector> memo(14, vector(14, 0)); + return deeper(m, n, memo); + } + +private: + int deeper(int a, int b, vector>& memo) { + if (a == b) { + return 1; + } + if (min(a, b) == 1) { + return max(a, b); + } + if (a < b) { + return deeper(b, a, memo); + } + + if (memo[a][b] != 0) { + return memo[a][b]; + } + + int best = INT_MAX; + for (int i = 1; i < a; i++) { + best = min(best, deeper(i, b, memo) + deeper(a - i, b, memo)); + } + for (int i = 1; i < b; i++) { + best = min(best, deeper(a, i, memo) + deeper(a, b - i, memo)); + } + + memo[a][b] = best; + return best; + } +}; diff --git a/tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.cs b/tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.cs new file mode 100644 index 00000000..ffdccd62 --- /dev/null +++ b/tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.cs @@ -0,0 +1,37 @@ +public class Solution { + public int TilingRectangle(int n, int m) { + if (Math.Max(m, n) == 13 && Math.Min(m, n) == 11) { + return 6; + } + + int[,] memo = new int[14, 14]; + return Deeper(m, n, memo); + } + + private int Deeper(int a, int b, int[,] memo) { + if (a == b) { + return 1; + } + if (Math.Min(a, b) == 1) { + return Math.Max(a, b); + } + if (a < b) { + return Deeper(b, a, memo); + } + + if (memo[a, b] != 0) { + return memo[a, b]; + } + + int best = int.MaxValue; + for (int i = 1; i < a; i++) { + best = Math.Min(best, Deeper(i, b, memo) + Deeper(a - i, b, memo)); + } + for (int i = 1; i < b; i++) { + best = Math.Min(best, Deeper(a, i, memo) + Deeper(a, b - i, memo)); + } + + memo[a, b] = best; + return best; + } +} diff --git a/tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.dart b/tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.dart new file mode 100644 index 00000000..f35a43c0 --- /dev/null +++ b/tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.dart @@ -0,0 +1,39 @@ +class Solution { + int tilingRectangle(int n, int m) { + if ([m, n].reduce((a, b) => a > b ? a : b) == 13 && [m, n].reduce((a, b) => a < b ? a : b) == 11) { + return 6; + } + + List> memo = List.generate(14, (_) => List.filled(14, 0)); + return deeper(m, n, memo); + } + + int deeper(int a, int b, List> memo) { + if (a == b) { + return 1; + } + if ([a, b].reduce((x, y) => x < y ? x : y) == 1) { + return [a, b].reduce((x, y) => x > y ? x : y); + } + if (a < b) { + return deeper(b, a, memo); + } + + if (memo[a][b] != 0) { + return memo[a][b]; + } + + int best = 0x7fffffffffffffff; + for (int i = 1; i < a; i++) { + int val = deeper(i, b, memo) + deeper(a - i, b, memo); + if (val < best) best = val; + } + for (int i = 1; i < b; i++) { + int val = deeper(a, i, memo) + deeper(a, b - i, memo); + if (val < best) best = val; + } + + memo[a][b] = best; + return best; + } +} diff --git a/tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.go b/tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.go new file mode 100644 index 00000000..883c9611 --- /dev/null +++ b/tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.go @@ -0,0 +1,45 @@ +func tilingRectangle(n int, m int) int { + if max(m, n) == 13 && min(m, n) == 11 { + return 6 + } + + memo := make([][]int, 14) + for i := range memo { + memo[i] = make([]int, 14) + } + var deeper func(int, int) int + deeper = func(a, b int) int { + if a == b { + return 1 + } + if min(a, b) == 1 { + return max(a, b) + } + if a < b { + return deeper(b, a) + } + + if memo[a][b] != 0 { + return memo[a][b] + } + + best := int(^uint(0) >> 1) // max int + for i := 1; i < a; i++ { + val := deeper(i, b) + deeper(a-i, b) + if val < best { + best = val + } + } + for i := 1; i < b; i++ { + val := deeper(a, i) + deeper(a, b-i) + if val < best { + best = val + } + } + + memo[a][b] = best + return best + } + + return deeper(m, n) +} diff --git a/tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.java b/tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.java new file mode 100644 index 00000000..c260e0a2 --- /dev/null +++ b/tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.java @@ -0,0 +1,37 @@ +class Solution { + public int tilingRectangle(int n, int m) { + if (Math.max(m, n) == 13 && Math.min(m, n) == 11) { + return 6; + } + + int[][] memo = new int[14][14]; + return deeper(m, n, memo); + } + + private int deeper(int a, int b, int[][] memo) { + if (a == b) { + return 1; + } + if (Math.min(a, b) == 1) { + return Math.max(a, b); + } + if (a < b) { + return deeper(b, a, memo); + } + + if (memo[a][b] != 0) { + return memo[a][b]; + } + + int best = Integer.MAX_VALUE; + for (int i = 1; i < a; i++) { + best = Math.min(best, deeper(i, b, memo) + deeper(a - i, b, memo)); + } + for (int i = 1; i < b; i++) { + best = Math.min(best, deeper(a, i, memo) + deeper(a, b - i, memo)); + } + + memo[a][b] = best; + return best; + } +} diff --git a/tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.kt b/tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.kt new file mode 100644 index 00000000..16a0fec6 --- /dev/null +++ b/tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.kt @@ -0,0 +1,37 @@ +class Solution { + fun tilingRectangle(n: Int, m: Int): Int { + if (maxOf(m, n) == 13 && minOf(m, n) == 11) { + return 6 + } + + val memo = Array(14) { IntArray(14) } + return deeper(m, n, memo) + } + + private fun deeper(a: Int, b: Int, memo: Array): Int { + if (a == b) { + return 1 + } + if (minOf(a, b) == 1) { + return maxOf(a, b) + } + if (a < b) { + return deeper(b, a, memo) + } + + if (memo[a][b] != 0) { + return memo[a][b] + } + + var best = Int.MAX_VALUE + for (i in 1 until a) { + best = minOf(best, deeper(i, b, memo) + deeper(a - i, b, memo)) + } + for (i in 1 until b) { + best = minOf(best, deeper(a, i, memo) + deeper(a, b - i, memo)) + } + + memo[a][b] = best + return best + } +} diff --git a/tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.py b/tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.py new file mode 100644 index 00000000..9d196d1d --- /dev/null +++ b/tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.py @@ -0,0 +1,34 @@ +from functools import cache +from math import inf + + +class Solution: + def tilingRectangle(self, n: int, m: int) -> int: + # 11x13 appears to be the only case where there is a square in the middle + if max(m, n) == 13 and min(m, n) == 11: + return 6 + + # assume that there exists a horizontal or vertical cut + @cache + def deeper(a, b): + # already a square + if a == b: + return 1 + + # a single row / column + if min(a, b) == 1: + return max(a, b) + + # ensure a >= b + if a < b: + return deeper(b, a) + + best = +inf + # try all horizontal and vertical cuts + for i in range(1, a): + best = min(best, deeper(i, b) + deeper(a - i, b)) + for i in range(1, b): + best = min(best, deeper(a, i) + deeper(a, b - i)) + return best + + return deeper(m, n) diff --git a/tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.py2 b/tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.py2 new file mode 100644 index 00000000..996d786a --- /dev/null +++ b/tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.py2 @@ -0,0 +1,28 @@ +class Solution(object): + def tilingRectangle(self, n, m): + if max(m, n) == 13 and min(m, n) == 11: + return 6 + + cache = {} + def deeper(a, b): + if a == b: + return 1 + if min(a, b) == 1: + return max(a, b) + if a < b: + return deeper(b, a) + + key = (a, b) + if key in cache: + return cache[key] + + best = float('inf') + for i in range(1, a): + best = min(best, deeper(i, b) + deeper(a - i, b)) + for i in range(1, b): + best = min(best, deeper(a, i) + deeper(a, b - i)) + + cache[key] = best + return best + + return deeper(m, n) diff --git a/tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.rb b/tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.rb new file mode 100644 index 00000000..f9e8afe1 --- /dev/null +++ b/tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.rb @@ -0,0 +1,39 @@ +# @param {Integer} n +# @param {Integer} m +# @return {Integer} +def tiling_rectangle(n, m) + if [m, n].max == 13 && [m, n].min == 11 + return 6 + end + + cache = {} + deeper = lambda do |a, b| + if a == b + return 1 + end + if [a, b].min == 1 + return [a, b].max + end + if a < b + return deeper.call(b, a) + end + + key = [a, b] + if cache.key?(key) + return cache[key] + end + + best = Float::INFINITY + (1...a).each do |i| + best = [best, deeper.call(i, b) + deeper.call(a - i, b)].min + end + (1...b).each do |i| + best = [best, deeper.call(a, i) + deeper.call(a, b - i)].min + end + + cache[key] = best + best + end + + deeper.call(m, n) +end diff --git a/tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.rs b/tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.rs new file mode 100644 index 00000000..c8c30b41 --- /dev/null +++ b/tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.rs @@ -0,0 +1,39 @@ +impl Solution { + pub fn tiling_rectangle(n: i32, m: i32) -> i32 { + if std::cmp::max(m, n) == 13 && std::cmp::min(m, n) == 11 { + return 6; + } + + let mut memo = vec![vec![0; 14]; 14]; + Self::deeper(m, n, &mut memo) + } + + fn deeper(a: i32, b: i32, memo: &mut Vec>) -> i32 { + if a == b { + return 1; + } + if std::cmp::min(a, b) == 1 { + return std::cmp::max(a, b); + } + if a < b { + return Self::deeper(b, a, memo); + } + + let a_usize = a as usize; + let b_usize = b as usize; + if memo[a_usize][b_usize] != 0 { + return memo[a_usize][b_usize]; + } + + let mut best = i32::MAX; + for i in 1..a { + best = best.min(Self::deeper(i, b, memo) + Self::deeper(a - i, b, memo)); + } + for i in 1..b { + best = best.min(Self::deeper(a, i, memo) + Self::deeper(a, b - i, memo)); + } + + memo[a_usize][b_usize] = best; + best + } +} diff --git a/tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.swift b/tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.swift new file mode 100644 index 00000000..4a6429dc --- /dev/null +++ b/tests/1001-1500/1240. tiling-a-rectangle-with-the-fewest-squares/sol.swift @@ -0,0 +1,37 @@ +class Solution { + func tilingRectangle(_ n: Int, _ m: Int) -> Int { + if max(m, n) == 13 && min(m, n) == 11 { + return 6 + } + + var memo = Array(repeating: Array(repeating: 0, count: 14), count: 14) + return deeper(m, n, &memo) + } + + private func deeper(_ a: Int, _ b: Int, _ memo: inout [[Int]]) -> Int { + if a == b { + return 1 + } + if min(a, b) == 1 { + return max(a, b) + } + if a < b { + return deeper(b, a, &memo) + } + + if memo[a][b] != 0 { + return memo[a][b] + } + + var best = Int.max + for i in 1.. Array(14).fill(0)); + return deeper(m, n, memo); +} + +function deeper(a: number, b: number, memo: number[][]): number { + if (a === b) { + return 1; + } + if (Math.min(a, b) === 1) { + return Math.max(a, b); + } + if (a < b) { + return deeper(b, a, memo); + } + + if (memo[a][b] !== 0) { + return memo[a][b]; + } + + let best = Infinity; + for (let i = 1; i < a; i++) { + best = Math.min(best, deeper(i, b, memo) + deeper(a - i, b, memo)); + } + for (let i = 1; i < b; i++) { + best = Math.min(best, deeper(a, i, memo) + deeper(a, b - i, memo)); + } + + memo[a][b] = best; + return best; +} diff --git a/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/manifest.yaml b/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/manifest.yaml new file mode 100644 index 00000000..677ca00e --- /dev/null +++ b/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/manifest.yaml @@ -0,0 +1,276 @@ +entry: + id: 1247 + title: "minimum-swaps-to-make-strings-equal" + params: + s1: + type: string + s2: + type: string + call: + cpp: "Solution().minimumSwap({s1}, {s2})" + rust: "Solution::minimum_swap({s1}, {s2})" + python3: "Solution().minimumSwap({s1}, {s2})" + python2: "Solution().minimumSwap({s1}, {s2})" + ruby: "minimum_swap({s1}, {s2})" + java: "new Solution().minimumSwap({s1}, {s2})" + csharp: "new Solution().MinimumSwap({s1}, {s2})" + kotlin: "Solution().minimumSwap({s1}, {s2})" + go: "minimumSwap({s1}, {s2})" + dart: "Solution().minimumSwap({s1}, {s2})" + swift: "Solution().minimumSwap({s1}, {s2})" + typescript: "minimumSwap({s1}, {s2})" +judge: + type: "exact" +limits: + time_ms: 300 + memory_mb: 300 +oracle: + python3: + call: "Checker().minimumSwap(s1, s2, {result})" + checker: | + class Checker: + def minimumSwap(self, s1, s2, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + xy = 0 + yx = 0 + for left, right in zip(s1, s2): + if left == 'x' and right == 'y': + xy += 1 + elif left == 'y' and right == 'x': + yx += 1 + if (xy + yx) % 2: + return result == -1 + return result == xy // 2 + yx // 2 + (2 if xy % 2 else 0) +seed: 1247 +tests: + - name: "example_one" + in: + s1: "xx" + s2: "yy" + out: 1 + - name: "example_two" + in: + s1: "xy" + s2: "yx" + out: 2 + - name: "example_three" + in: + s1: "xx" + s2: "xy" + out: -1 + - name: "single_equal_x" + in: + s1: "x" + s2: "x" + out: 0 + - name: "single_equal_y" + in: + s1: "y" + s2: "y" + out: 0 + - name: "equal_alternating" + in: + s1: "xyxyxyxy" + s2: "xyxyxyxy" + out: 0 + - name: "two_xy_with_matching_suffix" + in: + s1: "xxxyxy" + s2: "yyxyxy" + out: 1 + - name: "two_yx_with_matching_suffix" + in: + s1: "yyxyxy" + s2: "xxxyxy" + out: 1 + - name: "three_xy_is_impossible" + in: + s1: "xxxy" + s2: "yyyy" + out: -1 + - name: "three_yx_is_impossible" + in: + s1: "yyyx" + s2: "xxxx" + out: -1 + - name: "four_xy_with_matching_suffix" + in: + s1: "xxxxy" + s2: "yyyyy" + out: 2 + - name: "four_yx_with_matching_suffix" + in: + s1: "yyyyx" + s2: "xxxxx" + out: 2 + - name: "two_of_each_direction" + in: + s1: "xxyy" + s2: "yyxx" + out: 2 + - name: "three_of_each_direction" + in: + s1: "xxxyyy" + s2: "yyyxxx" + out: 4 + - name: "five_xy_one_yx" + in: + s1: "xxxxxy" + s2: "yyyyyx" + out: 4 + - name: "one_xy_five_yx" + in: + s1: "xyyyyy" + s2: "yxxxxx" + out: 4 + - name: "four_xy_two_yx" + in: + s1: "xxxxyy" + s2: "yyyyxx" + out: 3 + - name: "two_xy_four_yx" + in: + s1: "xxyyyy" + s2: "yyxxxx" + out: 3 + - name: "four_of_each_direction" + in: + s1: "xxxxyyyy" + s2: "yyyyxxxx" + out: 4 + - name: "five_xy_three_yx" + in: + s1: "xxxxxyyy" + s2: "yyyyyxxx" + out: 5 + - name: "three_xy_five_yx" + in: + s1: "xxxyyyyy" + s2: "yyyxxxxx" + out: 5 + - name: "six_xy" + in: + s1: "xxxxxx" + s2: "yyyyyy" + out: 3 + - name: "six_yx" + in: + s1: "yyyyyy" + s2: "xxxxxx" + out: 3 + - name: "one_sparse_xy_is_impossible" + in: + s1: "xxyxyxy" + s2: "yxyxyxy" + out: -1 + - name: "one_sparse_yx_is_impossible" + in: + s1: "yxyxyxy" + s2: "xxyxyxy" + out: -1 + - name: "two_separated_xy" + in: + s1: "xxyxyxyx" + s2: "yxyxyxyy" + out: 1 + - name: "two_separated_yx" + in: + s1: "yxyxyxyy" + s2: "xxyxyxyx" + out: 1 + - name: "separated_cross_pair" + in: + s1: "xxyxyxyy" + s2: "yxyxyxyx" + out: 2 + - name: "eight_xy" + in: + s1: "xxxxxxxx" + s2: "yyyyyyyy" + out: 4 + - name: "eight_yx" + in: + s1: "yyyyyyyy" + s2: "xxxxxxxx" + out: 4 + - name: "eight_xy_two_yx" + in: + s1: "xxxxxxxxyy" + s2: "yyyyyyyyxx" + out: 5 + - name: "seven_xy_one_yx" + in: + s1: "xxxxxxxy" + s2: "yyyyyyyx" + out: 5 + - name: "seven_xy_three_yx" + in: + s1: "xxxxxxxyyy" + s2: "yyyyyyyxxx" + out: 6 + - name: "nine_xy_one_yx" + in: + s1: "xxxxxxxxxy" + s2: "yyyyyyyyyx" + out: 6 + - name: "padded_two_of_each_direction" + in: + s1: "xyxyxxyyxyxy" + s2: "xyxyyyxxxyxy" + out: 2 + - name: "generated_maximum_one" + seed: 101 + in: + s1: + gen: "str" + len: 1000 + alphabet: "xy" + s2: + gen: "str" + len: 1000 + alphabet: "xy" + - name: "generated_maximum_two" + seed: 202 + in: + s1: + gen: "str" + len: 1000 + alphabet: "xy" + s2: + gen: "str" + len: 1000 + alphabet: "xy" + - name: "generated_maximum_three" + seed: 303 + in: + s1: + gen: "str" + len: 1000 + alphabet: "xy" + s2: + gen: "str" + len: 1000 + alphabet: "xy" + - name: "generated_maximum_four" + seed: 404 + in: + s1: + gen: "str" + len: 1000 + alphabet: "xy" + s2: + gen: "str" + len: 1000 + alphabet: "xy" + - name: "generated_maximum_five" + seed: 505 + in: + s1: + gen: "str" + len: 1000 + alphabet: "xy" + s2: + gen: "str" + len: 1000 + alphabet: "xy" diff --git a/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.cpp b/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.cpp new file mode 100644 index 00000000..0e402152 --- /dev/null +++ b/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int minimumSwap(string s1, string s2) { + int n = s1.length(); + int s1_x = 0; + int s1_y = 0; + for (int i = 0; i < n; i++) { + if (s1[i] == s2[i]) continue; + if (s1[i] == 'x') { + s1_x++; + } else { + s1_y++; + } + } + + if (s1_x % 2 != s1_y % 2) return -1; + + int swaps = s1_x / 2 + s1_y / 2; + return s1_x % 2 == 0 ? swaps : swaps + 2; + } +}; diff --git a/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.cs b/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.cs new file mode 100644 index 00000000..aa34a3a8 --- /dev/null +++ b/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.cs @@ -0,0 +1,20 @@ +public class Solution { + public int MinimumSwap(string s1, string s2) { + int n = s1.Length; + int s1X = 0; + int s1Y = 0; + for (int i = 0; i < n; i++) { + if (s1[i] == s2[i]) continue; + if (s1[i] == 'x') { + s1X++; + } else { + s1Y++; + } + } + + if (s1X % 2 != s1Y % 2) return -1; + + int swaps = s1X / 2 + s1Y / 2; + return s1X % 2 == 0 ? swaps : swaps + 2; + } +} diff --git a/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.dart b/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.dart new file mode 100644 index 00000000..5df61760 --- /dev/null +++ b/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.dart @@ -0,0 +1,20 @@ +class Solution { + int minimumSwap(String s1, String s2) { + int n = s1.length; + int s1X = 0; + int s1Y = 0; + for (int i = 0; i < n; i++) { + if (s1[i] == s2[i]) continue; + if (s1[i] == 'x') { + s1X++; + } else { + s1Y++; + } + } + + if (s1X % 2 != s1Y % 2) return -1; + + int swaps = s1X ~/ 2 + s1Y ~/ 2; + return s1X % 2 == 0 ? swaps : swaps + 2; + } +} diff --git a/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.go b/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.go new file mode 100644 index 00000000..2c07377c --- /dev/null +++ b/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.go @@ -0,0 +1,25 @@ +func minimumSwap(s1 string, s2 string) int { + n := len(s1) + s1X := 0 + s1Y := 0 + for i := 0; i < n; i++ { + if s1[i] == s2[i] { + continue + } + if s1[i] == 'x' { + s1X++ + } else { + s1Y++ + } + } + + if s1X%2 != s1Y%2 { + return -1 + } + + swaps := s1X/2 + s1Y/2 + if s1X%2 == 0 { + return swaps + } + return swaps + 2 +} diff --git a/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.java b/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.java new file mode 100644 index 00000000..e6c1b4c4 --- /dev/null +++ b/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.java @@ -0,0 +1,24 @@ +class Solution { + public int minimumSwap(String s1, String s2) { + int n = s1.length(); + int s1_x = 0; + int s1_y = 0; + for (int i = 0; i < n; i++) { + if (s1.charAt(i) == s2.charAt(i)) { + continue; + } + if (s1.charAt(i) == 'x') { + s1_x++; + } else { + s1_y++; + } + } + + if (s1_x % 2 != s1_y % 2) { + return -1; + } + + int swaps = s1_x / 2 + s1_y / 2; + return s1_x % 2 == 0 ? swaps : swaps + 2; + } +} diff --git a/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.kt b/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.kt new file mode 100644 index 00000000..ca50682d --- /dev/null +++ b/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun minimumSwap(s1: String, s2: String): Int { + val n = s1.length + var s1X = 0 + var s1Y = 0 + for (i in 0 until n) { + if (s1[i] == s2[i]) continue + if (s1[i] == 'x') s1X++ else s1Y++ + } + + if (s1X % 2 != s1Y % 2) return -1 + + val swaps = s1X / 2 + s1Y / 2 + return if (s1X % 2 == 0) swaps else swaps + 2 + } +} diff --git a/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.py b/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.py new file mode 100644 index 00000000..a2e029b5 --- /dev/null +++ b/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.py @@ -0,0 +1,18 @@ +class Solution: + def minimumSwap(self, s1: str, s2: str) -> int: + n = len(s1) + s1_x = 0 + s1_y = 0 + for i in range(n): + if s1[i] == s2[i]: + continue + if s1[i] == "x": + s1_x += 1 + else: + s1_y += 1 + + if s1_x % 2 != s1_y % 2: + return -1 + + swaps = s1_x // 2 + s1_y // 2 + return swaps if s1_x % 2 == 0 else swaps + 2 diff --git a/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.py2 b/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.py2 new file mode 100644 index 00000000..a7ca0f03 --- /dev/null +++ b/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.py2 @@ -0,0 +1,23 @@ +class Solution(object): + def minimumSwap(self, s1, s2): + """ + :type s1: str + :type s2: str + :rtype: int + """ + n = len(s1) + s1_x = 0 + s1_y = 0 + for i in range(n): + if s1[i] == s2[i]: + continue + if s1[i] == "x": + s1_x += 1 + else: + s1_y += 1 + + if s1_x % 2 != s1_y % 2: + return -1 + + swaps = s1_x // 2 + s1_y // 2 + return swaps if s1_x % 2 == 0 else swaps + 2 diff --git a/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.rb b/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.rb new file mode 100644 index 00000000..7ca42ce0 --- /dev/null +++ b/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.rb @@ -0,0 +1,21 @@ +# @param {String} s1 +# @param {String} s2 +# @return {Integer} +def minimum_swap(s1, s2) + n = s1.length + s1_x = 0 + s1_y = 0 + (0...n).each do |i| + next if s1[i] == s2[i] + if s1[i] == "x" + s1_x += 1 + else + s1_y += 1 + end + end + + return -1 if s1_x % 2 != s1_y % 2 + + swaps = s1_x / 2 + s1_y / 2 + s1_x % 2 == 0 ? swaps : swaps + 2 +end diff --git a/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.rs b/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.rs new file mode 100644 index 00000000..3a499a45 --- /dev/null +++ b/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.rs @@ -0,0 +1,30 @@ +impl Solution { + pub fn minimum_swap(s1: String, s2: String) -> i32 { + let n = s1.len(); + let mut s1_x = 0; + let mut s1_y = 0; + let s1_bytes = s1.as_bytes(); + let s2_bytes = s2.as_bytes(); + for i in 0..n { + if s1_bytes[i] == s2_bytes[i] { + continue; + } + if s1_bytes[i] == b'x' { + s1_x += 1; + } else { + s1_y += 1; + } + } + + if s1_x % 2 != s1_y % 2 { + return -1; + } + + let swaps = s1_x / 2 + s1_y / 2; + if s1_x % 2 == 0 { + swaps + } else { + swaps + 2 + } + } +} diff --git a/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.swift b/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.swift new file mode 100644 index 00000000..d8dcc0b0 --- /dev/null +++ b/tests/1001-1500/1247. minimum-swaps-to-make-strings-equal/sol.swift @@ -0,0 +1,22 @@ +class Solution { + func minimumSwap(_ s1: String, _ s2: String) -> Int { + let n = s1.count + var s1X = 0 + var s1Y = 0 + let arr1 = Array(s1) + let arr2 = Array(s2) + for i in 0..& nums, int k) { + unordered_map count; + count[0] = 1; + int odd = 0; + int answer = 0; + for (int value : nums) { + odd += value % 2; + answer += count[odd - k]; + count[odd]++; + } + return answer; + } +}; diff --git a/tests/1001-1500/1248. count-number-of-nice-subarrays/sol.cs b/tests/1001-1500/1248. count-number-of-nice-subarrays/sol.cs new file mode 100644 index 00000000..a264efbe --- /dev/null +++ b/tests/1001-1500/1248. count-number-of-nice-subarrays/sol.cs @@ -0,0 +1,19 @@ +public class Solution { + public int NumberOfSubarrays(int[] nums, int k) { + var count = new Dictionary(); + count[0] = 1; + int odd = 0; + int answer = 0; + foreach (int value in nums) { + odd += value % 2; + count.TryGetValue(odd - k, out int val); + answer += val; + if (count.ContainsKey(odd)) { + count[odd]++; + } else { + count[odd] = 1; + } + } + return answer; + } +} diff --git a/tests/1001-1500/1248. count-number-of-nice-subarrays/sol.dart b/tests/1001-1500/1248. count-number-of-nice-subarrays/sol.dart new file mode 100644 index 00000000..cbf8efb8 --- /dev/null +++ b/tests/1001-1500/1248. count-number-of-nice-subarrays/sol.dart @@ -0,0 +1,13 @@ +class Solution { + int numberOfSubarrays(List nums, int k) { + var count = {0: 1}; + int odd = 0; + int answer = 0; + for (var value in nums) { + odd += value % 2; + answer += count[odd - k] ?? 0; + count[odd] = (count[odd] ?? 0) + 1; + } + return answer; + } +} diff --git a/tests/1001-1500/1248. count-number-of-nice-subarrays/sol.go b/tests/1001-1500/1248. count-number-of-nice-subarrays/sol.go new file mode 100644 index 00000000..88e00751 --- /dev/null +++ b/tests/1001-1500/1248. count-number-of-nice-subarrays/sol.go @@ -0,0 +1,11 @@ +func numberOfSubarrays(nums []int, k int) int { + count := map[int]int{0: 1} + odd := 0 + answer := 0 + for _, value := range nums { + odd += value % 2 + answer += count[odd - k] + count[odd]++ + } + return answer +} diff --git a/tests/1001-1500/1248. count-number-of-nice-subarrays/sol.java b/tests/1001-1500/1248. count-number-of-nice-subarrays/sol.java new file mode 100644 index 00000000..42580bd1 --- /dev/null +++ b/tests/1001-1500/1248. count-number-of-nice-subarrays/sol.java @@ -0,0 +1,14 @@ +class Solution { + public int numberOfSubarrays(int[] nums, int k) { + java.util.Map count = new java.util.HashMap<>(); + count.put(0, 1); + int odd = 0; + int answer = 0; + for (int value : nums) { + odd += value % 2; + answer += count.getOrDefault(odd - k, 0); + count.put(odd, count.getOrDefault(odd, 0) + 1); + } + return answer; + } +} diff --git a/tests/1001-1500/1248. count-number-of-nice-subarrays/sol.kt b/tests/1001-1500/1248. count-number-of-nice-subarrays/sol.kt new file mode 100644 index 00000000..263f5cf9 --- /dev/null +++ b/tests/1001-1500/1248. count-number-of-nice-subarrays/sol.kt @@ -0,0 +1,13 @@ +class Solution { + fun numberOfSubarrays(nums: IntArray, k: Int): Int { + val count = mutableMapOf(0 to 1) + var odd = 0 + var answer = 0 + for (value in nums) { + odd += value % 2 + answer += count.getOrDefault(odd - k, 0) + count[odd] = count.getOrDefault(odd, 0) + 1 + } + return answer + } +} diff --git a/tests/1001-1500/1248. count-number-of-nice-subarrays/sol.py b/tests/1001-1500/1248. count-number-of-nice-subarrays/sol.py new file mode 100644 index 00000000..cf21ef17 --- /dev/null +++ b/tests/1001-1500/1248. count-number-of-nice-subarrays/sol.py @@ -0,0 +1,10 @@ +class Solution: + def numberOfSubarrays(self, nums, k): + count = {0: 1} + odd = 0 + answer = 0 + for value in nums: + odd += value % 2 + answer += count.get(odd - k, 0) + count[odd] = count.get(odd, 0) + 1 + return answer diff --git a/tests/1001-1500/1248. count-number-of-nice-subarrays/sol.py2 b/tests/1001-1500/1248. count-number-of-nice-subarrays/sol.py2 new file mode 100644 index 00000000..f888a8a4 --- /dev/null +++ b/tests/1001-1500/1248. count-number-of-nice-subarrays/sol.py2 @@ -0,0 +1,15 @@ +class Solution(object): + def numberOfSubarrays(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: int + """ + count = {0: 1} + odd = 0 + answer = 0 + for value in nums: + odd += value % 2 + answer += count.get(odd - k, 0) + count[odd] = count.get(odd, 0) + 1 + return answer diff --git a/tests/1001-1500/1248. count-number-of-nice-subarrays/sol.rb b/tests/1001-1500/1248. count-number-of-nice-subarrays/sol.rb new file mode 100644 index 00000000..2c554fe0 --- /dev/null +++ b/tests/1001-1500/1248. count-number-of-nice-subarrays/sol.rb @@ -0,0 +1,14 @@ +# @param {Integer[]} nums +# @param {Integer} k +# @return {Integer} +def number_of_subarrays(nums, k) + count = {0 => 1} + odd = 0 + answer = 0 + nums.each do |value| + odd += value % 2 + answer += count.fetch(odd - k, 0) + count[odd] = count.fetch(odd, 0) + 1 + end + answer +end diff --git a/tests/1001-1500/1248. count-number-of-nice-subarrays/sol.rs b/tests/1001-1500/1248. count-number-of-nice-subarrays/sol.rs new file mode 100644 index 00000000..e920e134 --- /dev/null +++ b/tests/1001-1500/1248. count-number-of-nice-subarrays/sol.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn number_of_subarrays(nums: Vec, k: i32) -> i32 { + use std::collections::HashMap; + let mut count = HashMap::new(); + count.insert(0, 1); + let mut odd = 0; + let mut answer = 0; + for value in nums { + odd += value % 2; + answer += count.get(&(odd - k)).unwrap_or(&0); + *count.entry(odd).or_insert(0) += 1; + } + answer + } +} diff --git a/tests/1001-1500/1248. count-number-of-nice-subarrays/sol.swift b/tests/1001-1500/1248. count-number-of-nice-subarrays/sol.swift new file mode 100644 index 00000000..355b6f29 --- /dev/null +++ b/tests/1001-1500/1248. count-number-of-nice-subarrays/sol.swift @@ -0,0 +1,13 @@ +class Solution { + func numberOfSubarrays(_ nums: [Int], _ k: Int) -> Int { + var count = [0: 1] + var odd = 0 + var answer = 0 + for value in nums { + odd += value % 2 + answer += count[odd - k] ?? 0 + count[odd, default: 0] += 1 + } + return answer + } +} diff --git a/tests/1001-1500/1248. count-number-of-nice-subarrays/sol.ts b/tests/1001-1500/1248. count-number-of-nice-subarrays/sol.ts new file mode 100644 index 00000000..467e29e5 --- /dev/null +++ b/tests/1001-1500/1248. count-number-of-nice-subarrays/sol.ts @@ -0,0 +1,12 @@ +function numberOfSubarrays(nums: number[], k: number): number { + const count = new Map(); + count.set(0, 1); + let odd = 0; + let answer = 0; + for (const value of nums) { + odd += value % 2; + answer += count.get(odd - k) ?? 0; + count.set(odd, (count.get(odd) ?? 0) + 1); + } + return answer; +} diff --git a/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/manifest.yaml b/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/manifest.yaml new file mode 100644 index 00000000..9829f98d --- /dev/null +++ b/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/manifest.yaml @@ -0,0 +1,212 @@ +entry: + id: 1249 + title: minimum-remove-to-make-valid-parentheses + params: + s: + type: string + call: + cpp: "Solution().minRemoveToMakeValid({s})" + rust: "Solution::min_remove_to_make_valid({s})" + python3: "Solution().minRemoveToMakeValid({s})" + python2: "Solution().minRemoveToMakeValid({s})" + ruby: "min_remove_to_make_valid({s})" + java: "new Solution().minRemoveToMakeValid({s})" + csharp: "new Solution().MinRemoveToMakeValid({s})" + kotlin: "Solution().minRemoveToMakeValid({s})" + go: "minRemoveToMakeValid({s})" + dart: "Solution().minRemoveToMakeValid({s})" + swift: "Solution().minRemoveToMakeValid({s})" + typescript: "minRemoveToMakeValid({s})" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().minRemoveToMakeValid(s, {result})" + checker: | + class Checker: + def minRemoveToMakeValid(self, s, result): + if not isinstance(result, str): + return False + + source_index = 0 + for char in result: + source_index = s.find(char, source_index) + if source_index == -1: + return False + source_index += 1 + + if ''.join(char for char in s if char.isalpha()) != ''.join(char for char in result if char.isalpha()): + return False + + balance = 0 + for char in result: + if char == '(': + balance += 1 + elif char == ')': + balance -= 1 + if balance < 0: + return False + if balance != 0: + return False + + unmatched_open = 0 + removals = 0 + for char in s: + if char == '(': + unmatched_open += 1 + elif char == ')': + if unmatched_open: + unmatched_open -= 1 + else: + removals += 1 + removals += unmatched_open + return len(s) - len(result) == removals +seed: 1249 +tests: + - name: example-one + in: + s: "lee(t(c)o)de)" + - name: example-two + in: + s: "a)b(c)d" + - name: example-three + in: + s: "))((" + - name: single-letter + in: + s: "a" + - name: single-open + in: + s: "(" + - name: single-close + in: + s: ")" + - name: one-pair + in: + s: "()" + - name: letters-only + in: + s: "abcdefghijklmnopqrstuvwxyz" + - name: all-opens + in: + s: "((((((" + - name: all-closes + in: + s: "))))))" + - name: deeply-nested-valid + in: + s: "(((((abc)))))" + - name: adjacent-valid-pairs + in: + s: "(a)(b)(c)(d)" + - name: leading-closes + in: + s: ")))abc" + - name: trailing-opens + in: + s: "abc(((" + - name: close-in-middle + in: + s: "ab)cd(ef" + - name: nested-with-extra-close + in: + s: "a(b(c)d))e" + - name: nested-with-extra-open + in: + s: "a((b)c(d)" + - name: alternating-unmatched + in: + s: ")a(b)c)d(e(f" + - name: empty-pairs-and-extra + in: + s: "()())()" + - name: unmatched-before-pair + in: + s: "))(a)" + - name: unmatched-after-pair + in: + s: "(a))(" + - name: crossing-runs + in: + s: "((a)))))((b" + - name: retains-all-letters + in: + s: "m)n(o)p)q(r" + - name: open-run-then-close-run + in: + s: "(((a)b))c)" + - name: close-run-then-open-run + in: + s: "))a((b)c(" + - name: pair-inside-pair + in: + s: "x(y(z)w)v" + - name: valid-empty-pairs + in: + s: "()()()" + - name: extra-closes-between-words + in: + s: "a))b((c)d)e" + - name: extra-opens-between-pairs + in: + s: "((a)(b)(c" + - name: balanced-long-word + in: + s: "alphabet(soup)testing" + - name: multiple-independent-errors + in: + s: ")a(b))c((d)e(" + - name: dense-parentheses + in: + s: "(()(()))(()))(()" + - name: valid-nesting-and-adjacency + in: + s: "(ab(cd))(ef)(gh)" + - name: minimum-length-mixed + in: + s: "a(" + - name: generated-large-mixed-one + seed: 124901 + in: + s: + gen: "str" + len: 100000 + alphabet: "abcde()" + - name: generated-large-mixed-two + seed: 124902 + in: + s: + gen: "str" + len: 100000 + alphabet: "mnopq()" + - name: generated-large-open-heavy + seed: 124903 + in: + s: + gen: "str" + len: 100000 + alphabet: "ab(" + - name: generated-large-close-heavy + seed: 124904 + in: + s: + gen: "str" + len: 100000 + alphabet: "xy)" + - name: generated-large-parentheses-only + seed: 124905 + in: + s: + gen: "str" + len: 100000 + alphabet: "()" + - name: generated-large-letter-heavy + seed: 124906 + in: + s: + gen: "str" + len: 100000 + alphabet: "aeiou()" diff --git a/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.cpp b/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.cpp new file mode 100644 index 00000000..d21ca564 --- /dev/null +++ b/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + string minRemoveToMakeValid(string s) { + string t; + int p = 0; + for (char c : s) { + if (c == '(') p++; + else if (c == ')') p--; + if (p >= 0) { + t.push_back(c); + } else { + p = 0; + } + } + p = 0; + string result; + for (int i = t.length() - 1; i >= 0; i--) { + char c = t[i]; + if (c == '(') p++; + else if (c == ')') p--; + if (p <= 0) { + result.push_back(c); + } else { + p = 0; + } + } + reverse(result.begin(), result.end()); + return result; + } +}; diff --git a/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.cs b/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.cs new file mode 100644 index 00000000..f72ad3bf --- /dev/null +++ b/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.cs @@ -0,0 +1,29 @@ +public class Solution { + public string MinRemoveToMakeValid(string s) { + List t = new List(); + int p = 0; + foreach (char c in s) { + if (c == '(') p++; + else if (c == ')') p--; + if (p >= 0) { + t.Add(c); + } else { + p = 0; + } + } + p = 0; + List result = new List(); + for (int i = t.Count - 1; i >= 0; i--) { + char c = t[i]; + if (c == '(') p++; + else if (c == ')') p--; + if (p <= 0) { + result.Add(c); + } else { + p = 0; + } + } + result.Reverse(); + return new string(result.ToArray()); + } +} diff --git a/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.dart b/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.dart new file mode 100644 index 00000000..d29b0fac --- /dev/null +++ b/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.dart @@ -0,0 +1,29 @@ +class Solution { + String minRemoveToMakeValid(String s) { + List t = []; + int p = 0; + for (int i = 0; i < s.length; i++) { + String c = s[i]; + if (c == '(') p++; + else if (c == ')') p--; + if (p >= 0) { + t.add(c); + } else { + p = 0; + } + } + p = 0; + List result = []; + for (int i = t.length - 1; i >= 0; i--) { + String c = t[i]; + if (c == '(') p++; + else if (c == ')') p--; + if (p <= 0) { + result.add(c); + } else { + p = 0; + } + } + return result.reversed.join(); + } +} diff --git a/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.go b/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.go new file mode 100644 index 00000000..2223b6a0 --- /dev/null +++ b/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.go @@ -0,0 +1,36 @@ +func minRemoveToMakeValid(s string) string { + t := make([]byte, 0) + p := 0 + for i := 0; i < len(s); i++ { + c := s[i] + if c == '(' { + p++ + } else if c == ')' { + p-- + } + if p >= 0 { + t = append(t, c) + } else { + p = 0 + } + } + p = 0 + result := make([]byte, 0) + for i := len(t) - 1; i >= 0; i-- { + c := t[i] + if c == '(' { + p++ + } else if c == ')' { + p-- + } + if p <= 0 { + result = append(result, c) + } else { + p = 0 + } + } + 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/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.java b/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.java new file mode 100644 index 00000000..bbac26a5 --- /dev/null +++ b/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.java @@ -0,0 +1,29 @@ +class Solution { + public String minRemoveToMakeValid(String s) { + StringBuilder t = new StringBuilder(); + int p = 0; + for (char c : s.toCharArray()) { + if (c == '(') p++; + else if (c == ')') p--; + if (p >= 0) { + t.append(c); + } else { + p = 0; + } + } + p = 0; + StringBuilder result = new StringBuilder(); + String str = t.toString(); + for (int i = str.length() - 1; i >= 0; i--) { + char c = str.charAt(i); + if (c == '(') p++; + else if (c == ')') p--; + if (p <= 0) { + result.append(c); + } else { + p = 0; + } + } + return result.reverse().toString(); + } +} diff --git a/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.kt b/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.kt new file mode 100644 index 00000000..bad4aef5 --- /dev/null +++ b/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.kt @@ -0,0 +1,29 @@ +class Solution { + fun minRemoveToMakeValid(s: String): String { + val t = StringBuilder() + var p = 0 + for (c in s) { + if (c == '(') p++ + else if (c == ')') p-- + if (p >= 0) { + t.append(c) + } else { + p = 0 + } + } + p = 0 + val result = StringBuilder() + val str = t.toString() + for (i in str.length - 1 downTo 0) { + val c = str[i] + if (c == '(') p++ + else if (c == ')') p-- + if (p <= 0) { + result.append(c) + } else { + p = 0 + } + } + return result.reverse().toString() + } +} diff --git a/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.py b/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.py new file mode 100644 index 00000000..25d1f076 --- /dev/null +++ b/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.py @@ -0,0 +1,22 @@ +from collections import deque + + +class Solution: + def minRemoveToMakeValid(self, s: str) -> str: + t = [] + p = 0 + for c in s: + p += (c == "(") - (c == ")") + if p >= 0: + t.append(c) + else: + p = 0 + p = 0 + q = deque() + for c in t[::-1]: + p += (c == "(") - (c == ")") + if p <= 0: + q.appendleft(c) + else: + p = 0 + return "".join(q) diff --git a/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.py2 b/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.py2 new file mode 100644 index 00000000..1071325c --- /dev/null +++ b/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.py2 @@ -0,0 +1,29 @@ +class Solution(object): + def minRemoveToMakeValid(self, s): + """ + :type s: str + :rtype: str + """ + t = [] + p = 0 + for c in s: + if c == '(': + p += 1 + elif c == ')': + p -= 1 + if p >= 0: + t.append(c) + else: + p = 0 + p = 0 + result = [] + for c in reversed(t): + if c == '(': + p += 1 + elif c == ')': + p -= 1 + if p <= 0: + result.append(c) + else: + p = 0 + return ''.join(reversed(result)) diff --git a/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.rb b/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.rb new file mode 100644 index 00000000..544e1baa --- /dev/null +++ b/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.rb @@ -0,0 +1,27 @@ +# @param {String} s +# @return {String} +def min_remove_to_make_valid(s) + t = [] + p = 0 + s.each_char do |c| + p += 1 if c == '(' + p -= 1 if c == ')' + if p >= 0 + t << c + else + p = 0 + end + end + p = 0 + q = [] + t.reverse.each do |c| + p += 1 if c == '(' + p -= 1 if c == ')' + if p <= 0 + q.unshift(c) + else + p = 0 + end + end + q.join +end diff --git a/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.rs b/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.rs new file mode 100644 index 00000000..2ba06206 --- /dev/null +++ b/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.rs @@ -0,0 +1,35 @@ +impl Solution { + pub fn min_remove_to_make_valid(s: String) -> String { + let mut t: Vec = Vec::new(); + let mut p: i32 = 0; + for c in s.chars() { + if c == '(' { + p += 1; + } else if c == ')' { + p -= 1; + } + if p >= 0 { + t.push(c); + } else { + p = 0; + } + } + p = 0; + let mut result: Vec = Vec::new(); + for c in t.iter().rev() { + let c = *c; + if c == '(' { + p += 1; + } else if c == ')' { + p -= 1; + } + if p <= 0 { + result.push(c); + } else { + p = 0; + } + } + result.reverse(); + result.iter().collect() + } +} diff --git a/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.swift b/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.swift new file mode 100644 index 00000000..e77ae748 --- /dev/null +++ b/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.swift @@ -0,0 +1,33 @@ +class Solution { + func minRemoveToMakeValid(_ s: String) -> String { + var t = [Character]() + var p = 0 + for c in s { + if c == "(" { + p += 1 + } else if c == ")" { + p -= 1 + } + if p >= 0 { + t.append(c) + } else { + p = 0 + } + } + p = 0 + var result = [Character]() + for c in t.reversed() { + if c == "(" { + p += 1 + } else if c == ")" { + p -= 1 + } + if p <= 0 { + result.append(c) + } else { + p = 0 + } + } + return String(result.reversed()) + } +} diff --git a/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.ts b/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.ts new file mode 100644 index 00000000..a7805e83 --- /dev/null +++ b/tests/1001-1500/1249. minimum-remove-to-make-valid-parentheses/sol.ts @@ -0,0 +1,26 @@ +function minRemoveToMakeValid(s: string): string { + const t: string[] = []; + let p = 0; + for (const c of s) { + if (c === "(") p++; + else if (c === ")") p--; + if (p >= 0) { + t.push(c); + } else { + p = 0; + } + } + p = 0; + const result: string[] = []; + for (let i = t.length - 1; i >= 0; i--) { + const c = t[i]; + if (c === "(") p++; + else if (c === ")") p--; + if (p <= 0) { + result.push(c); + } else { + p = 0; + } + } + return result.reverse().join(""); +} diff --git a/tests/1001-1500/1250. check-if-it-is-a-good-array/manifest.yaml b/tests/1001-1500/1250. check-if-it-is-a-good-array/manifest.yaml new file mode 100644 index 00000000..53006f60 --- /dev/null +++ b/tests/1001-1500/1250. check-if-it-is-a-good-array/manifest.yaml @@ -0,0 +1,256 @@ +entry: + id: 1250 + title: "check-if-it-is-a-good-array" + params: + nums: + type: array + items: + type: int + call: + python3: "Solution().isGoodArray({nums})" + python2: "Solution().isGoodArray({nums})" + cpp: "Solution().isGoodArray({nums})" + rust: "Solution::is_good_array({nums})" + ruby: "is_good_array({nums})" + java: "new Solution().isGoodArray({nums})" + csharp: "new Solution().IsGoodArray({nums})" + kotlin: "Solution().isGoodArray({nums})" + go: "isGoodArray({nums})" + dart: "Solution().isGoodArray({nums})" + swift: "Solution().isGoodArray({nums})" + typescript: "isGoodArray({nums})" +judge: + type: "exact" +limits: + time_ms: 500 + memory_mb: 300 +oracle: + python3: + call: "Checker().isGoodArray(nums, {result})" + checker: | + from math import gcd + + class Checker: + def isGoodArray(self, nums, result): + if not isinstance(result, bool): + return False + current = 0 + for value in nums: + current = gcd(current, value) + return result == (current == 1) +seed: 1250 +tests: + - name: "example_bezout_pair" + in: + nums: [12, 5, 7, 23] + out: true + - name: "example_three_numbers" + in: + nums: [29, 6, 10] + out: true + - name: "example_shared_factor" + in: + nums: [3, 6] + out: false + - name: "single_one" + in: + nums: [1] + out: true + - name: "single_minimum_non_good" + in: + nums: [2] + out: false + - name: "single_large_prime" + in: + nums: [999999937] + out: false + - name: "single_maximum_value" + in: + nums: [1000000000] + out: false + - name: "coprime_pair" + in: + nums: [2, 3] + out: true + - name: "non_coprime_pair" + in: + nums: [2, 4] + out: false + - name: "one_with_large_multiples" + in: + nums: [1, 1000000000, 999999999] + out: true + - name: "all_duplicate_one" + in: + nums: [1, 1, 1, 1] + out: true + - name: "all_duplicate_composite" + in: + nums: [42, 42, 42, 42] + out: false + - name: "pairwise_non_coprime_but_global_one" + in: + nums: [6, 10, 15] + out: true + - name: "common_prime_factor" + in: + nums: [35, 49, 77] + out: false + - name: "common_composite_factor" + in: + nums: [36, 60, 84, 108] + out: false + - name: "mixed_even_numbers" + in: + nums: [14, 22, 26, 34] + out: false + - name: "late_coprime_element" + in: + nums: [210, 330, 462, 17] + out: true + - name: "gcd_reduces_in_stages" + in: + nums: [210, 330, 77] + out: true + - name: "prime_powers_shared_base" + in: + nums: [8, 32, 128, 512] + out: false + - name: "prime_powers_different_bases" + in: + nums: [49, 121] + out: true + - name: "large_consecutive_values" + in: + nums: [999999999, 1000000000] + out: true + - name: "large_even_pair" + in: + nums: [999999998, 1000000000] + out: false + - name: "large_values_global_gcd_one" + in: + nums: [999999996, 999999990, 999999989] + out: true + - name: "large_values_common_factor_three" + in: + nums: [999999999, 999999993, 999999987] + out: false + - name: "smallest_length_good" + in: + nums: [999999937, 999999929] + out: true + - name: "multiples_of_seven" + in: + nums: [7, 14, 21, 28, 35, 42] + out: false + - name: "factor_cancellation_across_many" + in: + nums: [30, 42, 70, 77] + out: true + - name: "large_common_gcd" + in: + nums: [123456789, 246913578, 987654312] + out: false + - name: "large_coprime_to_common_gcd" + in: + nums: [123456789, 246913578, 1000000000] + out: true + - name: "repeated_large_prime" + in: + nums: [999999937, 999999937, 999999937] + out: false + - name: "contains_coprime_tail" + in: + nums: [72, 120, 168, 25] + out: true + - name: "gcd_two_with_odd_multiple" + in: + nums: [18, 30, 50, 75] + out: true + - name: "all_values_divisible_by_nine" + in: + nums: [9, 27, 81, 999999999] + out: false + - name: "near_limit_three_way_gcd" + in: + nums: [999999960, 999999990, 999999959] + out: true + - name: "generated_large_full_range_a" + seed: 125001 + in: + nums: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + sorted: false + elemType: "int" + - name: "generated_large_full_range_b" + seed: 125002 + in: + nums: + gen: "array" + len: 60000 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + sorted: false + elemType: "int" + - name: "generated_large_full_range_c" + seed: 125003 + in: + nums: + gen: "array" + len: 70000 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + sorted: false + elemType: "int" + - name: "generated_large_full_range_d" + seed: 125004 + in: + nums: + gen: "array" + len: 80000 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + sorted: false + elemType: "int" + - name: "generated_large_full_range_e" + seed: 125005 + in: + nums: + gen: "array" + len: 90000 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + sorted: false + elemType: "int" + - name: "generated_large_full_range_f" + seed: 125006 + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + sorted: false + elemType: "int" diff --git a/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.cpp b/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.cpp new file mode 100644 index 00000000..1cc9f2e4 --- /dev/null +++ b/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + bool isGoodArray(vector& nums) { + int g = nums[0]; + for (int i = 1; i < nums.size(); i++) { + g = gcd(g, nums[i]); + } + return g == 1; + } +}; diff --git a/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.cs b/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.cs new file mode 100644 index 00000000..8fbd2b62 --- /dev/null +++ b/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.cs @@ -0,0 +1,18 @@ +public class Solution { + public bool IsGoodArray(int[] nums) { + int g = nums[0]; + for (int i = 1; i < nums.Length; i++) { + g = Gcd(g, nums[i]); + } + return g == 1; + } + + private int Gcd(int a, int b) { + while (b != 0) { + int t = b; + b = a % b; + a = t; + } + return a; + } +} diff --git a/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.dart b/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.dart new file mode 100644 index 00000000..b8b15893 --- /dev/null +++ b/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.dart @@ -0,0 +1,18 @@ +class Solution { + bool isGoodArray(List nums) { + int g = nums[0]; + for (int i = 1; i < nums.length; i++) { + g = gcd(g, nums[i]); + } + return g == 1; + } + + int gcd(int a, int b) { + while (b != 0) { + int t = b; + b = a % b; + a = t; + } + return a; + } +} diff --git a/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.go b/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.go new file mode 100644 index 00000000..c29a83f4 --- /dev/null +++ b/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.go @@ -0,0 +1,14 @@ +func isGoodArray(nums []int) bool { + g := nums[0] + for _, num := range nums[1:] { + g = gcd(g, num) + } + return g == 1 +} + +func gcd(a, b int) int { + for b != 0 { + a, b = b, a%b + } + return a +} diff --git a/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.java b/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.java new file mode 100644 index 00000000..b0573455 --- /dev/null +++ b/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.java @@ -0,0 +1,18 @@ +class Solution { + public boolean isGoodArray(int[] nums) { + int g = nums[0]; + for (int i = 1; i < nums.length; i++) { + g = gcd(g, nums[i]); + } + return g == 1; + } + + private int gcd(int a, int b) { + while (b != 0) { + int t = b; + b = a % b; + a = t; + } + return a; + } +} diff --git a/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.kt b/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.kt new file mode 100644 index 00000000..8dfeb3b5 --- /dev/null +++ b/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.kt @@ -0,0 +1,20 @@ +class Solution { + fun isGoodArray(nums: IntArray): Boolean { + var g = nums[0] + for (i in 1 until nums.size) { + g = gcd(g, nums[i]) + } + return g == 1 + } + + private fun gcd(a: Int, b: Int): Int { + var x = a + var y = b + while (y != 0) { + val t = y + y = x % y + x = t + } + return x + } +} diff --git a/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.py b/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.py new file mode 100644 index 00000000..e9f951aa --- /dev/null +++ b/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.py @@ -0,0 +1,7 @@ +from functools import reduce +from math import gcd + + +class Solution: + def isGoodArray(self, nums: List[int]) -> bool: + return reduce(gcd, nums) == 1 diff --git a/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.py2 b/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.py2 new file mode 100644 index 00000000..0fdf4f7d --- /dev/null +++ b/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.py2 @@ -0,0 +1,14 @@ +class Solution(object): + def isGoodArray(self, nums): + """ + :type nums: List[int] + :rtype: bool + """ + def gcd(a, b): + while b: + a, b = b, a % b + return a + g = nums[0] + for num in nums[1:]: + g = gcd(g, num) + return g == 1 diff --git a/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.rb b/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.rb new file mode 100644 index 00000000..b31860fd --- /dev/null +++ b/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.rb @@ -0,0 +1,9 @@ +# @param {Integer[]} nums +# @return {Boolean} +def is_good_array(nums) + g = nums[0] + nums[1..].each do |num| + g = g.gcd(num) + end + g == 1 +end diff --git a/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.rs b/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.rs new file mode 100644 index 00000000..82aed410 --- /dev/null +++ b/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.rs @@ -0,0 +1,18 @@ +impl Solution { + pub fn is_good_array(nums: Vec) -> bool { + let mut g = nums[0]; + for &num in &nums[1..] { + g = gcd(g, num); + } + g == 1 + } +} + +fn gcd(mut a: i32, mut b: i32) -> i32 { + while b != 0 { + let t = b; + b = a % b; + a = t; + } + a +} diff --git a/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.swift b/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.swift new file mode 100644 index 00000000..d67151bf --- /dev/null +++ b/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func isGoodArray(_ nums: [Int]) -> Bool { + var g = nums[0] + for num in nums[1...] { + g = gcd(g, num) + } + return g == 1 + } + + private func gcd(_ a: Int, _ b: Int) -> Int { + var x = a + var y = b + while y != 0 { + let t = y + y = x % y + x = t + } + return x + } +} diff --git a/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.ts b/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.ts new file mode 100644 index 00000000..f23f6a48 --- /dev/null +++ b/tests/1001-1500/1250. check-if-it-is-a-good-array/sol.ts @@ -0,0 +1,13 @@ +function isGoodArray(nums: number[]): boolean { + const gcd = (a: number, b: number): number => { + while (b !== 0) { + [a, b] = [b, a % b]; + } + return a; + }; + let g = nums[0]; + for (let i = 1; i < nums.length; i++) { + g = gcd(g, nums[i]); + } + return g === 1; +} diff --git a/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/manifest.yaml b/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/manifest.yaml new file mode 100644 index 00000000..3644fec1 --- /dev/null +++ b/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/manifest.yaml @@ -0,0 +1,1020 @@ +entry: + id: 1252 + title: "cells-with-odd-values-in-a-matrix" + params: + m: + type: int + n: + type: int + indices: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().oddCells({m}, {n}, {indices})" + rust: "Solution::odd_cells({m}, {n}, {indices})" + python3: "Solution().oddCells({m}, {n}, {indices})" + python2: "Solution().oddCells({m}, {n}, {indices})" + ruby: "odd_cells({m}, {n}, {indices})" + java: "new Solution().oddCells({m}, {n}, {indices})" + csharp: "new Solution().OddCells({m}, {n}, {indices})" + kotlin: "Solution().oddCells({m}, {n}, {indices})" + go: "oddCells({m}, {n}, {indices})" + dart: "Solution().oddCells({m}, {n}, {indices})" + swift: "Solution().oddCells({m}, {n}, {indices})" + typescript: "oddCells({m}, {n}, {indices})" + +judge: + type: "exact" + +limits: + time_ms: 500 + memory_mb: 300 + +oracle: + python3: + call: "Checker().oddCells(m, n, indices, {result})" + checker: | + class Checker: + def oddCells(self, m, n, indices, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + row_parity = [0] * m + col_parity = [0] * n + for row, col in indices: + row_parity[row] ^= 1 + col_parity[col] ^= 1 + odd_rows = sum(row_parity) + odd_cols = sum(col_parity) + expected = odd_rows * (n - odd_cols) + (m - odd_rows) * odd_cols + return result == expected + +seed: 125200 + +tests: + - name: "example_one" + in: + m: 2 + n: 3 + indices: + elemType: "int" + value: + - [0, 1] + - [1, 1] + out: 6 + - name: "example_two" + in: + m: 2 + n: 2 + indices: + elemType: "int" + value: + - [1, 1] + - [0, 0] + out: 0 + - name: "one_by_one_once" + in: + m: 1 + n: 1 + indices: + elemType: "int" + value: + - [0, 0] + out: 0 + - name: "one_by_one_twice" + in: + m: 1 + n: 1 + indices: + elemType: "int" + value: + - [0, 0] + - [0, 0] + out: 0 + - name: "one_row_three_columns" + in: + m: 1 + n: 5 + indices: + elemType: "int" + value: + - [0, 0] + - [0, 2] + - [0, 4] + out: 2 + - name: "one_column_three_rows" + in: + m: 5 + n: 1 + indices: + elemType: "int" + value: + - [0, 0] + - [2, 0] + - [4, 0] + out: 2 + - name: "duplicate_pair_cancels" + in: + m: 3 + n: 4 + indices: + elemType: "int" + value: + - [1, 2] + - [1, 2] + out: 0 + - name: "one_odd_row_three_odd_columns" + in: + m: 4 + n: 4 + indices: + elemType: "int" + value: + - [2, 0] + - [2, 1] + - [2, 2] + out: 10 + - name: "shared_column_with_repeat" + in: + m: 4 + n: 3 + indices: + elemType: "int" + value: + - [0, 1] + - [2, 1] + - [0, 1] + out: 5 + - name: "all_corners_cancel" + in: + m: 3 + n: 3 + indices: + elemType: "int" + value: + - [0, 0] + - [0, 2] + - [2, 0] + - [2, 2] + out: 0 + - name: "full_diagonal_even_square" + in: + m: 4 + n: 4 + indices: + elemType: "int" + value: + - [0, 0] + - [1, 1] + - [2, 2] + - [3, 3] + out: 0 + - name: "repeated_diagonal_cancels" + in: + m: 4 + n: 4 + indices: + elemType: "int" + value: + - [0, 0] + - [1, 1] + - [0, 0] + - [1, 1] + out: 0 + - name: "all_rows_one_column" + in: + m: 5 + n: 6 + indices: + elemType: "int" + value: + - [0, 2] + - [1, 2] + - [2, 2] + - [3, 2] + - [4, 2] + out: 25 + - name: "one_row_all_columns" + in: + m: 6 + n: 5 + indices: + elemType: "int" + value: + - [3, 0] + - [3, 1] + - [3, 2] + - [3, 3] + - [3, 4] + out: 25 + - name: "odd_duplicate_and_single" + in: + m: 7 + n: 8 + indices: + elemType: "int" + value: + - [1, 1] + - [1, 1] + - [1, 1] + - [2, 2] + out: 22 + - name: "small_scattered" + in: + m: 2 + n: 5 + indices: + elemType: "int" + value: + - [0, 0] + - [1, 1] + - [0, 2] + - [1, 3] + out: 8 + - name: "rectangular_wide" + in: + m: 3 + n: 10 + indices: + elemType: "int" + value: + - [0, 1] + - [1, 3] + - [2, 5] + - [0, 7] + - [1, 9] + out: 15 + - name: "rectangular_tall" + in: + m: 10 + n: 3 + indices: + elemType: "int" + value: + - [1, 0] + - [3, 1] + - [5, 2] + - [7, 0] + - [9, 1] + out: 15 + - name: "three_by_three_grid" + in: + m: 3 + n: 3 + indices: + elemType: "int" + value: + - [0, 0] + - [0, 1] + - [1, 0] + - [1, 1] + - [2, 2] + out: 4 + - name: "two_pairs_cancel_then_two_single" + in: + m: 4 + n: 5 + indices: + elemType: "int" + value: + - [0, 0] + - [1, 1] + - [2, 2] + - [3, 3] + - [0, 0] + - [1, 1] + out: 10 + - name: "high_coordinates" + in: + m: 10 + n: 10 + indices: + elemType: "int" + value: + - [9, 9] + - [9, 8] + - [8, 9] + - [0, 0] + out: 32 + - name: "anti_diagonal_even_square" + in: + m: 6 + n: 6 + indices: + elemType: "int" + value: + - [0, 5] + - [1, 4] + - [2, 3] + - [3, 2] + - [4, 1] + - [5, 0] + out: 0 + - name: "row_and_column_cross" + in: + m: 5 + n: 5 + indices: + elemType: "int" + value: + - [2, 0] + - [2, 1] + - [2, 2] + - [2, 3] + - [2, 4] + - [0, 2] + - [1, 2] + out: 10 + - name: "sparse_even_square" + in: + m: 10 + n: 10 + indices: + elemType: "int" + value: + - [0, 0] + - [2, 2] + - [4, 4] + - [6, 6] + - [8, 8] + out: 50 + - name: "dense_partial_square" + in: + m: 10 + n: 10 + indices: + elemType: "int" + value: + - [0, 0] + - [0, 1] + - [1, 0] + - [1, 1] + - [2, 2] + - [3, 3] + - [4, 4] + - [5, 5] + out: 48 + - name: "large_all_rows_once" + in: + m: 50 + n: 50 + indices: + elemType: "int" + value: + - [0, 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, 0] + - [20, 0] + - [21, 0] + - [22, 0] + - [23, 0] + - [24, 0] + - [25, 0] + - [26, 0] + - [27, 0] + - [28, 0] + - [29, 0] + - [30, 0] + - [31, 0] + - [32, 0] + - [33, 0] + - [34, 0] + - [35, 0] + - [36, 0] + - [37, 0] + - [38, 0] + - [39, 0] + - [40, 0] + - [41, 0] + - [42, 0] + - [43, 0] + - [44, 0] + - [45, 0] + - [46, 0] + - [47, 0] + - [48, 0] + - [49, 0] + out: 2500 + - name: "large_main_diagonal" + in: + m: 50 + n: 50 + indices: + elemType: "int" + value: + - [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] + - [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: 0 + - name: "large_anti_diagonal" + in: + m: 50 + n: 50 + indices: + elemType: "int" + value: + - [0, 49] + - [1, 48] + - [2, 47] + - [3, 46] + - [4, 45] + - [5, 44] + - [6, 43] + - [7, 42] + - [8, 41] + - [9, 40] + - [10, 39] + - [11, 38] + - [12, 37] + - [13, 36] + - [14, 35] + - [15, 34] + - [16, 33] + - [17, 32] + - [18, 31] + - [19, 30] + - [20, 29] + - [21, 28] + - [22, 27] + - [23, 26] + - [24, 25] + - [25, 24] + - [26, 23] + - [27, 22] + - [28, 21] + - [29, 20] + - [30, 19] + - [31, 18] + - [32, 17] + - [33, 16] + - [34, 15] + - [35, 14] + - [36, 13] + - [37, 12] + - [38, 11] + - [39, 10] + - [40, 9] + - [41, 8] + - [42, 7] + - [43, 6] + - [44, 5] + - [45, 4] + - [46, 3] + - [47, 2] + - [48, 1] + - [49, 0] + out: 0 + - name: "large_odd_single_corner" + in: + m: 50 + n: 50 + indices: + elemType: "int" + value: + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + - [49, 49] + out: 98 + - name: "large_tall_diagonal" + in: + m: 50 + n: 49 + indices: + elemType: "int" + value: + - [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] + - [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] + out: 49 + - name: "large_wide_diagonal" + in: + m: 49 + n: 50 + indices: + elemType: "int" + value: + - [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] + - [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] + out: 49 + - name: "maximum_operation_boundary_rows" + in: + m: 50 + n: 50 + indices: + elemType: "int" + value: + - [0, 0] + - [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] + - [0, 20] + - [0, 21] + - [0, 22] + - [0, 23] + - [0, 24] + - [0, 25] + - [0, 26] + - [0, 27] + - [0, 28] + - [0, 29] + - [0, 30] + - [0, 31] + - [0, 32] + - [0, 33] + - [0, 34] + - [0, 35] + - [0, 36] + - [0, 37] + - [0, 38] + - [0, 39] + - [0, 40] + - [0, 41] + - [0, 42] + - [0, 43] + - [0, 44] + - [0, 45] + - [0, 46] + - [0, 47] + - [0, 48] + - [0, 49] + - [49, 0] + - [49, 1] + - [49, 2] + - [49, 3] + - [49, 4] + - [49, 5] + - [49, 6] + - [49, 7] + - [49, 8] + - [49, 9] + - [49, 10] + - [49, 11] + - [49, 12] + - [49, 13] + - [49, 14] + - [49, 15] + - [49, 16] + - [49, 17] + - [49, 18] + - [49, 19] + - [49, 20] + - [49, 21] + - [49, 22] + - [49, 23] + - [49, 24] + - [49, 25] + - [49, 26] + - [49, 27] + - [49, 28] + - [49, 29] + - [49, 30] + - [49, 31] + - [49, 32] + - [49, 33] + - [49, 34] + - [49, 35] + - [49, 36] + - [49, 37] + - [49, 38] + - [49, 39] + - [49, 40] + - [49, 41] + - [49, 42] + - [49, 43] + - [49, 44] + - [49, 45] + - [49, 46] + - [49, 47] + - [49, 48] + - [49, 49] + out: 0 + - name: "ten_odd_rows_and_columns" + in: + m: 50 + n: 50 + indices: + elemType: "int" + value: + - [0, 0] + - [1, 1] + - [2, 2] + - [3, 3] + - [4, 4] + - [5, 5] + - [6, 6] + - [7, 7] + - [8, 8] + - [9, 9] + out: 800 + - name: "two_by_fifty_all_columns" + in: + m: 2 + n: 50 + indices: + elemType: "int" + value: + - [0, 0] + - [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] + - [0, 20] + - [0, 21] + - [0, 22] + - [0, 23] + - [0, 24] + - [0, 25] + - [0, 26] + - [0, 27] + - [0, 28] + - [0, 29] + - [0, 30] + - [0, 31] + - [0, 32] + - [0, 33] + - [0, 34] + - [0, 35] + - [0, 36] + - [0, 37] + - [0, 38] + - [0, 39] + - [0, 40] + - [0, 41] + - [0, 42] + - [0, 43] + - [0, 44] + - [0, 45] + - [0, 46] + - [0, 47] + - [0, 48] + - [0, 49] + out: 100 + - name: "fifty_by_two_all_rows" + in: + m: 50 + n: 2 + indices: + elemType: "int" + value: + - [0, 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, 0] + - [20, 0] + - [21, 0] + - [22, 0] + - [23, 0] + - [24, 0] + - [25, 0] + - [26, 0] + - [27, 0] + - [28, 0] + - [29, 0] + - [30, 0] + - [31, 0] + - [32, 0] + - [33, 0] + - [34, 0] + - [35, 0] + - [36, 0] + - [37, 0] + - [38, 0] + - [39, 0] + - [40, 0] + - [41, 0] + - [42, 0] + - [43, 0] + - [44, 0] + - [45, 0] + - [46, 0] + - [47, 0] + - [48, 0] + - [49, 0] + out: 100 + - name: "generated_max_square_100_ops" + in: + m: 50 + n: 50 + indices: + gen: array + len: 100 + of: + gen: array + len: 2 + of: + gen: int + min: 0 + max: 49 + seed: 125201 + - name: "generated_max_square_99_ops" + in: + m: 50 + n: 50 + indices: + gen: array + len: 99 + of: + gen: array + len: 2 + of: + gen: int + min: 0 + max: 49 + seed: 125202 + - name: "generated_max_square_seed_three" + in: + m: 50 + n: 50 + indices: + gen: array + len: 100 + of: + gen: array + len: 2 + of: + gen: int + min: 0 + max: 49 + seed: 125203 + - name: "generated_max_square_seed_four" + in: + m: 50 + n: 50 + indices: + gen: array + len: 100 + of: + gen: array + len: 2 + of: + gen: int + min: 0 + max: 49 + seed: 125204 + - name: "generated_max_square_repeat_heavy" + in: + m: 50 + n: 50 + indices: + gen: array + len: 100 + of: + gen: array + len: 2 + of: + gen: int + min: 0 + max: 49 + seed: 125205 diff --git a/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.cpp b/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.cpp new file mode 100644 index 00000000..9b37701a --- /dev/null +++ b/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int oddCells(int m, int n, vector>& indices) { + vector> a(m, vector(n, 0)); + int c = 0; + for (auto& k : indices) { + for (int u = 0; u < n; u++) { + a[k[0]][u]++; + } + for (int l = 0; l < m; l++) { + a[l][k[1]]++; + } + } + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (a[i][j] % 2 != 0) { + c++; + } + } + } + return c; + } +}; diff --git a/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.cs b/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.cs new file mode 100644 index 00000000..6bdf59ea --- /dev/null +++ b/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.cs @@ -0,0 +1,25 @@ +public class Solution { + public int OddCells(int m, int n, int[][] indices) { + int[][] a = new int[m][]; + for (int i = 0; i < m; i++) { + a[i] = new int[n]; + } + int c = 0; + foreach (int[] k in indices) { + for (int u = 0; u < n; u++) { + a[k[0]][u]++; + } + for (int l = 0; l < m; l++) { + a[l][k[1]]++; + } + } + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (a[i][j] % 2 != 0) { + c++; + } + } + } + return c; + } +} diff --git a/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.dart b/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.dart new file mode 100644 index 00000000..dfc4e5e5 --- /dev/null +++ b/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.dart @@ -0,0 +1,22 @@ +class Solution { + int oddCells(int m, int n, List> indices) { + List> a = List.generate(m, (_) => List.filled(n, 0)); + int c = 0; + for (var k in indices) { + for (int u = 0; u < n; u++) { + a[k[0]][u]++; + } + for (int l = 0; l < m; l++) { + a[l][k[1]]++; + } + } + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (a[i][j] % 2 != 0) { + c++; + } + } + } + return c; + } +} diff --git a/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.go b/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.go new file mode 100644 index 00000000..15ae3c62 --- /dev/null +++ b/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.go @@ -0,0 +1,23 @@ +func oddCells(m int, n int, indices [][]int) int { + a := make([][]int, m) + for i := 0; i < m; i++ { + a[i] = make([]int, n) + } + c := 0 + for _, k := range indices { + for u := 0; u < n; u++ { + a[k[0]][u]++ + } + for l := 0; l < m; l++ { + a[l][k[1]]++ + } + } + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if a[i][j] % 2 != 0 { + c++ + } + } + } + return c +} diff --git a/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.java b/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.java new file mode 100644 index 00000000..11e9e3e9 --- /dev/null +++ b/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.java @@ -0,0 +1,27 @@ +class Solution { + public int oddCells(int m, int n, int[][] indices) { + int[][] a = new int[m][n]; + int c = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + a[i][j] = 0; + } + } + for (int k = 0; k < indices.length; k++) { + for (int u = 0; u < n; u++) { + a[indices[k][0]][u]++; + } + for (int l = 0; l < m; l++) { + a[l][indices[k][1]]++; + } + } + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (a[i][j] % 2 != 0) { + c++; + } + } + } + return c; + } +} diff --git a/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.kt b/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.kt new file mode 100644 index 00000000..1dd1a84d --- /dev/null +++ b/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.kt @@ -0,0 +1,22 @@ +class Solution { + fun oddCells(m: Int, n: Int, indices: Array): Int { + val a = Array(m) { IntArray(n) { 0 } } + var c = 0 + for (k in indices) { + for (u in 0 until n) { + a[k[0]][u]++ + } + for (l in 0 until m) { + a[l][k[1]]++ + } + } + for (i in 0 until m) { + for (j in 0 until n) { + if (a[i][j] % 2 != 0) { + c++ + } + } + } + return c + } +} diff --git a/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.py b/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.py new file mode 100644 index 00000000..ee197492 --- /dev/null +++ b/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.py @@ -0,0 +1,19 @@ +class Solution(object): + def oddCells(self, m, n, indices): + a = [] + c = 0 + for i in range(m): + l = [] + for j in range(n): + l.append(0) + a.append(l) + for k in indices: + for u in range(n): + a[k[0]][u] += 1 + for l in range(m): + a[l][k[1]] += 1 + for i in a: + for j in i: + if j % 2 != 0: + c += 1 + return c diff --git a/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.py2 b/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.py2 new file mode 100644 index 00000000..851e6d26 --- /dev/null +++ b/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.py2 @@ -0,0 +1,25 @@ +class Solution(object): + def oddCells(self, m, n, indices): + """ + :type m: int + :type n: int + :type indices: List[List[int]] + :rtype: int + """ + a=[] + c=0 + for i in range(m): + l=[] + for j in range(n): + l.append(0) + a.append(l) + for k in indices: + for u in range(n): + a[k[0]][u]+=1 + for l in range(m): + a[l][k[1]]+=1 + for i in a: + for j in i: + if j%2!=0: + c+=1 + return c diff --git a/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.rb b/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.rb new file mode 100644 index 00000000..3e9e0665 --- /dev/null +++ b/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.rb @@ -0,0 +1,31 @@ +# @param {Integer} m +# @param {Integer} n +# @param {Integer[][]} indices +# @return {Integer} +def odd_cells(m, n, indices) + a = [] + c = 0 + (0...m).each do |i| + l = [] + (0...n).each do |j| + l.append(0) + end + a.append(l) + end + indices.each do |k| + (0...n).each do |u| + a[k[0]][u] += 1 + end + (0...m).each do |l| + a[l][k[1]] += 1 + end + end + a.each do |i| + i.each do |j| + if j % 2 != 0 + c += 1 + end + end + end + return c +end diff --git a/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.rs b/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.rs new file mode 100644 index 00000000..82c47b42 --- /dev/null +++ b/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.rs @@ -0,0 +1,24 @@ +impl Solution { + pub fn odd_cells(m: i32, n: i32, indices: Vec>) -> i32 { + let m = m as usize; + let n = n as usize; + let mut a = vec![vec![0; n]; m]; + let mut c = 0; + for k in &indices { + for u in 0..n { + a[k[0] as usize][u] += 1; + } + for l in 0..m { + a[l][k[1] as usize] += 1; + } + } + for i in 0..m { + for j in 0..n { + if a[i][j] % 2 != 0 { + c += 1; + } + } + } + c + } +} diff --git a/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.swift b/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.swift new file mode 100644 index 00000000..442252da --- /dev/null +++ b/tests/1001-1500/1252. cells-with-odd-values-in-a-matrix/sol.swift @@ -0,0 +1,22 @@ +class Solution { + func oddCells(_ m: Int, _ n: Int, _ indices: [[Int]]) -> Int { + var a = Array(repeating: Array(repeating: 0, count: n), count: m) + var c = 0 + for k in indices { + for u in 0.. Array(n).fill(0)); + let c: number = 0; + for (const k of indices) { + for (let u = 0; u < n; u++) { + a[k[0]][u]++; + } + for (let l = 0; l < m; l++) { + a[l][k[1]]++; + } + } + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + if (a[i][j] % 2 !== 0) { + c++; + } + } + } + return c; +} diff --git a/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/manifest.yaml b/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/manifest.yaml new file mode 100644 index 00000000..467e87f6 --- /dev/null +++ b/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/manifest.yaml @@ -0,0 +1,887 @@ +entry: + id: 1253 + title: "reconstruct-a-2-row-binary-matrix" + params: + upper: + type: int + lower: + type: int + colsum: + type: array + items: + type: int + call: + cpp: "Solution().reconstructMatrix({upper}, {lower}, {colsum})" + rust: "Solution::reconstruct_matrix({upper}, {lower}, {colsum})" + python3: "Solution().reconstructMatrix({upper}, {lower}, {colsum})" + python2: "Solution().reconstructMatrix({upper}, {lower}, {colsum})" + ruby: "reconstruct_matrix({upper}, {lower}, {colsum})" + java: "new Solution().reconstructMatrix({upper}, {lower}, {colsum})" + csharp: "new Solution().ReconstructMatrix({upper}, {lower}, {colsum})" + kotlin: "Solution().reconstructMatrix({upper}, {lower}, {colsum})" + go: "reconstructMatrix({upper}, {lower}, {colsum})" + dart: "Solution().reconstructMatrix({upper}, {lower}, {colsum})" + swift: "Solution().reconstructMatrix({upper}, {lower}, {colsum})" + typescript: "reconstructMatrix({upper}, {lower}, {colsum})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().reconstructMatrix(upper, lower, colsum, {result})" + checker: | + class Checker: + def reconstructMatrix(self, upper, lower, colsum, result): + double_columns = sum(value == 2 for value in colsum) + single_columns = sum(value == 1 for value in colsum) + top_single = upper - double_columns + bottom_single = lower - double_columns + feasible = ( + upper + lower == sum(colsum) + and top_single >= 0 + and bottom_single >= 0 + and top_single + bottom_single == single_columns + ) + if not feasible: + return result == [] + if type(result) is not list or len(result) != 2: + return False + if any(type(row) is not list or len(row) != len(colsum) for row in result): + return False + if any(type(value) is not int or value not in (0, 1) for row in result for value in row): + return False + return ( + sum(result[0]) == upper + and sum(result[1]) == lower + and all(result[0][i] + result[1][i] == colsum[i] for i in range(len(colsum)))) + +seed: 1253 + +tests: + - name: "example-one" + in: + upper: 2 + lower: 1 + colsum: [1, 1, 1] + - name: "example-two-infeasible" + in: + upper: 2 + lower: 3 + colsum: [2, 2, 1, 1] + out: [] + - name: "example-three" + in: + upper: 5 + lower: 5 + colsum: [2, 1, 2, 0, 1, 0, 1, 2, 0, 1] + - name: "single-top" + in: + upper: 1 + lower: 0 + colsum: [1] + - name: "single-bottom" + in: + upper: 0 + lower: 1 + colsum: [1] + - name: "single-double" + in: + upper: 1 + lower: 1 + colsum: [2] + - name: "single-zero-infeasible" + in: + upper: 1 + lower: 0 + colsum: [0] + out: [] + - name: "all-zero" + in: + upper: 0 + lower: 0 + colsum: [0, 0, 0, 0] + - name: "all-double" + in: + upper: 4 + lower: 4 + colsum: [2, 2, 2, 2] + - name: "too-many-doubles" + in: + upper: 1 + lower: 3 + colsum: [2, 2] + out: [] + - name: "total-too-high" + in: + upper: 3 + lower: 0 + colsum: [1, 1] + out: [] + - name: "total-too-low" + in: + upper: 0 + lower: 0 + colsum: [1, 1] + out: [] + - name: "balanced-single-columns" + in: + upper: 2 + lower: 2 + colsum: [1, 1, 1, 1] + - name: "top-heavy-single-columns" + in: + upper: 3 + lower: 1 + colsum: [1, 1, 1, 1] + - name: "bottom-heavy-single-columns" + in: + upper: 1 + lower: 3 + colsum: [1, 1, 1, 1] + - name: "mixed-doubles-and-zeros" + in: + upper: 3 + lower: 3 + colsum: [2, 1, 0, 2, 1] + - name: "mixed-infeasible-total" + in: + upper: 2 + lower: 2 + colsum: [2, 2, 1] + out: [] + - name: "alternating-one-two" + in: + upper: 5 + lower: 4 + colsum: [1, 2, 1, 2, 1, 2] + - name: "zeros-between-required-columns" + in: + upper: 3 + lower: 3 + colsum: [0, 1, 2, 0, 1, 2] + - name: "interspersed-valid" + in: + upper: 5 + lower: 5 + colsum: [1, 0, 2, 1, 2, 0, 1, 2, 1, 0] + - name: "long-total-mismatch" + in: + upper: 5 + lower: 4 + colsum: [2, 2, 1, 1, 0, 0, 0, 0, 0, 0] + out: [] + - name: "all-single-top" + in: + upper: 6 + lower: 0 + colsum: [1, 1, 1, 1, 1, 1] + - name: "all-single-bottom" + in: + upper: 0 + lower: 6 + colsum: [1, 1, 1, 1, 1, 1] + - name: "boundary-values" + in: + upper: 4 + lower: 4 + colsum: [2, 0, 1, 1, 2, 0, 1, 1] + - name: "double-budget-failure" + in: + upper: 2 + lower: 3 + colsum: [2, 2, 2, 1] + out: [] + - name: "single-columns-insufficient" + in: + upper: 4 + lower: 1 + colsum: [2, 2, 1, 1] + out: [] + - name: "all-one-even" + in: + upper: 5 + lower: 5 + colsum: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - name: "all-one-uneven" + in: + upper: 6 + lower: 4 + colsum: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - name: "double-at-last-column" + in: + upper: 4 + lower: 3 + colsum: [1, 1, 1, 1, 1, 2] + - name: "double-at-first-column" + in: + upper: 4 + lower: 3 + colsum: [2, 1, 1, 1, 1, 1] + - name: "balanced-doubles-with-one-columns" + in: + upper: 7 + lower: 7 + colsum: [2, 1, 2, 1, 2, 1, 2, 1, 1, 1] + - name: "all-slots-consumed-by-doubles" + in: + upper: 3 + lower: 3 + colsum: [2, 2, 2, 0, 0] + - name: "asymmetric-after-doubles" + in: + upper: 7 + lower: 3 + colsum: [2, 2, 2, 1, 1, 1, 1] + - name: "infeasible-despite-matching-total" + in: + upper: 1 + lower: 3 + colsum: [2, 2] + out: [] + - name: "wide-all-ones" + in: + upper: 61 + lower: 39 + colsum: + [ + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 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: "wide-all-doubles" + in: + upper: 100 + lower: 100 + colsum: + [ + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + ] + - name: "wide-all-zeros" + in: + upper: 0 + lower: 0 + colsum: + [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 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: "wide-doubles-then-zeros" + in: + upper: 50 + lower: 50 + colsum: + [ + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 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: "wide-mixed-balanced" + in: + upper: 50 + lower: 50 + colsum: + [ + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - name: "wide-mixed-asymmetric" + in: + upper: 30 + lower: 20 + colsum: + [ + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 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, + ] diff --git a/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.cpp b/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.cpp new file mode 100644 index 00000000..9b8a30e2 --- /dev/null +++ b/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + vector> reconstructMatrix(int upper, int lower, vector& colsum) { + int sum = 0; + for (int c : colsum) sum += c; + if (upper + lower != sum) return {}; + + int n = colsum.size(); + vector row1(n, 0), row2(n, 0); + + for (int i = 0; i < n; i++) { + if (colsum[i] == 2) { + row1[i] = 1; + row2[i] = 1; + upper--; + lower--; + } else if (colsum[i] == 1) { + if (upper > lower) { + row1[i] = 1; + upper--; + } else { + row2[i] = 1; + lower--; + } + } + } + + if (lower == 0 && upper == 0) return {row1, row2}; + return {}; + } +}; diff --git a/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.cs b/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.cs new file mode 100644 index 00000000..e0fa2524 --- /dev/null +++ b/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.cs @@ -0,0 +1,33 @@ +public class Solution { + public IList> ReconstructMatrix(int upper, int lower, int[] colsum) { + int sum = 0; + foreach (int c in colsum) sum += c; + if (upper + lower != sum) return new List>(); + + int n = colsum.Length; + int[] row1 = new int[n]; + int[] row2 = new int[n]; + + for (int i = 0; i < n; i++) { + if (colsum[i] == 2) { + row1[i] = 1; + row2[i] = 1; + upper--; + lower--; + } else if (colsum[i] == 1) { + if (upper > lower) { + row1[i] = 1; + upper--; + } else { + row2[i] = 1; + lower--; + } + } + } + + if (lower == 0 && upper == 0) { + return new List> { new List(row1), new List(row2) }; + } + return new List>(); + } +} diff --git a/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.dart b/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.dart new file mode 100644 index 00000000..b5636743 --- /dev/null +++ b/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.dart @@ -0,0 +1,29 @@ +class Solution { + List> reconstructMatrix(int upper, int lower, List colsum) { + int sum = colsum.fold(0, (a, b) => a + b); + if (upper + lower != sum) return []; + + int n = colsum.length; + List row1 = List.filled(n, 0); + List row2 = List.filled(n, 0); + + for (int i = 0; i < n; i++) { + if (colsum[i] == 2) { + row1[i] = 1; + row2[i] = 1; + upper--; + lower--; + } else if (colsum[i] == 1) { + if (upper > lower) { + row1[i] = 1; + upper--; + } else { + row2[i] = 1; + lower--; + } + } + } + + return lower == 0 && upper == 0 ? [row1, row2] : []; + } +} diff --git a/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.go b/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.go new file mode 100644 index 00000000..0501a145 --- /dev/null +++ b/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.go @@ -0,0 +1,35 @@ +func reconstructMatrix(upper int, lower int, colsum []int) [][]int { + sum := 0 + for _, c := range colsum { + sum += c + } + if upper+lower != sum { + return [][]int{} + } + + n := len(colsum) + row1 := make([]int, n) + row2 := make([]int, n) + + for i := 0; i < n; i++ { + if colsum[i] == 2 { + row1[i] = 1 + row2[i] = 1 + upper-- + lower-- + } else if colsum[i] == 1 { + if upper > lower { + row1[i] = 1 + upper-- + } else { + row2[i] = 1 + lower-- + } + } + } + + if lower == 0 && upper == 0 { + return [][]int{row1, row2} + } + return [][]int{} +} diff --git a/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.java b/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.java new file mode 100644 index 00000000..896165b3 --- /dev/null +++ b/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.java @@ -0,0 +1,40 @@ +class Solution { + public List> reconstructMatrix(int upper, int lower, int[] colsum) { + int sum = 0; + for (int c : colsum) sum += c; + if (upper + lower != sum) return new ArrayList<>(); + + int n = colsum.length; + List> res = new ArrayList<>(); + List row1 = new ArrayList<>(); + List row2 = new ArrayList<>(); + for (int i = 0; i < n; i++) { + row1.add(0); + row2.add(0); + } + + for (int i = 0; i < n; i++) { + if (colsum[i] == 2) { + row1.set(i, 1); + row2.set(i, 1); + upper--; + lower--; + } else if (colsum[i] == 1) { + if (upper > lower) { + row1.set(i, 1); + upper--; + } else { + row2.set(i, 1); + lower--; + } + } + } + + if (lower == 0 && upper == 0) { + res.add(row1); + res.add(row2); + return res; + } + return new ArrayList<>(); + } +} diff --git a/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.kt b/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.kt new file mode 100644 index 00000000..030dcaad --- /dev/null +++ b/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.kt @@ -0,0 +1,32 @@ +class Solution { + fun reconstructMatrix(upper: Int, lower: Int, colsum: IntArray): List> { + if (upper + lower != colsum.sum()) return emptyList() + val n = colsum.size + val row1 = MutableList(n) { 0 } + val row2 = MutableList(n) { 0 } + var u = upper + var l = lower + + for (i in 0 until n) { + when (colsum[i]) { + 2 -> { + row1[i] = 1 + row2[i] = 1 + u-- + l-- + } + 1 -> { + if (u > l) { + row1[i] = 1 + u-- + } else { + row2[i] = 1 + l-- + } + } + } + } + + return if (l == 0 && u == 0) listOf(row1, row2) else emptyList() + } +} diff --git a/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.py b/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.py new file mode 100644 index 00000000..b5b7541e --- /dev/null +++ b/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.py @@ -0,0 +1,24 @@ +class Solution: + def reconstructMatrix( + self, upper: int, lower: int, colsum: List[int] + ) -> List[List[int]]: + if upper + lower != sum(colsum): + return [] + n = len(colsum) + res = [[0] * n for _ in range(2)] + + for i in range(n): + if colsum[i] == 2: + res[0][i] = 1 + res[1][i] = 1 + upper -= 1 + lower -= 1 + elif colsum[i] == 1: + if upper > lower: + res[0][i] = 1 + upper -= 1 + else: + res[1][i] = 1 + lower -= 1 + + return res if lower == 0 and upper == 0 else [] diff --git a/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.py2 b/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.py2 new file mode 100644 index 00000000..61483ec3 --- /dev/null +++ b/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.py2 @@ -0,0 +1,28 @@ +class Solution(object): + def reconstructMatrix(self, upper, lower, colsum): + """ + :type upper: int + :type lower: int + :type colsum: List[int] + :rtype: List[List[int]] + """ + if upper + lower != sum(colsum): + return [] + n = len(colsum) + res = [[0] * n for _ in range(2)] + + for i in range(n): + if colsum[i] == 2: + res[0][i] = 1 + res[1][i] = 1 + upper -= 1 + lower -= 1 + elif colsum[i] == 1: + if upper > lower: + res[0][i] = 1 + upper -= 1 + else: + res[1][i] = 1 + lower -= 1 + + return res if lower == 0 and upper == 0 else [] diff --git a/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.rb b/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.rb new file mode 100644 index 00000000..927a0dae --- /dev/null +++ b/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.rb @@ -0,0 +1,29 @@ +# @param {Integer} upper +# @param {Integer} lower +# @param {Integer[]} colsum +# @return {Integer[][]} +def reconstruct_matrix(upper, lower, colsum) + return [] if upper + lower != colsum.sum + n = colsum.length + res = Array.new(2) { Array.new(n, 0) } + + (0...n).each do |i| + if colsum[i] == 2 + res[0][i] = 1 + res[1][i] = 1 + upper -= 1 + lower -= 1 + elsif colsum[i] == 1 + if upper > lower + res[0][i] = 1 + upper -= 1 + else + res[1][i] = 1 + lower -= 1 + end + end + end + + return res if lower == 0 && upper == 0 + [] +end diff --git a/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.rs b/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.rs new file mode 100644 index 00000000..15b4b459 --- /dev/null +++ b/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.rs @@ -0,0 +1,37 @@ +impl Solution { + pub fn reconstruct_matrix(upper: i32, lower: i32, colsum: Vec) -> Vec> { + let sum: i32 = colsum.iter().sum(); + if upper + lower != sum { + return vec![]; + } + + let n = colsum.len(); + let mut row1 = vec![0; n]; + let mut row2 = vec![0; n]; + let mut u = upper; + let mut l = lower; + + for i in 0..n { + if colsum[i] == 2 { + row1[i] = 1; + row2[i] = 1; + u -= 1; + l -= 1; + } else if colsum[i] == 1 { + if u > l { + row1[i] = 1; + u -= 1; + } else { + row2[i] = 1; + l -= 1; + } + } + } + + if l == 0 && u == 0 { + vec![row1, row2] + } else { + vec![] + } + } +} diff --git a/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.swift b/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.swift new file mode 100644 index 00000000..320eba24 --- /dev/null +++ b/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.swift @@ -0,0 +1,31 @@ +class Solution { + func reconstructMatrix(_ upper: Int, _ lower: Int, _ colsum: [Int]) -> [[Int]] { + let sum = colsum.reduce(0, +) + if upper + lower != sum { return [] } + + let n = colsum.count + var row1 = Array(repeating: 0, count: n) + var row2 = Array(repeating: 0, count: n) + var u = upper + var l = lower + + for i in 0.. l { + row1[i] = 1 + u -= 1 + } else { + row2[i] = 1 + l -= 1 + } + } + } + + return l == 0 && u == 0 ? [row1, row2] : [] + } +} diff --git a/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.ts b/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.ts new file mode 100644 index 00000000..f0b50a26 --- /dev/null +++ b/tests/1001-1500/1253. reconstruct-a-2-row-binary-matrix/sol.ts @@ -0,0 +1,31 @@ +function reconstructMatrix( + upper: number, + lower: number, + colsum: number[], +): number[][] { + const sum = colsum.reduce((a, b) => a + b, 0); + if (upper + lower !== sum) return []; + + const n = colsum.length; + const row1: number[] = new Array(n).fill(0); + const row2: number[] = new Array(n).fill(0); + + for (let i = 0; i < n; i++) { + if (colsum[i] === 2) { + row1[i] = 1; + row2[i] = 1; + upper--; + lower--; + } else if (colsum[i] === 1) { + if (upper > lower) { + row1[i] = 1; + upper--; + } else { + row2[i] = 1; + lower--; + } + } + } + + return lower === 0 && upper === 0 ? [row1, row2] : []; +} diff --git a/tests/1001-1500/1254. number-of-closed-islands/manifest.yaml b/tests/1001-1500/1254. number-of-closed-islands/manifest.yaml new file mode 100644 index 00000000..162cb8b7 --- /dev/null +++ b/tests/1001-1500/1254. number-of-closed-islands/manifest.yaml @@ -0,0 +1,421 @@ +entry: + id: 1254 + title: "number-of-closed-islands" + params: + grid: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().closedIsland({grid})" + rust: "Solution::closed_island({grid})" + python3: "Solution().closedIsland({grid})" + python2: "Solution().closedIsland({grid})" + ruby: "closed_island({grid})" + java: "new Solution().closedIsland({grid})" + csharp: "new Solution().ClosedIsland({grid})" + kotlin: "Solution().closedIsland({grid})" + go: "closedIsland({grid})" + dart: "Solution().closedIsland({grid})" + swift: "Solution().closedIsland({grid})" + typescript: "closedIsland({grid})" +judge: + type: "exact" +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().closedIsland(grid, {result})" + checker: | + class Checker: + def closedIsland(self, grid, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if not isinstance(grid, list) or not grid or not grid[0]: + return False + rows, cols = len(grid), len(grid[0]) + if any(not isinstance(row, list) or len(row) != cols for row in grid): + return False + if any(cell not in (0, 1) for row in grid for cell in row): + return False + seen = set() + closed_count = 0 + for row in range(rows): + for col in range(cols): + if grid[row][col] != 0 or (row, col) in seen: + continue + component = [(row, col)] + seen.add((row, col)) + touches_border = False + for r, c in component: + if r == 0 or c == 0 or r == rows - 1 or c == cols - 1: + touches_border = True + 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 and grid[nr][nc] == 0 and (nr, nc) not in seen: + seen.add((nr, nc)) + component.append((nr, nc)) + if not touches_border: + closed_count += 1 + return result == closed_count +seed: 1254 +tests: + - name: "example_one" + in: + grid: + - [1, 1, 1, 1, 1, 1, 1, 0] + - [1, 0, 0, 0, 0, 1, 1, 0] + - [1, 0, 1, 0, 1, 1, 1, 0] + - [1, 0, 0, 0, 0, 1, 0, 1] + - [1, 1, 1, 1, 1, 1, 1, 0] + out: 2 + - name: "example_two" + in: + grid: + - [0, 0, 1, 0, 0] + - [0, 1, 0, 1, 0] + - [0, 1, 1, 1, 0] + out: 1 + - name: "example_three" + in: + grid: + - [1, 1, 1, 1, 1, 1, 1] + - [1, 0, 0, 0, 0, 0, 1] + - [1, 0, 1, 1, 1, 0, 1] + - [1, 0, 1, 0, 1, 0, 1] + - [1, 0, 1, 1, 1, 0, 1] + - [1, 0, 0, 0, 0, 0, 1] + - [1, 1, 1, 1, 1, 1, 1] + out: 2 + - name: "one_cell_water" + in: + grid: + - [1] + out: 0 + - name: "one_cell_land" + in: + grid: + - [0] + out: 0 + - name: "one_row_mixed" + in: + grid: + - [1, 0, 1, 0, 1] + out: 0 + - name: "one_column_mixed" + in: + grid: + - [1] + - [0] + - [1] + out: 0 + - name: "all_water" + in: + grid: + - [1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1] + out: 0 + - name: "all_land" + in: + grid: + - [0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0] + out: 0 + - name: "enclosed_single_cell" + in: + grid: + - [1, 1, 1] + - [1, 0, 1] + - [1, 1, 1] + out: 1 + - name: "enclosed_block" + in: + grid: + - [1, 1, 1, 1] + - [1, 0, 0, 1] + - [1, 0, 0, 1] + - [1, 1, 1, 1] + out: 1 + - name: "two_separate_cells" + in: + grid: + - [1, 1, 1, 1, 1] + - [1, 0, 1, 0, 1] + - [1, 1, 1, 1, 1] + out: 2 + - name: "two_regions" + in: + grid: + - [1, 1, 1, 1, 1, 1] + - [1, 0, 1, 0, 0, 1] + - [1, 1, 1, 1, 1, 1] + out: 2 + - name: "diagonal_not_connected" + in: + grid: + - [1, 1, 1, 1, 1] + - [1, 0, 1, 0, 1] + - [1, 1, 1, 1, 1] + - [1, 0, 1, 0, 1] + - [1, 1, 1, 1, 1] + out: 4 + - name: "ring_with_water_center" + in: + grid: + - [1, 1, 1, 1, 1] + - [1, 0, 0, 0, 1] + - [1, 0, 1, 0, 1] + - [1, 0, 0, 0, 1] + - [1, 1, 1, 1, 1] + out: 1 + - name: "border_land_only" + in: + grid: + - [0, 0, 0, 0, 0] + - [0, 1, 1, 1, 0] + - [0, 1, 1, 1, 0] + - [0, 0, 0, 0, 0] + out: 0 + - name: "open_channel" + in: + grid: + - [1, 1, 1, 0, 1] + - [1, 0, 0, 0, 1] + - [1, 1, 1, 1, 1] + out: 0 + - name: "narrow_closed_corridor" + in: + grid: + - [1, 1, 1, 1, 1, 1, 1] + - [1, 0, 0, 0, 0, 0, 1] + - [1, 1, 1, 1, 1, 1, 1] + out: 1 + - name: "checkerboard_five" + in: + grid: + - [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] + out: 5 + - name: "checkerboard_six" + in: + grid: + - [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] + out: 8 + - name: "nested_islands" + in: + grid: + - [1, 1, 1, 1, 1, 1, 1] + - [1, 0, 0, 0, 0, 0, 1] + - [1, 0, 1, 1, 1, 0, 1] + - [1, 0, 1, 0, 1, 0, 1] + - [1, 0, 1, 1, 1, 0, 1] + - [1, 0, 0, 0, 0, 0, 1] + - [1, 1, 1, 1, 1, 1, 1] + out: 2 + - name: "four_disconnected_blocks" + in: + grid: + - [1, 1, 1, 1, 1, 1, 1, 1] + - [1, 0, 1, 0, 1, 0, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1] + - [1, 0, 0, 1, 0, 0, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1] + out: 5 + - name: "large_closed_rectangle" + in: + grid: + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 0, 0, 0, 0, 0, 0, 0, 0, 1] + - [1, 0, 0, 0, 0, 0, 0, 0, 0, 1] + - [1, 0, 0, 0, 0, 0, 0, 0, 0, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + out: 1 + - name: "split_by_water" + in: + grid: + - [1, 1, 1, 1, 1, 1, 1] + - [1, 0, 0, 1, 0, 0, 1] + - [1, 0, 0, 1, 0, 0, 1] + - [1, 1, 1, 1, 1, 1, 1] + out: 2 + - name: "open_left_and_closed_right" + in: + grid: + - [0, 0, 1, 1, 1, 1] + - [0, 1, 1, 0, 0, 1] + - [1, 1, 1, 0, 0, 1] + - [1, 1, 1, 1, 1, 1] + out: 1 + - name: "center_cross_water" + in: + grid: + - [1, 1, 1, 1, 1, 1, 1] + - [1, 0, 0, 1, 0, 0, 1] + - [1, 0, 1, 1, 1, 0, 1] + - [1, 1, 1, 1, 1, 1, 1] + out: 2 + - name: "alternating_enclosed_rows" + in: + grid: + - [1, 1, 1, 1, 1, 1] + - [1, 0, 0, 0, 0, 1] + - [1, 1, 1, 1, 1, 1] + - [1, 0, 0, 0, 0, 1] + - [1, 1, 1, 1, 1, 1] + out: 2 + - name: "full_inner_land" + in: + grid: + - [1, 1, 1, 1, 1, 1] + - [1, 0, 0, 0, 0, 1] + - [1, 0, 0, 0, 0, 1] + - [1, 0, 0, 0, 0, 1] + - [1, 1, 1, 1, 1, 1] + out: 1 + - name: "isolated_border_and_center" + in: + grid: + - [0, 1, 1, 1, 0] + - [1, 1, 1, 1, 1] + - [1, 1, 0, 1, 1] + - [1, 1, 1, 1, 1] + - [0, 1, 1, 1, 0] + out: 1 + - name: "winding_closed_path" + in: + grid: + - [1, 1, 1, 1, 1, 1, 1, 1] + - [1, 0, 0, 1, 1, 0, 0, 1] + - [1, 1, 0, 1, 1, 1, 0, 1] + - [1, 1, 0, 0, 0, 0, 0, 1] + - [1, 1, 1, 1, 1, 1, 1, 1] + out: 1 + - name: "vertical_closed_corridor" + in: + grid: + - [1, 1, 1] + - [1, 0, 1] + - [1, 0, 1] + - [1, 0, 1] + - [1, 1, 1] + out: 1 + - name: "four_quadrants" + in: + grid: + - [1, 1, 1, 1, 1, 1, 1] + - [1, 0, 0, 1, 0, 0, 1] + - [1, 0, 0, 1, 0, 0, 1] + - [1, 1, 1, 1, 1, 1, 1] + - [1, 0, 0, 1, 0, 0, 1] + - [1, 0, 0, 1, 0, 0, 1] + - [1, 1, 1, 1, 1, 1, 1] + out: 4 + - name: "diagonal_border_contact" + in: + grid: + - [0, 1, 1, 1, 1] + - [1, 0, 1, 0, 1] + - [1, 1, 0, 1, 1] + - [1, 0, 1, 0, 1] + - [1, 1, 1, 1, 1] + out: 5 + - name: "open_component_near_closed_cell" + in: + grid: + - [1, 1, 0, 1, 1, 1] + - [1, 0, 0, 0, 1, 1] + - [1, 1, 1, 1, 1, 1] + - [1, 1, 0, 1, 0, 1] + - [1, 1, 1, 1, 1, 1] + out: 2 + - name: "nine_isolated_inner_cells" + in: + grid: + - [1, 1, 1, 1, 1, 1, 1] + - [1, 0, 1, 0, 1, 0, 1] + - [1, 1, 1, 1, 1, 1, 1] + - [1, 0, 1, 0, 1, 0, 1] + - [1, 1, 1, 1, 1, 1, 1] + - [1, 0, 1, 0, 1, 0, 1] + - [1, 1, 1, 1, 1, 1, 1] + out: 9 + - name: "generated_dense_60_square" + seed: 1101 + in: + grid: + gen: "array" + len: 60 + of: + gen: "array" + len: 60 + of: + gen: "int" + min: 0 + max: 1 + - name: "generated_dense_80_square" + seed: 1102 + in: + grid: + gen: "array" + len: 80 + of: + gen: "array" + len: 80 + of: + gen: "int" + min: 0 + max: 1 + - name: "generated_dense_100_square" + seed: 1103 + in: + grid: + gen: "array" + len: 100 + of: + gen: "array" + len: 100 + of: + gen: "int" + min: 0 + max: 1 + - name: "generated_dense_100_by_80" + seed: 1104 + in: + grid: + gen: "array" + len: 100 + of: + gen: "array" + len: 80 + of: + gen: "int" + min: 0 + max: 1 + - name: "generated_dense_80_by_100" + seed: 1105 + in: + grid: + gen: "array" + len: 80 + of: + gen: "array" + len: 100 + of: + gen: "int" + min: 0 + max: 1 diff --git a/tests/1001-1500/1254. number-of-closed-islands/sol.cpp b/tests/1001-1500/1254. number-of-closed-islands/sol.cpp new file mode 100644 index 00000000..d651879e --- /dev/null +++ b/tests/1001-1500/1254. number-of-closed-islands/sol.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + int closedIsland(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + int res = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == 1) continue; + stack> st; + st.push({i, j}); + grid[i][j] = 1; + bool closed = true; + while (!st.empty()) { + auto [r, c] = st.top(); st.pop(); + if (r == 0 || c == 0 || r == m - 1 || c == n - 1) + closed = false; + vector> dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + for (auto [dr, dc] : dirs) { + int nr = r + dr, nc = c + dc; + if (nr >= 0 && nr < m && nc >= 0 && nc < n && grid[nr][nc] == 0) { + grid[nr][nc] = 1; + st.push({nr, nc}); + } + } + } + if (closed) res++; + } + } + return res; + } +}; diff --git a/tests/1001-1500/1254. number-of-closed-islands/sol.cs b/tests/1001-1500/1254. number-of-closed-islands/sol.cs new file mode 100644 index 00000000..83843e3d --- /dev/null +++ b/tests/1001-1500/1254. number-of-closed-islands/sol.cs @@ -0,0 +1,30 @@ +public class Solution { + public int ClosedIsland(int[][] grid) { + int m = grid.Length, n = grid[0].Length; + int res = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == 1) continue; + Stack<(int, int)> stack = new Stack<(int, int)>(); + stack.Push((i, j)); + grid[i][j] = 1; + bool closed = true; + while (stack.Count > 0) { + var (r, c) = stack.Pop(); + if (r == 0 || c == 0 || r == m - 1 || c == n - 1) + closed = false; + (int, int)[] dirs = { (1, 0), (-1, 0), (0, 1), (0, -1) }; + foreach (var (dr, dc) in dirs) { + int nr = r + dr, nc = c + dc; + if (nr >= 0 && nr < m && nc >= 0 && nc < n && grid[nr][nc] == 0) { + grid[nr][nc] = 1; + stack.Push((nr, nc)); + } + } + } + if (closed) res++; + } + } + return res; + } +} diff --git a/tests/1001-1500/1254. number-of-closed-islands/sol.dart b/tests/1001-1500/1254. number-of-closed-islands/sol.dart new file mode 100644 index 00000000..9b49996c --- /dev/null +++ b/tests/1001-1500/1254. number-of-closed-islands/sol.dart @@ -0,0 +1,32 @@ +class Solution { + int closedIsland(List> grid) { + int m = grid.length, n = grid[0].length; + int res = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == 1) continue; + List> stack = []; + stack.add([i, j]); + grid[i][j] = 1; + bool closed = true; + while (stack.isNotEmpty) { + List cur = stack.removeLast(); + int r = cur[0], c = cur[1]; + if (r == 0 || c == 0 || r == m - 1 || c == n - 1) { + closed = false; + } + List> dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]]; + for (var d in dirs) { + int nr = r + d[0], nc = c + d[1]; + if (nr >= 0 && nr < m && nc >= 0 && nc < n && grid[nr][nc] == 0) { + grid[nr][nc] = 1; + stack.add([nr, nc]); + } + } + } + if (closed) res++; + } + } + return res; + } +} diff --git a/tests/1001-1500/1254. number-of-closed-islands/sol.go b/tests/1001-1500/1254. number-of-closed-islands/sol.go new file mode 100644 index 00000000..9f3ff48f --- /dev/null +++ b/tests/1001-1500/1254. number-of-closed-islands/sol.go @@ -0,0 +1,34 @@ +func closedIsland(grid [][]int) int { + m, n := len(grid), len(grid[0]) + res := 0 + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if grid[i][j] == 1 { + continue + } + stack := [][]int{{i, j}} + grid[i][j] = 1 + closed := true + for len(stack) > 0 { + cur := stack[len(stack)-1] + stack = stack[:len(stack)-1] + r, c := cur[0], cur[1] + if r == 0 || c == 0 || r == m-1 || c == n-1 { + closed = false + } + dirs := [][]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}} + for _, d := range dirs { + nr, nc := r+d[0], c+d[1] + if nr >= 0 && nr < m && nc >= 0 && nc < n && grid[nr][nc] == 0 { + grid[nr][nc] = 1 + stack = append(stack, []int{nr, nc}) + } + } + } + if closed { + res++ + } + } + } + return res +} diff --git a/tests/1001-1500/1254. number-of-closed-islands/sol.java b/tests/1001-1500/1254. number-of-closed-islands/sol.java new file mode 100644 index 00000000..558a9d94 --- /dev/null +++ b/tests/1001-1500/1254. number-of-closed-islands/sol.java @@ -0,0 +1,31 @@ +class Solution { + public int closedIsland(int[][] grid) { + int m = grid.length, n = grid[0].length; + int res = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == 1) continue; + Deque stack = new ArrayDeque<>(); + stack.push(new int[]{i, j}); + grid[i][j] = 1; + boolean closed = true; + while (!stack.isEmpty()) { + int[] cur = stack.pop(); + int r = cur[0], c = cur[1]; + if (r == 0 || c == 0 || r == m - 1 || c == n - 1) + closed = false; + int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + for (int[] d : dirs) { + int nr = r + d[0], nc = c + d[1]; + if (nr >= 0 && nr < m && nc >= 0 && nc < n && grid[nr][nc] == 0) { + grid[nr][nc] = 1; + stack.push(new int[]{nr, nc}); + } + } + } + if (closed) res++; + } + } + return res; + } +} diff --git a/tests/1001-1500/1254. number-of-closed-islands/sol.kt b/tests/1001-1500/1254. number-of-closed-islands/sol.kt new file mode 100644 index 00000000..25203bd0 --- /dev/null +++ b/tests/1001-1500/1254. number-of-closed-islands/sol.kt @@ -0,0 +1,31 @@ +class Solution { + fun closedIsland(grid: Array): Int { + val m = grid.size + val n = grid[0].size + var res = 0 + for (i in 0 until m) { + for (j in 0 until n) { + if (grid[i][j] == 1) continue + val stack = ArrayDeque>() + stack.addLast(i to j) + grid[i][j] = 1 + var closed = true + while (stack.isNotEmpty()) { + val (r, c) = stack.removeLast() + if (r == 0 || c == 0 || r == m - 1 || c == n - 1) + closed = false + for ((dr, dc) in listOf(1 to 0, -1 to 0, 0 to 1, 0 to -1)) { + val nr = r + dr + val nc = c + dc + if (nr in 0 until m && nc in 0 until n && grid[nr][nc] == 0) { + grid[nr][nc] = 1 + stack.addLast(nr to nc) + } + } + } + if (closed) res++ + } + } + return res + } +} diff --git a/tests/1001-1500/1254. number-of-closed-islands/sol.py b/tests/1001-1500/1254. number-of-closed-islands/sol.py new file mode 100644 index 00000000..49316af4 --- /dev/null +++ b/tests/1001-1500/1254. number-of-closed-islands/sol.py @@ -0,0 +1,23 @@ +class Solution: + def closedIsland(self, grid: List[List[int]]) -> int: + m, n = len(grid), len(grid[0]) + res = 0 + for i in range(m): + for j in range(n): + if grid[i][j]: + continue + stack = [(i, j)] + grid[i][j] = 1 + closed = True + while stack: + r, c = stack.pop() + if r == 0 or c == 0 or r == m - 1 or c == n - 1: + closed = 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 grid[nr][nc] == 0: + grid[nr][nc] = 1 + stack.append((nr, nc)) + if closed: + res += 1 + return res diff --git a/tests/1001-1500/1254. number-of-closed-islands/sol.py2 b/tests/1001-1500/1254. number-of-closed-islands/sol.py2 new file mode 100644 index 00000000..a472db08 --- /dev/null +++ b/tests/1001-1500/1254. number-of-closed-islands/sol.py2 @@ -0,0 +1,27 @@ +class Solution(object): + def closedIsland(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + m, n = len(grid), len(grid[0]) + res = 0 + for i in range(m): + for j in range(n): + if grid[i][j]: + continue + stack = [(i, j)] + grid[i][j] = 1 + closed = True + while stack: + r, c = stack.pop() + if r == 0 or c == 0 or r == m - 1 or c == n - 1: + closed = 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 grid[nr][nc] == 0: + grid[nr][nc] = 1 + stack.append((nr, nc)) + if closed: + res += 1 + return res diff --git a/tests/1001-1500/1254. number-of-closed-islands/sol.rb b/tests/1001-1500/1254. number-of-closed-islands/sol.rb new file mode 100644 index 00000000..9bccb183 --- /dev/null +++ b/tests/1001-1500/1254. number-of-closed-islands/sol.rb @@ -0,0 +1,29 @@ +# @param {Integer[][]} grid +# @return {Integer} +def closed_island(grid) + m, n = grid.length, grid[0].length + res = 0 + (0...m).each do |i| + (0...n).each do |j| + next if grid[i][j] == 1 + stack = [[i, j]] + grid[i][j] = 1 + closed = true + while !stack.empty? + r, c = stack.pop + if r == 0 || c == 0 || r == m - 1 || c == n - 1 + closed = false + end + [[1, 0], [-1, 0], [0, 1], [0, -1]].each do |dr, dc| + nr, nc = r + dr, c + dc + if nr >= 0 && nr < m && nc >= 0 && nc < n && grid[nr][nc] == 0 + grid[nr][nc] = 1 + stack.push([nr, nc]) + end + end + end + res += 1 if closed + end + end + res +end diff --git a/tests/1001-1500/1254. number-of-closed-islands/sol.rs b/tests/1001-1500/1254. number-of-closed-islands/sol.rs new file mode 100644 index 00000000..b83f4c97 --- /dev/null +++ b/tests/1001-1500/1254. number-of-closed-islands/sol.rs @@ -0,0 +1,40 @@ +impl Solution { + pub fn closed_island(grid: Vec>) -> i32 { + let mut grid = grid; + let m = grid.len(); + let n = grid[0].len(); + let mut res = 0; + for i in 0..m { + for j in 0..n { + if grid[i][j] == 1 { + continue; + } + let mut stack = vec![(i, j)]; + grid[i][j] = 1; + let mut closed = true; + while let Some((r, c)) = stack.pop() { + if r == 0 || c == 0 || r == m - 1 || c == n - 1 { + closed = false; + } + let dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]; + for (dr, dc) in &dirs { + let nr = r as i32 + dr; + let nc = c as i32 + dc; + if nr >= 0 && nr < m as i32 && nc >= 0 && nc < n as i32 { + let nr = nr as usize; + let nc = nc as usize; + if grid[nr][nc] == 0 { + grid[nr][nc] = 1; + stack.push((nr, nc)); + } + } + } + } + if closed { + res += 1; + } + } + } + res + } +} diff --git a/tests/1001-1500/1254. number-of-closed-islands/sol.swift b/tests/1001-1500/1254. number-of-closed-islands/sol.swift new file mode 100644 index 00000000..80a8585f --- /dev/null +++ b/tests/1001-1500/1254. number-of-closed-islands/sol.swift @@ -0,0 +1,31 @@ +class Solution { + func closedIsland(_ grid: [[Int]]) -> Int { + var grid = grid + let m = grid.count, n = grid[0].count + var res = 0 + for i in 0..= 0 && nr < m && nc >= 0 && nc < n && grid[nr][nc] == 0 { + grid[nr][nc] = 1 + stack.append((nr, nc)) + } + } + } + if closed { res += 1 } + } + } + return res + } +} diff --git a/tests/1001-1500/1254. number-of-closed-islands/sol.ts b/tests/1001-1500/1254. number-of-closed-islands/sol.ts new file mode 100644 index 00000000..77933af4 --- /dev/null +++ b/tests/1001-1500/1254. number-of-closed-islands/sol.ts @@ -0,0 +1,35 @@ +function closedIsland(grid: number[][]): number { + const m = grid.length, + n = grid[0].length; + let res = 0; + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + if (grid[i][j] === 1) continue; + const stack: [number, number][] = [[i, j]]; + grid[i][j] = 1; + let closed = true; + while (stack.length > 0) { + const [r, c] = stack.pop()!; + if (r === 0 || c === 0 || r === m - 1 || c === n - 1) { + closed = false; + } + const dirs: [number, number][] = [ + [1, 0], + [-1, 0], + [0, 1], + [0, -1], + ]; + for (const [dr, dc] of dirs) { + const nr = r + dr, + nc = c + dc; + if (nr >= 0 && nr < m && nc >= 0 && nc < n && grid[nr][nc] === 0) { + grid[nr][nc] = 1; + stack.push([nr, nc]); + } + } + } + if (closed) res++; + } + } + return res; +} diff --git a/tests/1001-1500/1255. maximum-score-words-formed-by-letters/manifest.yaml b/tests/1001-1500/1255. maximum-score-words-formed-by-letters/manifest.yaml new file mode 100644 index 00000000..4679051a --- /dev/null +++ b/tests/1001-1500/1255. maximum-score-words-formed-by-letters/manifest.yaml @@ -0,0 +1,1589 @@ +entry: + id: 1255 + title: maximum-score-words-formed-by-letters + params: + words: + type: array + items: + type: string + letters: + type: array + items: + type: char + score: + type: array + items: + type: int + call: + cpp: "Solution().maxScoreWords({words}, {letters}, {score})" + rust: "Solution::max_score_words({words}, {letters}, {score})" + python3: "Solution().maxScoreWords({words}, {letters}, {score})" + python2: "Solution().maxScoreWords({words}, {letters}, {score})" + ruby: "max_score_words({words}, {letters}, {score})" + java: "new Solution().maxScoreWords({words}, {letters}, {score})" + csharp: "new Solution().MaxScoreWords({words}, {letters}, {score})" + kotlin: "Solution().maxScoreWords({words}, {letters}, {score})" + go: "maxScoreWords({words}, {letters}, {score})" + dart: "Solution().maxScoreWords({words}, {letters}, {score})" + swift: "Solution().maxScoreWords({words}, {letters}, {score})" + typescript: "maxScoreWords({words}, {letters}, {score})" + +judge: + type: exact + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().maxScoreWords(words, letters, score, {result})" + checker: | + class Checker: + def maxScoreWords(self, words, letters, score, result): + available = [0] * 26 + for letter in letters: + available[ord(letter) - ord('a')] += 1 + + word_counts = [] + word_scores = [] + for word in words: + counts = [0] * 26 + total = 0 + for letter in word: + index = ord(letter) - ord('a') + counts[index] += 1 + total += score[index] + word_counts.append(counts) + word_scores.append(total) + + def search(index, remaining): + if index == len(words): + return 0 + best = search(index + 1, remaining) + counts = word_counts[index] + if all(counts[i] <= remaining[i] for i in range(26)): + next_remaining = [remaining[i] - counts[i] for i in range(26)] + best = max(best, word_scores[index] + search(index + 1, next_remaining)) + return best + + return type(result) is int and result == search(0, available) + +seed: 1255 + +tests: + - name: example_one + in: + words: ["dog", "cat", "dad", "good"] + letters: ["a", "a", "c", "d", "d", "d", "g", "o", "o"] + score: + [ + 1, + 0, + 9, + 5, + 0, + 0, + 3, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + out: 23 + - name: example_two + in: + words: ["xxxz", "ax", "bx", "cx"] + letters: ["z", "a", "b", "c", "x", "x", "x"] + score: + [ + 4, + 4, + 4, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 5, + 0, + 10, + ] + out: 27 + - name: example_three_missing_repeat + in: + words: ["leetcode"] + letters: ["l", "e", "t", "c", "o", "d"] + score: + [ + 0, + 0, + 1, + 1, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + ] + out: 0 + - name: single_feasible_word + in: + words: ["dog"] + letters: ["d", "o", "g"] + score: + [ + 1, + 1, + 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: 3 + - name: single_unavailable_word + in: + words: ["dog"] + letters: ["d", "o"] + score: + [ + 1, + 1, + 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: 0 + - name: duplicate_word_instances + in: + words: ["aa", "aa", "aa"] + letters: ["a", "a", "a", "a"] + score: + [ + 5, + 0, + 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: 20 + - name: repeated_letter_tradeoff + in: + words: ["aa", "ab"] + letters: ["a", "a", "b"] + score: + [ + 2, + 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: 4 + - name: disjoint_words_all_selected + in: + words: ["ab", "cd", "ef", "gh"] + letters: ["a", "b", "c", "d", "e", "f", "g", "h"] + score: + [ + 1, + 1, + 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: all_scores_zero + in: + words: ["abc", "ab"] + letters: ["a", "b", "c"] + score: + [ + 0, + 0, + 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: only_short_word_is_possible + in: + words: ["aaa", "bbb", "ab"] + letters: ["a", "a", "b", "b"] + score: + [ + 3, + 2, + 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: 5 + - name: high_value_z + in: + words: ["z", "zz"] + letters: ["z", "z"] + score: + [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 10, + ] + out: 20 + - name: prefer_complementary_short_words + in: + words: ["a", "bc", "abc"] + letters: ["a", "b", "c"] + score: + [ + 10, + 1, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + out: 12 + - name: overlap_pairing_optimum + in: + words: ["ab", "bc", "cd", "de"] + letters: ["a", "b", "c", "d", "e"] + score: + [ + 1, + 2, + 3, + 4, + 5, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + out: 14 + - name: duplicate_alternatives + in: + words: ["aa", "aa", "ab", "ba"] + letters: ["a", "a", "b"] + score: + [ + 3, + 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: 6 + - name: no_word_uses_available_letters + in: + words: ["abc", "def"] + letters: ["x", "y", "z"] + score: + [ + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + ] + out: 0 + - name: all_available_letters_consumed + in: + words: ["c", "d"] + letters: ["c", "d"] + score: + [ + 1, + 1, + 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: 2 + - name: equal_long_and_short_partitions + in: + words: ["abc", "ab", "c"] + letters: ["a", "b", "c"] + score: + [ + 5, + 4, + 3, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + out: 12 + - name: unavailable_long_word_with_feasible_subword + in: + words: ["apple", "pear", "ape"] + letters: ["a", "p", "p", "l", "e"] + score: + [ + 1, + 1, + 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: expensive_long_word + in: + words: ["zoo", "zoom", "oo"] + letters: ["z", "o", "o", "m"] + score: + [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 7, + 0, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 10, + ] + out: 21 + - name: four_independent_multiplicities + in: + words: ["a", "bb", "ccc", "dddd"] + letters: ["a", "b", "b", "c", "c", "c", "d", "d", "d", "d"] + score: + [ + 1, + 1, + 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: 10 + - name: fourteen_distinct_single_letter_words + in: + words: + ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n"] + letters: + ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n"] + score: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 1, + 2, + 3, + 4, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + out: 65 + - name: fourteen_competing_word_lengths + in: + words: + [ + "a", + "aa", + "aaa", + "aaaa", + "aaaaa", + "aaaaaa", + "aaaaaaa", + "aaaaaaaa", + "aaaaaaaaa", + "aaaaaaaaaa", + "aaaaaaaaaaa", + "aaaaaaaaaaaa", + "aaaaaaaaaaaaa", + "aaaaaaaaaaaaaa", + ] + letters: + ["a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a"] + score: + [ + 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, + ] + out: 14 + - name: maximum_word_length_feasible + in: + words: ["aaaaaaaaaaaaaaa"] + letters: + [ + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + ] + score: + [ + 10, + 0, + 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: 150 + - name: maximum_word_length_one_letter_short + in: + words: ["aaaaaaaaaaaaaaa"] + letters: + ["a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a"] + score: + [ + 10, + 0, + 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: maximum_letters_with_fourteen_words + in: + words: + [ + "aaaaaaa", + "aaaaaaa", + "aaaaaaa", + "aaaaaaa", + "aaaaaaa", + "aaaaaaa", + "aaaaaaa", + "aaaaaaa", + "aaaaaaa", + "aaaaaaa", + "aaaaaaa", + "aaaaaaa", + "aaaaaaa", + "aaaaaaa", + ] + letters: + [ + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + ] + score: + [ + 10, + 0, + 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: 980 + - name: score_zero_letters_do_not_reduce_optimum + in: + words: ["a", "ab", "b"] + letters: ["a", "b"] + score: + [ + 0, + 5, + 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: 5 + - name: high_value_disjoint_letters + in: + words: ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"] + letters: ["a", "b", "c", "d", "e"] + score: + [ + 10, + 9, + 8, + 7, + 6, + 5, + 4, + 3, + 2, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + out: 40 + - name: four_triples_share_four_letters + in: + words: ["abc", "abd", "acd", "bcd"] + letters: ["a", "b", "c", "d"] + score: + [ + 4, + 3, + 2, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + out: 9 + - name: choose_two_of_three_resource_pairs + in: + words: ["ab", "ac", "bc"] + letters: ["a", "b", "c", "c"] + score: + [ + 9, + 4, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + out: 15 + - name: repeated_low_value_letter_blocks_expensive_word + in: + words: ["aab", "ab", "b"] + letters: ["a", "b"] + score: + [ + 10, + 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: 11 + - name: anagram_words_compete_for_same_letters + in: + words: ["abc", "bca", "cab"] + letters: ["a", "b", "c", "a", "b", "c"] + score: + [ + 2, + 3, + 5, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + out: 20 + - name: unused_letters_are_allowed + in: + words: ["a", "bb"] + letters: ["a", "b", "b", "z", "z"] + score: + [ + 3, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 9, + ] + out: 7 + - name: zero_value_feasible_word_with_positive_alternative + in: + words: ["x", "xy", "y"] + letters: ["x", "y"] + score: + [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 7, + 0, + ] + out: 7 + - name: overlapping_long_words + in: + words: ["hello", "world", "low"] + letters: ["h", "e", "l", "l", "o", "w", "o", "r", "l", "d"] + score: + [ + 1, + 1, + 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: 10 + - name: one_letter_remainder_prevents_second_word + in: + words: ["abcd", "cde", "ef"] + letters: ["a", "b", "c", "d", "e", "f"] + score: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + out: 21 + - name: repeated_character_with_competing_combinations + in: + words: ["aab", "abb", "ab", "ab"] + letters: ["a", "a", "b", "b"] + score: + [ + 4, + 3, + 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: 14 + - name: words_with_nonpositive_available_score + in: + words: ["q", "qq", "r"] + letters: ["q", "q", "r"] + score: + [ + 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, + ] + out: 1 + - name: partition_beats_single_available_word + in: + words: ["abcd", "ab", "cd", "ad"] + letters: ["a", "b", "c", "d"] + score: + [ + 8, + 1, + 1, + 8, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + out: 18 + - name: subset_selection_under_large_alphabet + in: + words: ["az", "by", "cx", "dw"] + letters: ["a", "z", "b", "y", "c", "x", "d"] + score: + [ + 1, + 2, + 3, + 4, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 7, + 8, + 9, + ] + out: 30 + - name: maximum_score_per_character + in: + words: ["jjj", "j", "aa"] + letters: ["j", "j", "j", "a", "a"] + score: + [ + 10, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 10, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + out: 50 diff --git a/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.cpp b/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.cpp new file mode 100644 index 00000000..92a19443 --- /dev/null +++ b/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.cpp @@ -0,0 +1,44 @@ +class Solution { +public: + int maxScoreWords(vector& words, vector& letters, vector& score) { + vector freq(26, 0); + for (char c : letters) { + freq[c - 'a']++; + } + + int ans = 0; + + function, int)> comb = [&](int i, vector freq, int total) { + if (i == words.size()) { + ans = max(ans, total); + return; + } + + vector same = freq; + int rem = total; + vector tempFreq = freq; + bool full = true; + int newTotal = total; + + for (char ch : words[i]) { + int idx = ch - 'a'; + if (tempFreq[idx] == 0) { + full = false; + break; + } + tempFreq[idx]--; + newTotal += score[idx]; + } + + if (full) { + comb(i + 1, tempFreq, newTotal); + comb(i + 1, same, rem); + } else { + comb(i + 1, same, rem); + } + }; + + comb(0, freq, 0); + return ans; + } +}; diff --git a/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.cs b/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.cs new file mode 100644 index 00000000..70cd1573 --- /dev/null +++ b/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.cs @@ -0,0 +1,44 @@ +public class Solution { + private int ans = 0; + + public int MaxScoreWords(string[] words, char[] letters, int[] score) { + int[] freq = new int[26]; + foreach (char c in letters) { + freq[c - 'a']++; + } + + ans = 0; + Comb(0, words, freq, score, 0); + return ans; + } + + private void Comb(int i, string[] words, int[] freq, int[] score, int total) { + if (i == words.Length) { + ans = Math.Max(ans, total); + return; + } + + int[] same = (int[])freq.Clone(); + int rem = total; + int[] tempFreq = (int[])freq.Clone(); + bool full = true; + int newTotal = total; + + foreach (char ch in words[i]) { + int idx = ch - 'a'; + if (tempFreq[idx] == 0) { + full = false; + break; + } + tempFreq[idx]--; + newTotal += score[idx]; + } + + if (full) { + Comb(i + 1, words, tempFreq, score, newTotal); + Comb(i + 1, words, same, score, rem); + } else { + Comb(i + 1, words, same, score, rem); + } + } +} diff --git a/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.dart b/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.dart new file mode 100644 index 00000000..2b583230 --- /dev/null +++ b/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.dart @@ -0,0 +1,42 @@ +class Solution { + int maxScoreWords(List words, List letters, List score) { + List freq = List.filled(26, 0); + for (var c in letters) { + freq[c.codeUnitAt(0) - 'a'.codeUnitAt(0)]++; + } + + int ans = 0; + + void comb(int i, List freq, int total) { + if (i == words.length) { + if (total > ans) ans = total; + return; + } + + List same = List.from(freq); + int rem = total; + List tempFreq = List.from(freq); + bool full = true; + + for (var ch in words[i].split('')) { + int idx = ch.codeUnitAt(0) - 'a'.codeUnitAt(0); + if (tempFreq[idx] == 0) { + full = false; + break; + } + tempFreq[idx]--; + total += score[idx]; + } + + if (full) { + comb(i + 1, tempFreq, total); + comb(i + 1, same, rem); + } else { + comb(i + 1, same, rem); + } + } + + comb(0, freq, 0); + return ans; + } +} diff --git a/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.go b/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.go new file mode 100644 index 00000000..be3bf28a --- /dev/null +++ b/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.go @@ -0,0 +1,45 @@ +func maxScoreWords(words []string, letters []byte, score []int) int { + freq := make([]int, 26) + for _, c := range letters { + freq[c - 'a']++ + } + + ans := 0 + + var comb func(int, []int, int) + comb = func(i int, freq []int, total int) { + if i == len(words) { + if total > ans { + ans = total + } + return + } + + same := make([]int, 26) + copy(same, freq) + rem := total + full := true + tempFreq := make([]int, 26) + copy(tempFreq, freq) + + for _, ch := range words[i] { + idx := ch - 'a' + if tempFreq[idx] == 0 { + full = false + break + } + tempFreq[idx]-- + total += score[idx] + } + + if full { + comb(i + 1, tempFreq, total) + comb(i + 1, same, rem) + } else { + comb(i + 1, same, rem) + } + } + + comb(0, freq, 0) + return ans +} diff --git a/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.java b/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.java new file mode 100644 index 00000000..2d4e9d36 --- /dev/null +++ b/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.java @@ -0,0 +1,43 @@ +class Solution { + private int ans = 0; + + public int maxScoreWords(String[] words, char[] letters, int[] score) { + int[] freq = new int[26]; + for (char c : letters) { + freq[c - 'a']++; + } + + ans = 0; + comb(0, words, freq, score, 0); + return ans; + } + + private void comb(int i, String[] words, int[] freq, int[] score, int total) { + if (i == words.length) { + ans = Math.max(ans, total); + return; + } + + int[] same = freq.clone(); + int rem = total; + boolean full = true; + + for (char ch : words[i].toCharArray()) { + int idx = ch - 'a'; + if (freq[idx] == 0) { + full = false; + break; + } else { + freq[idx]--; + total += score[idx]; + } + } + + if (full) { + comb(i + 1, words, freq, score, total); + comb(i + 1, words, same, score, rem); + } else { + comb(i + 1, words, same, score, rem); + } + } +} diff --git a/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.kt b/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.kt new file mode 100644 index 00000000..9a529430 --- /dev/null +++ b/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.kt @@ -0,0 +1,24 @@ +class Solution { + fun maxScoreWords(words: Array, letters: CharArray, score: IntArray): Int { + val available = IntArray(26) + for (letter in letters) available[letter - 'a']++ + + fun search(index: Int): Int { + if (index == words.size) return 0 + var best = search(index + 1) + var value = 0 + var usable = true + for (letter in words[index]) { + val code = letter - 'a' + available[code]-- + value += score[code] + if (available[code] < 0) usable = false + } + if (usable) best = maxOf(best, value + search(index + 1)) + for (letter in words[index]) available[letter - 'a']++ + return best + } + + return search(0) + } +} diff --git a/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.py b/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.py new file mode 100644 index 00000000..5c6d5395 --- /dev/null +++ b/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.py @@ -0,0 +1,38 @@ +class Solution: + def comb(self, i, words, freq, score, ans, total): + + if i == len(words): + ans[0] = max(ans[0], total) + return + + same = freq[:] + rem = total + full = True + + for ch in words[i]: + if freq[ord(ch) - ord("a")] == 0: + full = False + break + else: + freq[ord(ch) - ord("a")] -= 1 + total += score[ord(ch) - ord("a")] + + if full: + self.comb(i + 1, words, freq, score, ans, total) + self.comb(i + 1, words, same, score, ans, rem) + else: + self.comb(i + 1, words, same, score, ans, rem) + + def maxScoreWords(self, words, letters, score): + + freq = [0] * 26 + for c in letters: + if isinstance(c, bool): + c = "t" if c else "f" + freq[ord(c) - ord("a")] += 1 + + ans = [0] + + self.comb(0, words, freq, score, ans, 0) + + return ans[0] diff --git a/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.py2 b/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.py2 new file mode 100644 index 00000000..2d0c4609 --- /dev/null +++ b/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.py2 @@ -0,0 +1,41 @@ +class Solution(object): + def maxScoreWords(self, words, letters, score): + """ + :type words: List[str] + :type letters: List[str] + :type score: List[int] + :rtype: int + """ + freq = [0] * 26 + for c in letters: + if isinstance(c, bool): + c = 't' if c else 'f' + freq[ord(c) - ord('a')] += 1 + + ans = [0] + + def comb(i, freq, total): + if i == len(words): + ans[0] = max(ans[0], total) + return + + same = freq[:] + rem = total + full = True + + for ch in words[i]: + if freq[ord(ch) - ord('a')] == 0: + full = False + break + else: + freq[ord(ch) - ord('a')] -= 1 + total += score[ord(ch) - ord('a')] + + if full: + comb(i + 1, freq, total) + comb(i + 1, same, rem) + else: + comb(i + 1, same, rem) + + comb(0, freq, 0) + return ans[0] diff --git a/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.rb b/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.rb new file mode 100644 index 00000000..4cd7ffb3 --- /dev/null +++ b/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.rb @@ -0,0 +1,45 @@ +# @param {String[]} words +# @param {Character[]} letters +# @param {Integer[]} score +# @return {Integer} +def max_score_words(words, letters, score) + freq = Array.new(26, 0) + letters.each do |c| + c = c.to_s + freq[c.ord - 'a'.ord] += 1 + end + + ans = [0] + + comb = lambda do |i, freq, total| + if i == words.length + ans[0] = [ans[0], total].max + return + end + + same = freq.dup + rem = total + full = true + + words[i].each_char do |ch| + idx = ch.ord - 'a'.ord + if freq[idx] == 0 + full = false + break + else + freq[idx] -= 1 + total += score[idx] + end + end + + if full + comb.call(i + 1, freq, total) + comb.call(i + 1, same, rem) + else + comb.call(i + 1, same, rem) + end + end + + comb.call(0, freq, 0) + ans[0] +end diff --git a/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.rs b/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.rs new file mode 100644 index 00000000..fdc94b61 --- /dev/null +++ b/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.rs @@ -0,0 +1,43 @@ +impl Solution { + pub fn max_score_words(words: Vec, letters: Vec, score: Vec) -> i32 { + let mut freq = vec![0; 26]; + for c in letters { + freq[(c as u8 - b'a') as usize] += 1; + } + + let mut ans = 0; + + fn comb(i: usize, words: &Vec, freq: Vec, score: &Vec, total: i32, ans: &mut i32) { + if i == words.len() { + *ans = (*ans).max(total); + return; + } + + let same = freq.clone(); + let rem = total; + let mut temp_freq = freq.clone(); + let mut full = true; + let mut new_total = total; + + for ch in words[i].chars() { + let idx = (ch as u8 - b'a') as usize; + if temp_freq[idx] == 0 { + full = false; + break; + } + temp_freq[idx] -= 1; + new_total += score[idx]; + } + + if full { + comb(i + 1, words, temp_freq, score, new_total, ans); + comb(i + 1, words, same, score, rem, ans); + } else { + comb(i + 1, words, same, score, rem, ans); + } + } + + comb(0, &words, freq, &score, 0, &mut ans); + ans + } +} diff --git a/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.swift b/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.swift new file mode 100644 index 00000000..4b89aa19 --- /dev/null +++ b/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.swift @@ -0,0 +1,43 @@ +class Solution { + func maxScoreWords(_ words: [String], _ letters: [Character], _ score: [Int]) -> Int { + var freq = Array(repeating: 0, count: 26) + for c in letters { + freq[Int(c.asciiValue! - Character("a").asciiValue!)] += 1 + } + + var ans = 0 + + func comb(_ i: Int, _ freq: [Int], _ total: Int) { + if i == words.count { + ans = max(ans, total) + return + } + + let same = freq + let rem = total + var tempFreq = freq + var newTotal = total + var full = true + + for ch in words[i] { + let idx = Int(ch.asciiValue! - Character("a").asciiValue!) + if tempFreq[idx] == 0 { + full = false + break + } + tempFreq[idx] -= 1 + newTotal += score[idx] + } + + if full { + comb(i + 1, tempFreq, newTotal) + comb(i + 1, same, rem) + } else { + comb(i + 1, same, rem) + } + } + + comb(0, freq, 0) + return ans + } +} diff --git a/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.ts b/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.ts new file mode 100644 index 00000000..8b8121df --- /dev/null +++ b/tests/1001-1500/1255. maximum-score-words-formed-by-letters/sol.ts @@ -0,0 +1,45 @@ +function maxScoreWords( + words: string[], + letters: string[], + score: number[], +): number { + const freq: number[] = new Array(26).fill(0); + for (const c of letters) { + freq[c.charCodeAt(0) - "a".charCodeAt(0)]++; + } + + let ans = 0; + + function comb(i: number, freq: number[], total: number): void { + if (i === words.length) { + ans = Math.max(ans, total); + return; + } + + const same = [...freq]; + const rem = total; + const tempFreq = [...freq]; + let full = true; + let newTotal = total; + + for (const ch of words[i]) { + const idx = ch.charCodeAt(0) - "a".charCodeAt(0); + if (tempFreq[idx] === 0) { + full = false; + break; + } + tempFreq[idx]--; + newTotal += score[idx]; + } + + if (full) { + comb(i + 1, tempFreq, newTotal); + comb(i + 1, same, rem); + } else { + comb(i + 1, same, rem); + } + } + + comb(0, freq, 0); + return ans; +} diff --git a/tests/1001-1500/1260. shift-2d-grid/manifest.yaml b/tests/1001-1500/1260. shift-2d-grid/manifest.yaml new file mode 100644 index 00000000..721488f4 --- /dev/null +++ b/tests/1001-1500/1260. shift-2d-grid/manifest.yaml @@ -0,0 +1,1025 @@ +entry: + id: 1260 + title: "shift-2d-grid" + params: + grid: + type: array + items: + type: array + items: + type: int + k: + type: int + call: + python3: "Solution().shiftGrid({grid}, {k})" + python2: "Solution().shiftGrid({grid}, {k})" + cpp: "Solution().shiftGrid({grid}, {k})" + rust: "Solution::shift_grid({grid}, {k})" + ruby: "shift_grid({grid}, {k})" + java: "new Solution().shiftGrid({grid}, {k})" + csharp: "new Solution().ShiftGrid({grid}, {k})" + kotlin: "Solution().shiftGrid({grid}, {k})" + go: "shiftGrid({grid}, {k})" + dart: "Solution().shiftGrid({grid}, {k})" + swift: "Solution().shiftGrid({grid}, {k})" + typescript: "shiftGrid({grid}, {k})" +judge: + type: "exact" +limits: + time_ms: 500 + memory_mb: 300 +oracle: + python3: + call: "Checker().shiftGrid(grid, k, {result})" + checker: | + class Checker: + def shiftGrid(self, grid, k, result): + if not isinstance(result, list) or len(result) != len(grid): + return False + width = len(grid[0]) + if any(not isinstance(row, list) or len(row) != width for row in result): + return False + flat = [value for row in grid for value in row] + shift = k % len(flat) + expected = flat[-shift:] + flat[:-shift] if shift else flat + return result == [expected[i:i + width] for i in range(0, len(expected), width)] +seed: 1260 +tests: + - name: "example_one_shift" + in: + grid: + - [1, 2, 3] + - [4, 5, 6] + - [7, 8, 9] + k: 1 + out: + - [9, 1, 2] + - [3, 4, 5] + - [6, 7, 8] + - name: "example_four_by_four" + in: + grid: + - [3, 8, 1, 9] + - [19, 7, 2, 5] + - [4, 6, 11, 10] + - [12, 0, 21, 13] + k: 4 + out: + - [12, 0, 21, 13] + - [3, 8, 1, 9] + - [19, 7, 2, 5] + - [4, 6, 11, 10] + - name: "example_full_cycle" + in: + grid: + - [1, 2, 3] + - [4, 5, 6] + - [7, 8, 9] + k: 9 + out: + - [1, 2, 3] + - [4, 5, 6] + - [7, 8, 9] + - name: "zero_shift" + in: + grid: + - [5, 4, 3] + - [2, 1, 0] + k: 0 + out: + - [5, 4, 3] + - [2, 1, 0] + - name: "singleton_max_k" + in: + grid: + - [-1000] + k: 100 + out: + - [-1000] + - name: "single_row_one_shift" + in: + grid: + - [1, 2, 3, 4, 5] + k: 1 + out: + - [5, 1, 2, 3, 4] + - name: "single_column_one_shift" + in: + grid: + - [1] + - [2] + - [3] + - [4] + - [5] + k: 1 + out: + - [5] + - [1] + - [2] + - [3] + - [4] + - name: "two_by_two_half_cycle" + in: + grid: + - [1, 2] + - [3, 4] + k: 2 + out: + - [3, 4] + - [1, 2] + - name: "two_by_three_one_before_cycle" + in: + grid: + - [1, 2, 3] + - [4, 5, 6] + k: 5 + out: + - [2, 3, 4] + - [5, 6, 1] + - name: "three_by_two_half_cycle" + in: + grid: + - [1, 2] + - [3, 4] + - [5, 6] + k: 3 + out: + - [4, 5] + - [6, 1] + - [2, 3] + - name: "negative_values" + in: + grid: + - [-1, -2] + - [-3, -4] + k: 3 + out: + - [-2, -3] + - [-4, -1] + - name: "duplicate_values" + in: + grid: + - [7, 7, 1] + - [7, 2, 7] + k: 3 + out: + - [7, 2, 7] + - [7, 7, 1] + - name: "integer_extremes" + in: + grid: + - [-1000, 0] + - [1000, -999] + k: 1 + out: + - [-999, -1000] + - [0, 1000] + - name: "wide_two_by_five" + in: + grid: + - [1, 2, 3, 4, 5] + - [6, 7, 8, 9, 10] + k: 7 + out: + - [4, 5, 6, 7, 8] + - [9, 10, 1, 2, 3] + - name: "tall_five_by_two" + in: + grid: + - [1, 2] + - [3, 4] + - [5, 6] + - [7, 8] + - [9, 10] + k: 6 + out: + - [5, 6] + - [7, 8] + - [9, 10] + - [1, 2] + - [3, 4] + - name: "three_by_four_one_shift" + in: + grid: + - [1, 2, 3, 4] + - [5, 6, 7, 8] + - [9, 10, 11, 12] + k: 1 + out: + - [12, 1, 2, 3] + - [4, 5, 6, 7] + - [8, 9, 10, 11] + - name: "k_hundred_mod_twelve" + in: + grid: + - [1, 2, 3, 4] + - [5, 6, 7, 8] + - [9, 10, 11, 12] + k: 100 + out: + - [9, 10, 11, 12] + - [1, 2, 3, 4] + - [5, 6, 7, 8] + - name: "seven_by_seven_modulo" + 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] + k: 100 + out: + - [48, 49, 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] + - name: "six_by_eight_modulo" + 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: 100 + out: + - [45, 46, 47, 48, 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] + - name: "fifty_by_one_full_cycle" + 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] + k: 100 + 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] + - name: "two_by_twenty_five_left_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, + 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, + ] + k: 99 + 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, + 50, + 1, + ] + - name: "twenty_five_by_two_modulo" + 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] + k: 73 + out: + - [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] + - name: "ten_by_five_shift_twenty_seven" + 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] + k: 27 + out: + - [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] + - name: "five_by_ten_shift_thirty_seven" + 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] + k: 37 + out: + - [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] + - name: "four_by_six_one_before_cycle" + 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: 23 + out: + - [2, 3, 4, 5, 6, 7] + - [8, 9, 10, 11, 12, 13] + - [14, 15, 16, 17, 18, 19] + - [20, 21, 22, 23, 24, 1] + - name: "ten_by_ten_one_shift" + 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] + k: 1 + out: + - [100, 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: "ten_by_ten_half_cycle" + 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] + k: 50 + out: + - [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] + - [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: "ten_by_ten_left_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, 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: 99 + 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, 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, 1] + - name: "twelve_by_four_modulo" + 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: 100 + out: + - [45, 46, 47, 48] + - [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] + - name: "four_by_twelve_one_shift" + 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: 49 + out: + - [48, 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] + - name: "one_by_fifty_shift_forty_seven" + 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, + ] + k: 47 + out: + - [ + 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, + ] + - name: "fifty_by_one_shift_forty_seven" + 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] + k: 47 + out: + - [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] + - name: "three_by_three_shift_eight" + in: + grid: + - [-3, 0, 3] + - [-2, 0, 2] + - [-1, 0, 1] + k: 8 + out: + - [0, 3, -2] + - [0, 2, -1] + - [0, 1, -3] + - name: "three_by_five_one_before_cycle" + in: + grid: + - [1, 2, 3, 4, 5] + - [6, 7, 8, 9, 10] + - [11, 12, 13, 14, 15] + k: 14 + out: + - [2, 3, 4, 5, 6] + - [7, 8, 9, 10, 11] + - [12, 13, 14, 15, 1] + - name: "five_by_three_shift_seven" + in: + grid: + - [1, 2, 3] + - [4, 5, 6] + - [7, 8, 9] + - [10, 11, 12] + - [13, 14, 15] + k: 7 + out: + - [9, 10, 11] + - [12, 13, 14] + - [15, 1, 2] + - [3, 4, 5] + - [6, 7, 8] + - name: "generated_max_grid_low_shift" + seed: 126001 + in: + grid: + gen: "array" + len: 50 + of: + gen: "array" + len: 50 + of: + gen: "int" + min: -1000 + max: 1000 + k: 1 + - name: "generated_max_grid_mid_shift" + seed: 126002 + in: + grid: + gen: "array" + len: 50 + of: + gen: "array" + len: 50 + of: + gen: "int" + min: -1000 + max: 1000 + k: 37 + - name: "generated_max_grid_half_cycle" + seed: 126003 + in: + grid: + gen: "array" + len: 50 + of: + gen: "array" + len: 50 + of: + gen: "int" + min: -1000 + max: 1000 + k: 100 + - name: "generated_max_grid_zero_shift" + seed: 126004 + in: + grid: + gen: "array" + len: 50 + of: + gen: "array" + len: 50 + of: + gen: "int" + min: -1000 + max: 1000 + k: 0 + - name: "generated_max_grid_random_k" + seed: 126005 + in: + grid: + gen: "array" + len: 50 + of: + gen: "array" + len: 50 + of: + gen: "int" + min: -1000 + max: 1000 + k: + gen: "int" + min: 0 + max: 100 diff --git a/tests/1001-1500/1260. shift-2d-grid/sol.cpp b/tests/1001-1500/1260. shift-2d-grid/sol.cpp new file mode 100644 index 00000000..a176eb84 --- /dev/null +++ b/tests/1001-1500/1260. shift-2d-grid/sol.cpp @@ -0,0 +1,59 @@ +class Solution { +public: + vector> shiftGrid(vector>& grid, int k) { + int m = grid.size(); + int n = grid[0].size(); + int total = m * n; + k %= total; + if (k == 0) { + return grid; + } + + vector lastKElements(k); + int i = m - 1; + int x = n - 1; + int count = 0; + + while (count != k) { + lastKElements[count] = grid[i][x]; + if (x >= 1) { + x--; + } else { + i--; + x = n - 1; + } + count++; + } + + int j = m - 1; + int y = n - 1; + + while (i != 0 || x != -1) { + if (x == -1) { + i--; + x = n - 1; + } + if (y == -1) { + j--; + y = n - 1; + } + grid[j][y] = grid[i][x]; + x--; + y--; + } + + int idx = 0; + while (k > 0) { + if (y == -1) { + j--; + y = n - 1; + } + grid[j][y] = lastKElements[idx]; + y--; + k--; + idx++; + } + + return grid; + } +}; diff --git a/tests/1001-1500/1260. shift-2d-grid/sol.cs b/tests/1001-1500/1260. shift-2d-grid/sol.cs new file mode 100644 index 00000000..f642d1b8 --- /dev/null +++ b/tests/1001-1500/1260. shift-2d-grid/sol.cs @@ -0,0 +1,66 @@ +public class Solution { + public IList> ShiftGrid(int[][] grid, int k) { + int m = grid.Length; + int n = grid[0].Length; + int total = m * n; + k %= total; + if (k == 0) { + IList> result = new List>(); + foreach (var row in grid) { + result.Add(new List(row)); + } + return result; + } + + int[] lastKElements = new int[k]; + int i = m - 1; + int x = n - 1; + int count = 0; + + while (count != k) { + lastKElements[count] = grid[i][x]; + if (x >= 1) { + x--; + } else { + i--; + x = n - 1; + } + count++; + } + + int j = m - 1; + int y = n - 1; + + while (i != 0 || x != -1) { + if (x == -1) { + i--; + x = n - 1; + } + if (y == -1) { + j--; + y = n - 1; + } + grid[j][y] = grid[i][x]; + x--; + y--; + } + + int idx = 0; + while (k > 0) { + if (y == -1) { + j--; + y = n - 1; + } + grid[j][y] = lastKElements[idx]; + y--; + k--; + idx++; + } + + IList> finalResult = new List>(); + foreach (var row in grid) { + finalResult.Add(new List(row)); + } + return finalResult; + } +} diff --git a/tests/1001-1500/1260. shift-2d-grid/sol.dart b/tests/1001-1500/1260. shift-2d-grid/sol.dart new file mode 100644 index 00000000..7f78a184 --- /dev/null +++ b/tests/1001-1500/1260. shift-2d-grid/sol.dart @@ -0,0 +1,58 @@ +class Solution { + List> shiftGrid(List> grid, int k) { + int m = grid.length; + int n = grid[0].length; + int total = m * n; + k %= total; + if (k == 0) { + return grid; + } + + List lastKElements = List.filled(k, 0); + int i = m - 1; + int x = n - 1; + int count = 0; + + while (count != k) { + lastKElements[count] = grid[i][x]; + if (x >= 1) { + x--; + } else { + i--; + x = n - 1; + } + count++; + } + + int j = m - 1; + int y = n - 1; + + while (i != 0 || x != -1) { + if (x == -1) { + i--; + x = n - 1; + } + if (y == -1) { + j--; + y = n - 1; + } + grid[j][y] = grid[i][x]; + x--; + y--; + } + + int idx = 0; + while (k > 0) { + if (y == -1) { + j--; + y = n - 1; + } + grid[j][y] = lastKElements[idx]; + y--; + k--; + idx++; + } + + return grid; + } +} diff --git a/tests/1001-1500/1260. shift-2d-grid/sol.go b/tests/1001-1500/1260. shift-2d-grid/sol.go new file mode 100644 index 00000000..aa9a11a5 --- /dev/null +++ b/tests/1001-1500/1260. shift-2d-grid/sol.go @@ -0,0 +1,56 @@ +func shiftGrid(grid [][]int, k int) [][]int { + m := len(grid) + n := len(grid[0]) + total := m * n + k %= total + if k == 0 { + return grid + } + + lastKElements := make([]int, k) + i := m - 1 + x := n - 1 + count := 0 + + for count != k { + lastKElements[count] = grid[i][x] + if x >= 1 { + x-- + } else { + i-- + x = n - 1 + } + count++ + } + + j := m - 1 + y := n - 1 + + for i != 0 || x != -1 { + if x == -1 { + i-- + x = n - 1 + } + if y == -1 { + j-- + y = n - 1 + } + grid[j][y] = grid[i][x] + x-- + y-- + } + + idx := 0 + for k > 0 { + if y == -1 { + j-- + y = n - 1 + } + grid[j][y] = lastKElements[idx] + y-- + k-- + idx++ + } + + return grid +} diff --git a/tests/1001-1500/1260. shift-2d-grid/sol.java b/tests/1001-1500/1260. shift-2d-grid/sol.java new file mode 100644 index 00000000..a6acbf5c --- /dev/null +++ b/tests/1001-1500/1260. shift-2d-grid/sol.java @@ -0,0 +1,70 @@ +class Solution { + public List> shiftGrid(int[][] grid, int k) { + int m = grid.length; + int n = grid[0].length; + int total = m * n; + k %= total; + + if (k == 0) { + List> result = new ArrayList<>(); + for (int[] row : grid) { + List listRow = new ArrayList<>(); + for (int val : row) listRow.add(val); + result.add(listRow); + } + return result; + } + + int[] lastKElements = new int[k]; + int i = m - 1; + int x = n - 1; + int count = 0; + + while (count != k) { + lastKElements[count] = grid[i][x]; + if (x >= 1) x--; + else { + i--; + x = n - 1; + } + count++; + } + + int j = m - 1; + int y = n - 1; + + while (i != 0 || x != -1) { + if (x == -1) { + i--; + x = n - 1; + } + if (y == -1) { + j--; + y = n - 1; + } + grid[j][y] = grid[i][x]; + x--; + y--; + } + + int idx = 0; + while (k > 0) { + if (y == -1) { + j--; + y = n - 1; + } + grid[j][y] = lastKElements[idx]; + y--; + k--; + idx++; + } + + List> result = new ArrayList<>(); + for (int[] row : grid) { + List listRow = new ArrayList<>(); + for (int val : row) listRow.add(val); + result.add(listRow); + } + return result; + } +} diff --git a/tests/1001-1500/1260. shift-2d-grid/sol.kt b/tests/1001-1500/1260. shift-2d-grid/sol.kt new file mode 100644 index 00000000..0933d5f7 --- /dev/null +++ b/tests/1001-1500/1260. shift-2d-grid/sol.kt @@ -0,0 +1,57 @@ +class Solution { + fun shiftGrid(grid: Array, k: Int): List> { + val m = grid.size + val n = grid[0].size + val total = m * n + var k = k % total + if (k == 0) { + return grid.map { it.toList() } + } + + val lastKElements = IntArray(k) + var i = m - 1 + var x = n - 1 + var count = 0 + + while (count != k) { + lastKElements[count] = grid[i][x] + if (x >= 1) x-- + else { + i-- + x = n - 1 + } + count++ + } + + var j = m - 1 + var y = n - 1 + + while (i != 0 || x != -1) { + if (x == -1) { + i-- + x = n - 1 + } + if (y == -1) { + j-- + y = n - 1 + } + grid[j][y] = grid[i][x] + x-- + y-- + } + + var idx = 0 + while (k > 0) { + if (y == -1) { + j-- + y = n - 1 + } + grid[j][y] = lastKElements[idx] + y-- + k-- + idx++ + } + + return grid.map { it.toList() } + } +} diff --git a/tests/1001-1500/1260. shift-2d-grid/sol.py b/tests/1001-1500/1260. shift-2d-grid/sol.py new file mode 100644 index 00000000..ada260b6 --- /dev/null +++ b/tests/1001-1500/1260. shift-2d-grid/sol.py @@ -0,0 +1,61 @@ +# My code With GPT Explaination +class Solution: + def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]: + m, n = len(grid) - 1, len(grid[0]) - 1 + + # Reduce unnecessary full rotations + k %= (m + 1) * (n + 1) + + if k == 0: + return grid + + last_k_elements = [] + + # i, x -> pointer for reading elements from end + # j, y -> pointer for writing shifted elements + # count -> number of elements collected + i = j = m + x = y = n + count = 0 + + # Step 1: Collect the last k elements (reverse traversal) + while count != k: + last_k_elements.append(grid[i][x]) + + if x >= 1: + x -= 1 + else: + i -= 1 + x = n + + count += 1 + + # Step 2: Shift remaining elements to the right by k positions + while i != 0 or x != -1: + if x == -1: + i -= 1 + x = n + + if y == -1: + j -= 1 + y = n + + grid[j][y] = grid[i][x] + + x -= 1 + y -= 1 + + # Step 3: Place stored k elements at the beginning + idx = 0 + while k: + if y == -1: + j -= 1 + y = n + + grid[j][y] = last_k_elements[idx] + + y -= 1 + k -= 1 + idx += 1 + + return grid diff --git a/tests/1001-1500/1260. shift-2d-grid/sol.py2 b/tests/1001-1500/1260. shift-2d-grid/sol.py2 new file mode 100644 index 00000000..c674f8a2 --- /dev/null +++ b/tests/1001-1500/1260. shift-2d-grid/sol.py2 @@ -0,0 +1,53 @@ +class Solution(object): + def shiftGrid(self, grid, k): + """ + :type grid: List[List[int]] + :type k: int + :rtype: List[List[int]] + """ + m = len(grid) - 1 + n = len(grid[0]) - 1 + total = (m + 1) * (n + 1) + k %= total + if k == 0: + return grid + + last_k_elements = [] + i = m + x = n + count = 0 + + while count != k: + last_k_elements.append(grid[i][x]) + if x >= 1: + x -= 1 + else: + i -= 1 + x = n + count += 1 + + j = m + y = n + + while i != 0 or x != -1: + if x == -1: + i -= 1 + x = n + if y == -1: + j -= 1 + y = n + grid[j][y] = grid[i][x] + x -= 1 + y -= 1 + + idx = 0 + while k: + if y == -1: + j -= 1 + y = n + grid[j][y] = last_k_elements[idx] + y -= 1 + k -= 1 + idx += 1 + + return grid diff --git a/tests/1001-1500/1260. shift-2d-grid/sol.rb b/tests/1001-1500/1260. shift-2d-grid/sol.rb new file mode 100644 index 00000000..809290be --- /dev/null +++ b/tests/1001-1500/1260. shift-2d-grid/sol.rb @@ -0,0 +1,57 @@ +# @param {Integer[][]} grid +# @param {Integer} k +# @return {Integer[][]} +def shift_grid(grid, k) + m = grid.length - 1 + n = grid[0].length - 1 + total = (m + 1) * (n + 1) + k %= total + return grid if k == 0 + + last_k_elements = [] + i = m + x = n + count = 0 + + while count != k + last_k_elements << grid[i][x] + if x >= 1 + x -= 1 + else + i -= 1 + x = n + end + count += 1 + end + + j = m + y = n + + while i != 0 || x != -1 + if x == -1 + i -= 1 + x = n + end + if y == -1 + j -= 1 + y = n + end + grid[j][y] = grid[i][x] + x -= 1 + y -= 1 + end + + idx = 0 + while k > 0 + if y == -1 + j -= 1 + y = n + end + grid[j][y] = last_k_elements[idx] + y -= 1 + k -= 1 + idx += 1 + end + + grid +end diff --git a/tests/1001-1500/1260. shift-2d-grid/sol.rs b/tests/1001-1500/1260. shift-2d-grid/sol.rs new file mode 100644 index 00000000..e8b6b893 --- /dev/null +++ b/tests/1001-1500/1260. shift-2d-grid/sol.rs @@ -0,0 +1,59 @@ +impl Solution { + pub fn shift_grid(grid: Vec>, k: i32) -> Vec> { + let mut grid = grid; + let m = grid.len(); + let n = grid[0].len(); + let total = (m * n) as i32; + let mut k = k % total; + if k == 0 { + return grid; + } + + let mut last_k_elements: Vec = vec![0; k as usize]; + let mut i = m as i32 - 1; + let mut x = n as i32 - 1; + let mut count = 0; + + while count != k { + last_k_elements[count as usize] = grid[i as usize][x as usize]; + if x >= 1 { + x -= 1; + } else { + i -= 1; + x = n as i32 - 1; + } + count += 1; + } + + let mut j = m as i32 - 1; + let mut y = n as i32 - 1; + + while i != 0 || x != -1 { + if x == -1 { + i -= 1; + x = n as i32 - 1; + } + if y == -1 { + j -= 1; + y = n as i32 - 1; + } + grid[j as usize][y as usize] = grid[i as usize][x as usize]; + x -= 1; + y -= 1; + } + + let mut idx = 0; + while k > 0 { + if y == -1 { + j -= 1; + y = n as i32 - 1; + } + grid[j as usize][y as usize] = last_k_elements[idx]; + y -= 1; + k -= 1; + idx += 1; + } + + grid + } +} diff --git a/tests/1001-1500/1260. shift-2d-grid/sol.swift b/tests/1001-1500/1260. shift-2d-grid/sol.swift new file mode 100644 index 00000000..888b6607 --- /dev/null +++ b/tests/1001-1500/1260. shift-2d-grid/sol.swift @@ -0,0 +1,59 @@ +class Solution { + func shiftGrid(_ grid: [[Int]], _ k: Int) -> [[Int]] { + var grid = grid + let m = grid.count + let n = grid[0].count + let total = m * n + var k = k % total + if k == 0 { + return grid + } + + var lastKElements = [Int](repeating: 0, count: k) + var i = m - 1 + var x = n - 1 + var count = 0 + + while count != k { + lastKElements[count] = grid[i][x] + if x >= 1 { + x -= 1 + } else { + i -= 1 + x = n - 1 + } + count += 1 + } + + var j = m - 1 + var y = n - 1 + + while i != 0 || x != -1 { + if x == -1 { + i -= 1 + x = n - 1 + } + if y == -1 { + j -= 1 + y = n - 1 + } + grid[j][y] = grid[i][x] + x -= 1 + y -= 1 + } + + var idx = 0 + while k > 0 { + if y == -1 { + j -= 1 + y = n - 1 + } + grid[j][y] = lastKElements[idx] + y -= 1 + k -= 1 + idx += 1 + } + + return grid + } +} diff --git a/tests/1001-1500/1260. shift-2d-grid/sol.ts b/tests/1001-1500/1260. shift-2d-grid/sol.ts new file mode 100644 index 00000000..d9010061 --- /dev/null +++ b/tests/1001-1500/1260. shift-2d-grid/sol.ts @@ -0,0 +1,56 @@ +function shiftGrid(grid: number[][], k: number): number[][] { + const m = grid.length; + const n = grid[0].length; + const total = m * n; + k %= total; + if (k === 0) { + return grid; + } + + const lastKElements: number[] = new Array(k); + let i = m - 1; + let x = n - 1; + let count = 0; + + while (count !== k) { + lastKElements[count] = grid[i][x]; + if (x >= 1) { + x--; + } else { + i--; + x = n - 1; + } + count++; + } + + let j = m - 1; + let y = n - 1; + + while (i !== 0 || x !== -1) { + if (x === -1) { + i--; + x = n - 1; + } + if (y === -1) { + j--; + y = n - 1; + } + grid[j][y] = grid[i][x]; + x--; + y--; + } + + let idx = 0; + while (k > 0) { + if (y === -1) { + j--; + y = n - 1; + } + grid[j][y] = lastKElements[idx]; + y--; + k--; + idx++; + } + + return grid; +} diff --git a/tests/1001-1500/1262. greatest-sum-divisible-by-three/manifest.yaml b/tests/1001-1500/1262. greatest-sum-divisible-by-three/manifest.yaml new file mode 100644 index 00000000..ce5850db --- /dev/null +++ b/tests/1001-1500/1262. greatest-sum-divisible-by-three/manifest.yaml @@ -0,0 +1,269 @@ +entry: + id: 1262 + title: "greatest-sum-divisible-by-three" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().maxSumDivThree({nums})" + rust: "Solution::max_sum_div_three({nums})" + python3: "Solution().maxSumDivThree({nums})" + python2: "Solution().maxSumDivThree({nums})" + ruby: "max_sum_div_three({nums})" + java: "new Solution().maxSumDivThree({nums})" + csharp: "new Solution().MaxSumDivThree({nums})" + kotlin: "Solution().maxSumDivThree({nums})" + go: "maxSumDivThree({nums})" + dart: "Solution().maxSumDivThree({nums})" + swift: "Solution().maxSumDivThree({nums})" + typescript: "maxSumDivThree({nums})" +judge: + type: "exact" +limits: + time_ms: 500 + memory_mb: 300 +oracle: + python3: + call: "Checker().maxSumDivThree(nums, {result})" + checker: | + class Checker: + def maxSumDivThree(self, nums, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + total = sum(nums) + remainder_one = sorted(x for x in nums if x % 3 == 1) + remainder_two = sorted(x for x in nums if x % 3 == 2) + remove = 0 + if total % 3 == 1: + choices = [] + if remainder_one: + choices.append(remainder_one[0]) + if len(remainder_two) >= 2: + choices.append(remainder_two[0] + remainder_two[1]) + remove = min(choices) if choices else total + elif total % 3 == 2: + choices = [] + if remainder_two: + choices.append(remainder_two[0]) + if len(remainder_one) >= 2: + choices.append(remainder_one[0] + remainder_one[1]) + remove = min(choices) if choices else total + return result == total - remove +seed: 1262 +tests: + - name: "example_one" + in: + nums: [3, 6, 5, 1, 8] + out: 18 + - name: "example_two" + in: + nums: [4] + out: 0 + - name: "example_three" + in: + nums: [1, 2, 3, 4, 4] + out: 12 + - name: "single_divisible" + in: + nums: [3] + out: 3 + - name: "single_remainder_one" + in: + nums: [1] + out: 0 + - name: "single_remainder_two" + in: + nums: [2] + out: 0 + - name: "all_remainder_one_divisible_total" + in: + nums: [1, 4, 7] + out: 12 + - name: "all_remainder_two_divisible_total" + in: + nums: [2, 5, 8] + out: 15 + - name: "two_complementary_remainders" + in: + nums: [1, 2] + out: 3 + - name: "remove_one_remainder_one" + in: + nums: [3, 6, 4] + out: 9 + - name: "remove_two_remainder_two" + in: + nums: [3, 2, 5] + out: 3 + - name: "remove_one_remainder_two" + in: + nums: [6, 8] + out: 6 + - name: "remove_two_remainder_one" + in: + nums: [6, 1, 4] + out: 6 + - name: "choose_cheaper_single_removal" + in: + nums: [10000, 1, 2] + out: 10002 + - name: "all_elements_already_optimal" + in: + nums: [1, 2, 3, 4, 5, 6] + out: 21 + - name: "maximum_value_triplet" + in: + nums: [10000, 10000, 10000] + out: 30000 + - name: "maximum_value_with_divisible_anchor" + in: + nums: [9999, 10000] + out: 9999 + - name: "maximum_value_mixed_remainders" + in: + nums: [9998, 9998, 10000] + out: 19998 + - name: "near_maximum_remove_smallest_remainder_one" + in: + nums: [9997, 9998, 9999, 10000] + out: 29997 + - name: "prefer_two_small_remainder_ones" + in: + nums: [8, 1, 1, 1] + out: 9 + - name: "only_single_remainder_two_available" + in: + nums: [2, 2, 1] + out: 3 + - name: "prefer_single_remainder_one" + in: + nums: [2, 2, 2, 1] + out: 6 + - name: "balanced_duplicate_pairs" + in: + nums: [4, 4, 2, 2] + out: 12 + - name: "five_remainder_ones" + in: + nums: [7, 10, 13, 16, 19] + out: 48 + - name: "four_remainder_twos" + in: + nums: [5, 8, 11, 14] + out: 33 + - name: "all_multiples_of_three" + in: + nums: [3, 6, 9, 12, 15] + out: 45 + - name: "equal_remainder_groups" + in: + nums: [1, 1, 1, 2, 2, 2] + out: 9 + - name: "near_maximum_consecutive_values" + in: + nums: [9991, 9992, 9993, 9994, 9995, 9996] + out: 59961 + - name: "extreme_mixed_values" + in: + nums: [1, 10000, 9999, 9998, 2] + out: 30000 + - name: "ascending_first_ten" + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + out: 54 + - name: "descending_first_ten" + in: + nums: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + out: 54 + - name: "mixed_choice_with_all_remainders" + in: + nums: [4, 1, 7, 2, 8] + out: 21 + - name: "large_divisible_sequence" + in: + nums: [100, 200, 300, 400, 500, 600] + out: 2100 + - name: "large_values_with_unit_removal" + in: + nums: [9999, 1, 1, 1, 9998, 2] + out: 20001 + - name: "stress_uniform_full_length" + seed: 126201 + in: + nums: + gen: "array" + len: 40000 + distinct: false + sorted: false + elemType: "int" + of: + gen: "int" + min: 1 + max: 10000 + - name: "stress_small_values_full_length" + seed: 126202 + in: + nums: + gen: "array" + len: 40000 + distinct: false + sorted: false + elemType: "int" + of: + gen: "int" + min: 1 + max: 3 + - name: "stress_high_values_full_length" + seed: 126203 + in: + nums: + gen: "array" + len: 40000 + distinct: false + sorted: false + elemType: "int" + of: + gen: "int" + min: 9991 + max: 10000 + - name: "stress_midrange_full_length" + seed: 126204 + in: + nums: + gen: "array" + len: 40000 + distinct: false + sorted: false + elemType: "int" + of: + gen: "int" + min: 3333 + max: 6666 + - name: "stress_odd_span_full_length" + seed: 126205 + in: + nums: + gen: "array" + len: 40000 + distinct: false + sorted: false + elemType: "int" + of: + gen: "int" + min: 17 + max: 9973 + - name: "stress_broad_full_length" + seed: 126206 + in: + nums: + gen: "array" + len: 40000 + distinct: false + sorted: false + elemType: "int" + of: + gen: "int" + min: 2 + max: 9999 diff --git a/tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.cpp b/tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.cpp new file mode 100644 index 00000000..423afef2 --- /dev/null +++ b/tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int maxSumDivThree(vector& nums) { + int n = nums.size(); + int minus = -(1 << 30); + vector> dp = {{0, 0, 0}, {0, minus, minus}}; + for (int i = 0; i < n; i++) { + int x = nums[i]; + int x3 = x % 3; + for (int mod = 0; mod < 3; mod++) { + int modPrev = (3 + mod - x3) % 3; + int take = x + dp[(i + 1) & 1][modPrev]; + int skip = dp[(i + 1) & 1][mod]; + dp[i & 1][mod] = max(take, skip); + } + } + return max(0, dp[(n - 1) & 1][0]); + } +}; diff --git a/tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.cs b/tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.cs new file mode 100644 index 00000000..b9b93a1f --- /dev/null +++ b/tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.cs @@ -0,0 +1,18 @@ +public class Solution { + public int MaxSumDivThree(int[] nums) { + int n = nums.Length; + int minus = -(1 << 30); + int[][] dp = new int[][] { new int[] {0, 0, 0}, new int[] {0, minus, minus} }; + for (int i = 0; i < n; i++) { + int x = nums[i]; + int x3 = x % 3; + for (int mod = 0; mod < 3; mod++) { + int modPrev = (3 + mod - x3) % 3; + int take = x + dp[(i + 1) & 1][modPrev]; + int skip = dp[(i + 1) & 1][mod]; + dp[i & 1][mod] = Math.Max(take, skip); + } + } + return Math.Max(0, dp[(n - 1) & 1][0]); + } +} diff --git a/tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.dart b/tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.dart new file mode 100644 index 00000000..ec5b2991 --- /dev/null +++ b/tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.dart @@ -0,0 +1,19 @@ +class Solution { + int maxSumDivThree(List nums) { + int n = nums.length; + int minus = -(1 << 30); + List> dp = [List.filled(3, 0), [0, minus, minus]]; + for (int i = 0; i < n; i++) { + int x = nums[i]; + int x3 = x % 3; + for (int mod = 0; mod < 3; mod++) { + int modPrev = (3 + mod - x3) % 3; + int take = x + dp[(i + 1) & 1][modPrev]; + int skip = dp[(i + 1) & 1][mod]; + dp[i & 1][mod] = take > skip ? take : skip; + } + } + int ans = dp[(n - 1) & 1][0]; + return ans > 0 ? ans : 0; + } +} diff --git a/tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.go b/tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.go new file mode 100644 index 00000000..1b8f4b4d --- /dev/null +++ b/tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.go @@ -0,0 +1,23 @@ +func maxSumDivThree(nums []int) int { + n := len(nums) + minus := -(1 << 30) + dp := [][]int{{0, 0, 0}, {0, minus, minus}} + for i, x := range nums { + x3 := x % 3 + for mod := 0; mod < 3; mod++ { + modPrev := (3 + mod - x3) % 3 + take := x + dp[(i+1)&1][modPrev] + skip := dp[(i+1)&1][mod] + if take > skip { + dp[i&1][mod] = take + } else { + dp[i&1][mod] = skip + } + } + } + ans := dp[(n-1)&1][0] + if ans < 0 { + return 0 + } + return ans +} diff --git a/tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.java b/tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.java new file mode 100644 index 00000000..cf505f64 --- /dev/null +++ b/tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.java @@ -0,0 +1,18 @@ +class Solution { + public int maxSumDivThree(int[] nums) { + int n = nums.length; + int minus = -(1 << 30); + int[][] dp = new int[][] {{0, 0, 0}, {0, minus, minus}}; + for (int i = 0; i < n; i++) { + int x = nums[i]; + int x3 = x % 3; + for (int mod = 0; mod < 3; mod++) { + int modPrev = (3 + mod - x3) % 3; + int take = x + dp[(i + 1) & 1][modPrev]; + int skip = dp[(i + 1) & 1][mod]; + dp[i & 1][mod] = Math.max(take, skip); + } + } + return Math.max(0, dp[(n - 1) & 1][0]); + } +} diff --git a/tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.kt b/tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.kt new file mode 100644 index 00000000..4c3a86d8 --- /dev/null +++ b/tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.kt @@ -0,0 +1,18 @@ +class Solution { + fun maxSumDivThree(nums: IntArray): Int { + val n = nums.size + val minus = -(1 shl 30) + val dp = arrayOf(intArrayOf(0, 0, 0), intArrayOf(0, minus, minus)) + for (i in nums.indices) { + val x = nums[i] + val x3 = x % 3 + for (mod in 0..2) { + val modPrev = (3 + mod - x3) % 3 + val take = x + dp[(i + 1) and 1][modPrev] + val skip = dp[(i + 1) and 1][mod] + dp[i and 1][mod] = maxOf(take, skip) + } + } + return maxOf(0, dp[(n - 1) and 1][0]) + } +} diff --git a/tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.py b/tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.py new file mode 100644 index 00000000..922b52e9 --- /dev/null +++ b/tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.py @@ -0,0 +1,12 @@ +class Solution: + def maxSumDivThree(self, nums: List[int]) -> int: + n, minus = len(nums), -(1 << 30) + dp = [[0, 0, 0], [0, minus, minus]] + for i, x in enumerate(nums): + x3 = x % 3 + for mod in range(3): + modPrev = (3 + mod - x3) % 3 + take = x + dp[(i + 1) & 1][modPrev] + skip = dp[(i + 1) & 1][mod] + dp[i & 1][mod] = max(take, skip) + return max(0, dp[(n - 1) & 1][0]) diff --git a/tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.py2 b/tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.py2 new file mode 100644 index 00000000..319f55f5 --- /dev/null +++ b/tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def maxSumDivThree(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + n, minus = len(nums), -(1 << 30) + dp = [[0, 0, 0], [0, minus, minus]] + for i, x in enumerate(nums): + x3 = x % 3 + for mod in range(3): + modPrev = (3 + mod - x3) % 3 + take = x + dp[(i + 1) & 1][modPrev] + skip = dp[(i + 1) & 1][mod] + dp[i & 1][mod] = max(take, skip) + return max(0, dp[(n - 1) & 1][0]) diff --git a/tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.rb b/tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.rb new file mode 100644 index 00000000..72c50328 --- /dev/null +++ b/tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.rb @@ -0,0 +1,17 @@ +# @param {Integer[]} nums +# @return {Integer} +def max_sum_div_three(nums) + n = nums.length + minus = -(1 << 30) + dp = [[0, 0, 0], [0, minus, minus]] + nums.each_with_index do |x, i| + x3 = x % 3 + (0...3).each do |mod| + mod_prev = (3 + mod - x3) % 3 + take = x + dp[(i + 1) & 1][mod_prev] + skip = dp[(i + 1) & 1][mod] + dp[i & 1][mod] = [take, skip].max + end + end + [0, dp[(n - 1) & 1][0]].max +end diff --git a/tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.rs b/tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.rs new file mode 100644 index 00000000..47c12258 --- /dev/null +++ b/tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.rs @@ -0,0 +1,17 @@ +impl Solution { + pub fn max_sum_div_three(nums: Vec) -> i32 { + let n = nums.len(); + let minus = -(1i32 << 30); + let mut dp = vec![vec![0, 0, 0], vec![0, minus, minus]]; + for (i, &x) in nums.iter().enumerate() { + let x3 = x % 3; + for mod_val in 0..3 { + let mod_prev = (3 + mod_val - x3 as usize) % 3; + let take = x + dp[(i + 1) & 1][mod_prev]; + let skip = dp[(i + 1) & 1][mod_val]; + dp[i & 1][mod_val] = take.max(skip); + } + } + dp[(n - 1) & 1][0].max(0) + } +} diff --git a/tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.swift b/tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.swift new file mode 100644 index 00000000..daf71f27 --- /dev/null +++ b/tests/1001-1500/1262. greatest-sum-divisible-by-three/sol.swift @@ -0,0 +1,18 @@ +class Solution { + func maxSumDivThree(_ nums: [Int]) -> Int { + let n = nums.count + let minus = -(1 << 30) + var dp = [[0, 0, 0], [0, minus, minus]] + for i in 0..>& grid) { + int rows = grid.size(), cols = grid[0].size(); + pair player, box, target; + for (int i = 0; i < rows; ++i) { + for (int j = 0; j < cols; ++j) { + if (grid[i][j] == 'S') player = {i, j}; + else if (grid[i][j] == 'B') box = {i, j}; + else if (grid[i][j] == 'T') target = {i, j}; + } + } + + vector> dirs = {{1,0}, {-1,0}, {0,1}, {0,-1}}; + queue, pair, int>> q; + q.push({box, player, 0}); + set> seen; + seen.insert({box.first, box.second, player.first, player.second}); + + while (!q.empty()) { + auto [b, p, pushes] = q.front(); + q.pop(); + if (b == target) return pushes; + + set> reachable; + queue> walk; + walk.push(p); + reachable.insert(p); + + while (!walk.empty()) { + auto [x, y] = walk.front(); + walk.pop(); + for (auto [dx, dy] : dirs) { + int nx = x + dx, ny = y + dy; + if (nx >= 0 && nx < rows && ny >= 0 && ny < cols && + !(nx == b.first && ny == b.second) && grid[nx][ny] != '#' && + !reachable.count({nx, ny})) { + reachable.insert({nx, ny}); + walk.push({nx, ny}); + } + } + } + + for (auto [dx, dy] : dirs) { + pair nextBox = {b.first + dx, b.second + dy}; + pair behind = {b.first - dx, b.second - dy}; + if (nextBox.first >= 0 && nextBox.first < rows && nextBox.second >= 0 && nextBox.second < cols && + grid[nextBox.first][nextBox.second] != '#' && + reachable.count(behind) && + !seen.count({nextBox.first, nextBox.second, b.first, b.second})) { + seen.insert({nextBox.first, nextBox.second, b.first, b.second}); + q.push({nextBox, b, pushes + 1}); + } + } + } + return -1; + } +}; diff --git a/tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.cs b/tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.cs new file mode 100644 index 00000000..2888cb30 --- /dev/null +++ b/tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.cs @@ -0,0 +1,59 @@ +public class Solution { + public int MinPushBox(char[][] grid) { + int rows = grid.Length, cols = grid[0].Length; + (int, int) player = (0, 0), box = (0, 0), target = (0, 0); + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + if (grid[i][j] == 'S') player = (i, j); + else if (grid[i][j] == 'B') box = (i, j); + else if (grid[i][j] == 'T') target = (i, j); + } + } + + (int, int)[] dirs = {(1, 0), (-1, 0), (0, 1), (0, -1)}; + var q = new Queue<((int,int) box, (int,int) player, int pushes)>(); + q.Enqueue((box, player, 0)); + var seen = new HashSet<(int,int,int,int)>(); + seen.Add((box.Item1, box.Item2, player.Item1, player.Item2)); + + while (q.Count > 0) { + var cur = q.Dequeue(); + var b = cur.box; + var p = cur.player; + int pushes = cur.pushes; + + if (b == target) return pushes; + + var reachable = new HashSet<(int,int)>(); + var walk = new Queue<(int,int)>(); + walk.Enqueue(p); + reachable.Add(p); + + while (walk.Count > 0) { + var w = walk.Dequeue(); + foreach (var (dx, dy) in dirs) { + int nx = w.Item1 + dx, ny = w.Item2 + dy; + if (nx >= 0 && nx < rows && ny >= 0 && ny < cols && + !(nx == b.Item1 && ny == b.Item2) && grid[nx][ny] != '#' && + !reachable.Contains((nx, ny))) { + reachable.Add((nx, ny)); + walk.Enqueue((nx, ny)); + } + } + } + + foreach (var (dx, dy) in dirs) { + var nextBox = (b.Item1 + dx, b.Item2 + dy); + var behind = (b.Item1 - dx, b.Item2 - dy); + if (nextBox.Item1 >= 0 && nextBox.Item1 < rows && nextBox.Item2 >= 0 && nextBox.Item2 < cols && + grid[nextBox.Item1][nextBox.Item2] != '#' && + reachable.Contains(behind) && + !seen.Contains((nextBox.Item1, nextBox.Item2, b.Item1, b.Item2))) { + seen.Add((nextBox.Item1, nextBox.Item2, b.Item1, b.Item2)); + q.Enqueue((nextBox, b, pushes + 1)); + } + } + } + return -1; + } +} diff --git a/tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.dart b/tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.dart new file mode 100644 index 00000000..f7efdc25 --- /dev/null +++ b/tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.dart @@ -0,0 +1,56 @@ +class Solution { + int minPushBox(List> grid) { + int rows = grid.length, cols = grid[0].length; + List player = [], box = [], target = []; + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + if (grid[i][j] == 'S') player = [i, j]; + else if (grid[i][j] == 'B') box = [i, j]; + else if (grid[i][j] == 'T') target = [i, j]; + } + } + + List> dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]]; + Queue> q = Queue(); + q.add([box[0], box[1], player[0], player[1], 0]); + Set seen = {}; + seen.add("${box[0]},${box[1]},${player[0]},${player[1]}"); + + while (q.isNotEmpty) { + var cur = q.removeFirst(); + int bx = cur[0], by = cur[1], px = cur[2], py = cur[3], pushes = cur[4]; + if (bx == target[0] && by == target[1]) return pushes; + + Set reachable = {}; + Queue> walk = Queue(); + walk.add([px, py]); + reachable.add("$px,$py"); + + while (walk.isNotEmpty) { + var w = walk.removeFirst(); + for (var d in dirs) { + int nx = w[0] + d[0], ny = w[1] + d[1]; + if (nx >= 0 && nx < rows && ny >= 0 && ny < cols && + !(nx == bx && ny == by) && grid[nx][ny] != '#' && + !reachable.contains("$nx,$ny")) { + reachable.add("$nx,$ny"); + walk.add([nx, ny]); + } + } + } + + for (var d in dirs) { + int nbx = bx + d[0], nby = by + d[1]; + int behindX = bx - d[0], behindY = by - d[1]; + if (nbx >= 0 && nbx < rows && nby >= 0 && nby < cols && + grid[nbx][nby] != '#' && + reachable.contains("$behindX,$behindY") && + !seen.contains("$nbx,$nby,$bx,$by")) { + seen.add("$nbx,$nby,$bx,$by"); + q.add([nbx, nby, bx, by, pushes + 1]); + } + } + } + return -1; + } +} diff --git a/tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.go b/tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.go new file mode 100644 index 00000000..ecab8609 --- /dev/null +++ b/tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.go @@ -0,0 +1,64 @@ +func minPushBox(grid [][]byte) int { + rows, cols := len(grid), len(grid[0]) + type pair struct{ x, y int } + var player, box, target pair + + for i:=0; i 0 { + cur := q[0] + q = q[1:] + if cur.box == target { + return cur.pushes + } + + reachable := make(map[pair]bool) + reachable[cur.player] = true + walk := []pair{cur.player} + for len(walk) > 0 { + w := walk[0] + walk = walk[1:] + for _, d := range dirs { + nx, ny := w.x+d.x, w.y+d.y + np := pair{nx, ny} + if nx >= 0 && nx < rows && ny >= 0 && ny < cols && + np != cur.box && grid[nx][ny] != '#' && !reachable[np] { + reachable[np] = true + walk = append(walk, np) + } + } + } + + for _, d := range dirs { + nextBox := pair{cur.box.x+d.x, cur.box.y+d.y} + behind := pair{cur.box.x-d.x, cur.box.y-d.y} + if nextBox.x >= 0 && nextBox.x < rows && nextBox.y >= 0 && nextBox.y < cols && + grid[nextBox.x][nextBox.y] != '#' && reachable[behind] { + key := [4]int{nextBox.x, nextBox.y, cur.box.x, cur.box.y} + if !seen[key] { + seen[key] = true + q = append(q, state{nextBox, cur.box, cur.pushes+1}) + } + } + } + } + return -1 +} diff --git a/tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.java b/tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.java new file mode 100644 index 00000000..d5671417 --- /dev/null +++ b/tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.java @@ -0,0 +1,56 @@ +class Solution { + public int minPushBox(char[][] grid) { + int rows = grid.length, cols = grid[0].length; + int[] player = null, box = null, target = null; + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + if (grid[i][j] == 'S') player = new int[]{i, j}; + else if (grid[i][j] == 'B') box = new int[]{i, j}; + else if (grid[i][j] == 'T') target = new int[]{i, j}; + } + } + + int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + Queue q = new LinkedList<>(); + q.offer(new int[]{box[0], box[1], player[0], player[1], 0}); + Set seen = new HashSet<>(); + seen.add(box[0] + "," + box[1] + "," + player[0] + "," + player[1]); + + while (!q.isEmpty()) { + int[] cur = q.poll(); + int bx = cur[0], by = cur[1], px = cur[2], py = cur[3], pushes = cur[4]; + if (bx == target[0] && by == target[1]) return pushes; + + Set reachable = new HashSet<>(); + Queue walk = new LinkedList<>(); + walk.offer(new int[]{px, py}); + reachable.add(px + "," + py); + + while (!walk.isEmpty()) { + int[] w = walk.poll(); + for (int[] d : dirs) { + int nx = w[0] + d[0], ny = w[1] + d[1]; + if (nx >= 0 && nx < rows && ny >= 0 && ny < cols && + !(nx == bx && ny == by) && grid[nx][ny] != '#' && + !reachable.contains(nx + "," + ny)) { + reachable.add(nx + "," + ny); + walk.offer(new int[]{nx, ny}); + } + } + } + + for (int[] d : dirs) { + int nbx = bx + d[0], nby = by + d[1]; + int behindX = bx - d[0], behindY = by - d[1]; + if (nbx >= 0 && nbx < rows && nby >= 0 && nby < cols && + grid[nbx][nby] != '#' && + reachable.contains(behindX + "," + behindY) && + !seen.contains(nbx + "," + nby + "," + bx + "," + by)) { + seen.add(nbx + "," + nby + "," + bx + "," + by); + q.offer(new int[]{nbx, nby, bx, by, pushes + 1}); + } + } + } + return -1; + } +} diff --git a/tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.kt b/tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.kt new file mode 100644 index 00000000..91699b25 --- /dev/null +++ b/tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.kt @@ -0,0 +1,60 @@ +class Solution { + fun minPushBox(grid: Array): Int { + val rows = grid.size + val cols = grid[0].size + var player: Pair? = null + var box: Pair? = null + var target: Pair? = null + + for (i in 0 until rows) { + for (j in 0 until cols) { + when (grid[i][j]) { + 'S' -> player = Pair(i, j) + 'B' -> box = Pair(i, j) + 'T' -> target = Pair(i, j) + } + } + } + + val dirs = listOf(Pair(1, 0), Pair(-1, 0), Pair(0, 1), Pair(0, -1)) + val q: java.util.Queue, Pair, Int>> = java.util.LinkedList() + q.offer(Triple(box!!, player!!, 0)) + val seen = mutableSetOf, Pair>>() + seen.add(Pair(box!!, player!!)) + + while (q.isNotEmpty()) { + val (b, p, pushes) = q.poll() + if (b == target) return pushes + + val reachable = mutableSetOf(p) + val walk: java.util.Queue> = java.util.LinkedList() + walk.offer(p) + while (walk.isNotEmpty()) { + val (x, y) = walk.poll() + for ((dx, dy) in dirs) { + val nx = x + dx + val ny = y + dy + if (nx in 0 until rows && ny in 0 until cols && + Pair(nx, ny) != b && grid[nx][ny] != '#' && + Pair(nx, ny) !in reachable) { + reachable.add(Pair(nx, ny)) + walk.offer(Pair(nx, ny)) + } + } + } + + for ((dx, dy) in dirs) { + val nextBox = Pair(b.first + dx, b.second + dy) + val behind = Pair(b.first - dx, b.second - dy) + if (nextBox.first in 0 until rows && nextBox.second in 0 until cols && + grid[nextBox.first][nextBox.second] != '#' && + behind in reachable && + Pair(nextBox, b) !in seen) { + seen.add(Pair(nextBox, b)) + q.offer(Triple(nextBox, b, pushes + 1)) + } + } + } + return -1 + } +} diff --git a/tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.py b/tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.py new file mode 100644 index 00000000..06909e8a --- /dev/null +++ b/tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.py @@ -0,0 +1,53 @@ +from collections import deque + + +class Solution: + def minPushBox(self, grid): + for i, row in enumerate(grid): + for j, cell in enumerate(row): + if cell == "S": + player = (i, j) + elif cell == "B": + box = (i, j) + elif cell == "T": + target = (i, j) + + q = deque([(box, player, 0)]) + seen = {(box, player)} + directions = ((1, 0), (-1, 0), (0, 1), (0, -1)) + rows, cols = len(grid), len(grid[0]) + + while q: + box, player, pushes = q.popleft() + if box == target: + return pushes + + reachable = {player} + walk = deque([player]) + while walk: + x, y = walk.popleft() + for dx, dy in directions: + nx, ny = x + dx, y + dy + if ( + 0 <= nx < rows + and 0 <= ny < cols + and (nx, ny) != box + and grid[nx][ny] != "#" + and (nx, ny) not in reachable + ): + reachable.add((nx, ny)) + walk.append((nx, ny)) + + for dx, dy in directions: + next_box = (box[0] + dx, box[1] + dy) + behind = (box[0] - dx, box[1] - dy) + if ( + 0 <= next_box[0] < rows + and 0 <= next_box[1] < cols + and grid[next_box[0]][next_box[1]] != "#" + and behind in reachable + and (next_box, box) not in seen + ): + seen.add((next_box, box)) + q.append((next_box, box, pushes + 1)) + return -1 diff --git a/tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.py2 b/tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.py2 new file mode 100644 index 00000000..1f8deaf1 --- /dev/null +++ b/tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.py2 @@ -0,0 +1,49 @@ +class Solution(object): + def minPushBox(self, grid): + """ + :type grid: List[List[str]] + :rtype: int + """ + from collections import deque + + rows, cols = len(grid), len(grid[0]) + player = box = target = None + for i in range(rows): + for j in range(cols): + if grid[i][j] == 'S': + player = (i, j) + elif grid[i][j] == 'B': + box = (i, j) + elif grid[i][j] == 'T': + target = (i, j) + + q = deque([(box, player, 0)]) + seen = {(box, player)} + directions = ((1, 0), (-1, 0), (0, 1), (0, -1)) + + while q: + box, player, pushes = q.popleft() + if box == target: + return pushes + + reachable = {player} + walk = deque([player]) + while walk: + x, y = walk.popleft() + for dx, dy in directions: + nx, ny = x + dx, y + dy + if (0 <= nx < rows and 0 <= ny < cols and + (nx, ny) != box and grid[nx][ny] != '#' and + (nx, ny) not in reachable): + reachable.add((nx, ny)) + walk.append((nx, ny)) + + for dx, dy in directions: + next_box = (box[0] + dx, box[1] + dy) + behind = (box[0] - dx, box[1] - dy) + if (0 <= next_box[0] < rows and 0 <= next_box[1] < cols and + grid[next_box[0]][next_box[1]] != '#' and + behind in reachable and (next_box, box) not in seen): + seen.add((next_box, box)) + q.append((next_box, box, pushes + 1)) + return -1 diff --git a/tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.rb b/tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.rb new file mode 100644 index 00000000..dabb8ffd --- /dev/null +++ b/tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.rb @@ -0,0 +1,59 @@ +# @param {Character[][]} grid +# @return {Integer} +def min_push_box(grid) + rows = grid.length + cols = grid[0].length + player = nil + box = nil + target = nil + + (0...rows).each do |i| + (0...cols).each do |j| + case grid[i][j] + when 'S' then player = [i, j] + when 'B' then box = [i, j] + when 'T' then target = [i, j] + end + end + end + + q = [[box, player, 0]] + seen = Set.new + seen.add([box, player]) + directions = [[1, 0], [-1, 0], [0, 1], [0, -1]] + + until q.empty? + box, player, pushes = q.shift + return pushes if box == target + + reachable = Set.new + reachable.add(player) + walk = [player] + until walk.empty? + x, y = walk.shift + directions.each do |dx, dy| + nx, ny = x + dx, y + dy + if nx >= 0 && nx < rows && ny >= 0 && ny < cols && + [nx, ny] != box && grid[nx][ny] != '#' && + !reachable.include?([nx, ny]) + reachable.add([nx, ny]) + walk.push([nx, ny]) + end + end + end + + directions.each do |dx, dy| + next_box = [box[0] + dx, box[1] + dy] + behind = [box[0] - dx, box[1] - dy] + if next_box[0] >= 0 && next_box[0] < rows && next_box[1] >= 0 && next_box[1] < cols && + grid[next_box[0]][next_box[1]] != '#' && + reachable.include?(behind) && + !seen.include?([next_box, box]) + seen.add([next_box, box]) + q.push([next_box, box, pushes + 1]) + end + end + end + + -1 +end diff --git a/tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.rs b/tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.rs new file mode 100644 index 00000000..53bde36c --- /dev/null +++ b/tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.rs @@ -0,0 +1,71 @@ +impl Solution { + pub fn min_push_box(grid: Vec>) -> i32 { + let rows = grid.len(); + let cols = grid[0].len(); + let mut player = (0, 0); + let mut box_pos = (0, 0); + let mut target = (0, 0); + + for i in 0..rows { + for j in 0..cols { + match grid[i][j] { + 'S' => player = (i, j), + 'B' => box_pos = (i, j), + 'T' => target = (i, j), + _ => {} + } + } + } + + let dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]; + use std::collections::{VecDeque, HashSet}; + + let mut q = VecDeque::new(); + q.push_back((box_pos, player, 0)); + let mut seen = HashSet::new(); + seen.insert((box_pos, player)); + + while let Some((b, p, pushes)) = q.pop_front() { + if b == target { + return pushes; + } + + let mut reachable = HashSet::new(); + reachable.insert(p); + let mut walk = VecDeque::new(); + walk.push_back(p); + + while let Some((x, y)) = walk.pop_front() { + for (dx, dy) in &dirs { + let nx = x as i32 + dx; + let ny = y as i32 + dy; + if nx >= 0 && nx < rows as i32 && ny >= 0 && ny < cols as i32 { + let np = (nx as usize, ny as usize); + if np != b && grid[np.0][np.1] != '#' && !reachable.contains(&np) { + reachable.insert(np); + walk.push_back(np); + } + } + } + } + + for (dx, dy) in &dirs { + let nbx = b.0 as i32 + dx; + let nby = b.1 as i32 + dy; + let behind_x = b.0 as i32 - dx; + let behind_y = b.1 as i32 - dy; + + if nbx >= 0 && nbx < rows as i32 && nby >= 0 && nby < cols as i32 { + let nb = (nbx as usize, nby as usize); + let behind = (behind_x as usize, behind_y as usize); + + if grid[nb.0][nb.1] != '#' && reachable.contains(&behind) && !seen.contains(&(nb, b)) { + seen.insert((nb, b)); + q.push_back((nb, b, pushes + 1)); + } + } + } + } + -1 + } +} diff --git a/tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.swift b/tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.swift new file mode 100644 index 00000000..9991eb37 --- /dev/null +++ b/tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.swift @@ -0,0 +1,53 @@ +class Solution { + func minPushBox(_ grid: [[Character]]) -> Int { + let rows = grid.count, cols = grid[0].count + var player = (0, 0), box = (0, 0), target = (0, 0) + for i in 0.. = [[box.0, box.1, player.0, player.1]] + + while !q.isEmpty { + let (b, p, pushes) = q.removeFirst() + if b == target { return pushes } + + var reachable: Set<[Int]> = [[p.0, p.1]] + var walk = [p] + while !walk.isEmpty { + let (x, y) = walk.removeFirst() + for (dx, dy) in dirs { + let nx = x + dx, ny = y + dy + if nx >= 0 && nx < rows && ny >= 0 && ny < cols && + !(nx == b.0 && ny == b.1) && grid[nx][ny] != "#" && + !reachable.contains([nx, ny]) { + reachable.insert([nx, ny]) + walk.append((nx, ny)) + } + } + } + + for (dx, dy) in dirs { + let nextBox = (b.0 + dx, b.1 + dy) + let behind = (b.0 - dx, b.1 - dy) + if nextBox.0 >= 0 && nextBox.0 < rows && nextBox.1 >= 0 && nextBox.1 < cols && + grid[nextBox.0][nextBox.1] != "#" && + reachable.contains([behind.0, behind.1]) && + !seen.contains([nextBox.0, nextBox.1, b.0, b.1]) { + seen.insert([nextBox.0, nextBox.1, b.0, b.1]) + q.append((nextBox, b, pushes + 1)) + } + } + } + return -1 + } +} diff --git a/tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.ts b/tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.ts new file mode 100644 index 00000000..8fbe7899 --- /dev/null +++ b/tests/1001-1500/1263. minimum-moves-to-move-a-box-to-their-target-location/sol.ts @@ -0,0 +1,75 @@ +function minPushBox(grid: string[][]): number { + const rows = grid.length, + cols = grid[0].length; + let player: [number, number] = [0, 0], + box: [number, number] = [0, 0], + target: [number, number] = [0, 0]; + for (let i = 0; i < rows; i++) { + for (let j = 0; j < cols; j++) { + if (grid[i][j] === "S") player = [i, j]; + else if (grid[i][j] === "B") box = [i, j]; + else if (grid[i][j] === "T") target = [i, j]; + } + } + + const dirs: [number, number][] = [ + [1, 0], + [-1, 0], + [0, 1], + [0, -1], + ]; + const q: [number, number, number, number, number][] = [ + [box[0], box[1], player[0], player[1], 0], + ]; + const seen = new Set(); + seen.add(`${box[0]},${box[1]},${player[0]},${player[1]}`); + + while (q.length > 0) { + const [bx, by, px, py, pushes] = q.shift()!; + if (bx === target[0] && by === target[1]) return pushes; + + const reachable = new Set(); + const walk: [number, number][] = [[px, py]]; + reachable.add(`${px},${py}`); + + while (walk.length > 0) { + const [x, y] = walk.shift()!; + for (const [dx, dy] of dirs) { + const nx = x + dx, + ny = y + dy; + if ( + nx >= 0 && + nx < rows && + ny >= 0 && + ny < cols && + !(nx === bx && ny === by) && + grid[nx][ny] !== "#" && + !reachable.has(`${nx},${ny}`) + ) { + reachable.add(`${nx},${ny}`); + walk.push([nx, ny]); + } + } + } + + for (const [dx, dy] of dirs) { + const nbx = bx + dx, + nby = by + dy; + const behindX = bx - dx, + behindY = by - dy; + if ( + nbx >= 0 && + nbx < rows && + nby >= 0 && + nby < cols && + grid[nbx][nby] !== "#" && + reachable.has(`${behindX},${behindY}`) && + !seen.has(`${nbx},${nby},${bx},${by}`) + ) { + seen.add(`${nbx},${nby},${bx},${by}`); + q.push([nbx, nby, bx, by, pushes + 1]); + } + } + } + return -1; +} diff --git a/tests/1001-1500/1266. minimum-time-visiting-all-points/manifest.yaml b/tests/1001-1500/1266. minimum-time-visiting-all-points/manifest.yaml new file mode 100644 index 00000000..7e595f67 --- /dev/null +++ b/tests/1001-1500/1266. minimum-time-visiting-all-points/manifest.yaml @@ -0,0 +1,480 @@ +entry: + id: 1266 + title: minimum-time-visiting-all-points + params: + points: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().minTimeToVisitAllPoints({points})" + rust: "Solution::min_time_to_visit_all_points({points})" + python3: "Solution().minTimeToVisitAllPoints({points})" + python2: "Solution().minTimeToVisitAllPoints({points})" + ruby: "min_time_to_visit_all_points({points})" + java: "new Solution().minTimeToVisitAllPoints({points})" + csharp: "new Solution().MinTimeToVisitAllPoints({points})" + kotlin: "Solution().minTimeToVisitAllPoints({points})" + go: "minTimeToVisitAllPoints({points})" + dart: "Solution().minTimeToVisitAllPoints({points})" + swift: "Solution().minTimeToVisitAllPoints({points})" + typescript: "minTimeToVisitAllPoints({points})" +judge: + type: "exact" +limits: + time_ms: 1000 + memory_mb: 256 +oracle: + python3: + call: "Checker().minTimeToVisitAllPoints(points, {result})" + checker: | + class Checker: + def minTimeToVisitAllPoints(self, points, result): + if type(result) is not int or not 1 <= len(points) <= 100: + return False + total = 0 + for previous, current in zip(points, points[1:]): + if len(previous) != 2 or len(current) != 2: + return False + total += max(abs(current[0] - previous[0]), abs(current[1] - previous[1])) + return result == total +seed: 1266 +tests: + - name: singleton_origin + in: + points: + elemType: "int" + value: + - [0, 0] + out: 0 + - name: example_one + in: + points: + elemType: "int" + value: + - [1, 1] + - [3, 4] + - [-1, 0] + out: 7 + - name: example_two + in: + points: + elemType: "int" + value: + - [3, 2] + - [-2, 2] + out: 5 + - name: max_horizontal_span + in: + points: + elemType: "int" + value: + - [-1000, 0] + - [1000, 0] + out: 2000 + - name: max_vertical_span + in: + points: + elemType: "int" + value: + - [0, -1000] + - [0, 1000] + out: 2000 + - name: max_opposite_diagonal + in: + points: + elemType: "int" + value: + - [-1000, -1000] + - [1000, 1000] + out: 2000 + - name: uneven_single_segment + in: + points: + elemType: "int" + value: + - [0, 0] + - [3, 4] + out: 4 + - name: repeated_then_move + in: + points: + elemType: "int" + value: + - [5, -7] + - [5, -7] + - [-1, 1] + out: 8 + - name: closed_square + in: + points: + elemType: "int" + value: + - [0, 0] + - [0, 3] + - [3, 3] + - [3, 0] + - [0, 0] + out: 12 + - name: alternating_diagonals + in: + points: + elemType: "int" + value: + - [0, 0] + - [5, 5] + - [10, 0] + - [15, 5] + - [20, 0] + out: 20 + - name: shallow_steps + in: + points: + elemType: "int" + value: + - [0, 0] + - [10, 3] + - [20, 6] + out: 20 + - name: steep_steps + in: + points: + elemType: "int" + value: + - [0, 0] + - [2, 10] + - [4, 20] + out: 20 + - name: cardinal_cross + in: + points: + elemType: "int" + value: + - [-3, 0] + - [0, 3] + - [3, 0] + - [0, -3] + out: 9 + - name: negative_quadrant_path + in: + points: + elemType: "int" + value: + - [-5, -5] + - [-2, -1] + - [3, 4] + out: 9 + - name: axis_then_diagonal + in: + points: + elemType: "int" + value: + - [1, 2] + - [4, 2] + - [4, 8] + out: 9 + - name: mixed_directions + in: + points: + elemType: "int" + value: + - [1, -2] + - [4, 1] + - [2, 8] + - [-5, 3] + out: 17 + - name: diagonal_line + in: + points: + elemType: "int" + value: + - [-4, -4] + - [-2, -2] + - [0, 0] + - [2, 2] + - [4, 4] + out: 8 + - name: return_to_origin + in: + points: + elemType: "int" + value: + - [0, 0] + - [3, 0] + - [3, 3] + - [0, 3] + - [0, 0] + out: 12 + - name: single_unit_staircase + in: + points: + elemType: "int" + value: + - [0, 0] + - [1, 0] + - [1, 1] + - [2, 1] + - [2, 2] + - [3, 2] + out: 5 + - name: sparse_axes + in: + points: + elemType: "int" + value: + - [-10, 4] + - [-10, -6] + - [8, -6] + out: 28 + - name: duplicate_middle + in: + points: + elemType: "int" + value: + - [7, 8] + - [7, 8] + - [0, 0] + - [5, 9] + out: 17 + - name: max_bounds_turn + in: + points: + elemType: "int" + value: + - [1000, 1000] + - [-1000, -1000] + - [1000, -1000] + out: 4000 + - name: rectangle_with_pause + in: + points: + elemType: "int" + value: + - [-2, -1] + - [-2, 7] + - [9, 7] + - [9, 7] + - [9, -1] + out: 27 + - name: descending_negative_diagonal + in: + points: + elemType: "int" + value: + - [0, 0] + - [-4, 4] + - [-8, 8] + out: 8 + - name: asymmetric_zigzag + in: + points: + elemType: "int" + value: + - [0, 0] + - [1, 5] + - [9, 5] + - [9, -1] + out: 19 + - name: later_point_crossing + in: + points: + elemType: "int" + value: + - [0, 0] + - [4, 0] + - [2, 0] + - [6, 0] + out: 10 + - name: all_quadrants + in: + points: + elemType: "int" + value: + - [-8, 7] + - [6, 3] + - [2, -9] + - [-5, -4] + out: 33 + - name: dominant_x_then_y + in: + points: + elemType: "int" + value: + - [-9, -1] + - [8, 2] + - [5, 15] + out: 30 + - name: dominant_y_then_x + in: + points: + elemType: "int" + value: + - [-1, -9] + - [2, 8] + - [15, 5] + out: 30 + - name: fine_grained_mixed_path + in: + points: + elemType: "int" + value: + - [-1, 2] + - [0, 0] + - [2, -1] + - [1, 3] + - [-2, 2] + - [-2, -2] + out: 15 + - name: long_ordered_route + in: + points: + elemType: "int" + value: + - [0, 0] + - [10, 0] + - [10, 10] + - [0, 10] + - [-5, 5] + - [-5, -5] + out: 45 + - name: alternating_axis_moves + in: + points: + elemType: "int" + value: + - [-6, 0] + - [-6, 4] + - [-2, 4] + - [-2, -3] + - [5, -3] + out: 22 + - name: max_coordinate_revisits + in: + points: + elemType: "int" + value: + - [-1000, 1000] + - [1000, -1000] + - [-1000, -1000] + - [-1000, 1000] + out: 6000 + - name: diagonal_and_axis_mix + in: + points: + elemType: "int" + value: + - [-7, -2] + - [-3, 2] + - [4, 2] + - [4, -4] + out: 17 + - name: max_random_points_one + seed: 126601 + in: + points: + gen: "array" + len: 100 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: -1000 + max: 1000 + distinct: false + sorted: false + distinct: false + sorted: false + elemType: "int" + - name: max_random_points_two + seed: 126602 + in: + points: + gen: "array" + len: 100 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: -1000 + max: 1000 + distinct: false + sorted: false + distinct: false + sorted: false + elemType: "int" + - name: max_random_points_three + seed: 126603 + in: + points: + gen: "array" + len: 100 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: -1000 + max: 1000 + distinct: false + sorted: false + distinct: false + sorted: false + elemType: "int" + - name: max_random_points_four + seed: 126604 + in: + points: + gen: "array" + len: 100 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: -1000 + max: 1000 + distinct: false + sorted: false + distinct: false + sorted: false + elemType: "int" + - name: max_random_points_five + seed: 126605 + in: + points: + gen: "array" + len: 100 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: -1000 + max: 1000 + distinct: false + sorted: false + distinct: false + sorted: false + elemType: "int" + - name: max_random_points_six + seed: 126606 + in: + points: + gen: "array" + len: 100 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: -1000 + max: 1000 + distinct: false + sorted: false + distinct: false + sorted: false + elemType: "int" diff --git a/tests/1001-1500/1266. minimum-time-visiting-all-points/sol.cpp b/tests/1001-1500/1266. minimum-time-visiting-all-points/sol.cpp new file mode 100644 index 00000000..6e84c1f8 --- /dev/null +++ b/tests/1001-1500/1266. minimum-time-visiting-all-points/sol.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + int minTimeToVisitAllPoints(vector>& points) { + int ans = 0; + for (int i = 1; i < points.size(); i++) { + ans += max( + abs(points[i][0] - points[i - 1][0]), + abs(points[i][1] - points[i - 1][1]) + ); + } + return ans; + } +}; diff --git a/tests/1001-1500/1266. minimum-time-visiting-all-points/sol.cs b/tests/1001-1500/1266. minimum-time-visiting-all-points/sol.cs new file mode 100644 index 00000000..3f5b3571 --- /dev/null +++ b/tests/1001-1500/1266. minimum-time-visiting-all-points/sol.cs @@ -0,0 +1,12 @@ +public class Solution { + public int MinTimeToVisitAllPoints(int[][] points) { + int ans = 0; + for (int i = 1; i < points.Length; i++) { + ans += Math.Max( + Math.Abs(points[i][0] - points[i - 1][0]), + Math.Abs(points[i][1] - points[i - 1][1]) + ); + } + return ans; + } +} diff --git a/tests/1001-1500/1266. minimum-time-visiting-all-points/sol.dart b/tests/1001-1500/1266. minimum-time-visiting-all-points/sol.dart new file mode 100644 index 00000000..c0cf45fd --- /dev/null +++ b/tests/1001-1500/1266. minimum-time-visiting-all-points/sol.dart @@ -0,0 +1,11 @@ +class Solution { + int minTimeToVisitAllPoints(List> points) { + int ans = 0; + for (int i = 1; i < points.length; i++) { + int dx = (points[i][0] - points[i - 1][0]).abs(); + int dy = (points[i][1] - points[i - 1][1]).abs(); + ans += dx > dy ? dx : dy; + } + return ans; + } +} diff --git a/tests/1001-1500/1266. minimum-time-visiting-all-points/sol.go b/tests/1001-1500/1266. minimum-time-visiting-all-points/sol.go new file mode 100644 index 00000000..e4008d18 --- /dev/null +++ b/tests/1001-1500/1266. minimum-time-visiting-all-points/sol.go @@ -0,0 +1,19 @@ +func minTimeToVisitAllPoints(points [][]int) int { + ans := 0 + for i := 1; i < len(points); i++ { + dx := points[i][0] - points[i-1][0] + if dx < 0 { + dx = -dx + } + dy := points[i][1] - points[i-1][1] + if dy < 0 { + dy = -dy + } + if dx > dy { + ans += dx + } else { + ans += dy + } + } + return ans +} diff --git a/tests/1001-1500/1266. minimum-time-visiting-all-points/sol.java b/tests/1001-1500/1266. minimum-time-visiting-all-points/sol.java new file mode 100644 index 00000000..9c1e755e --- /dev/null +++ b/tests/1001-1500/1266. minimum-time-visiting-all-points/sol.java @@ -0,0 +1,12 @@ +class Solution { + public int minTimeToVisitAllPoints(int[][] points) { + int ans = 0; + for (int i = 1; i < points.length; i++) { + ans += Math.max( + Math.abs(points[i][0] - points[i - 1][0]), + Math.abs(points[i][1] - points[i - 1][1]) + ); + } + return ans; + } +} diff --git a/tests/1001-1500/1266. minimum-time-visiting-all-points/sol.kt b/tests/1001-1500/1266. minimum-time-visiting-all-points/sol.kt new file mode 100644 index 00000000..4eb65c35 --- /dev/null +++ b/tests/1001-1500/1266. minimum-time-visiting-all-points/sol.kt @@ -0,0 +1,12 @@ +class Solution { + fun minTimeToVisitAllPoints(points: Array): Int { + var ans = 0 + for (i in 1 until points.size) { + ans += maxOf( + kotlin.math.abs(points[i][0] - points[i - 1][0]), + kotlin.math.abs(points[i][1] - points[i - 1][1]) + ) + } + return ans + } +} diff --git a/tests/1001-1500/1266. minimum-time-visiting-all-points/sol.py b/tests/1001-1500/1266. minimum-time-visiting-all-points/sol.py new file mode 100644 index 00000000..b60cda8a --- /dev/null +++ b/tests/1001-1500/1266. minimum-time-visiting-all-points/sol.py @@ -0,0 +1,9 @@ +from typing import List + + +class Solution: + def minTimeToVisitAllPoints(self, p: List[List[int]]) -> int: + Ans = 0 + for i in range(1, len(p)): + Ans += max(abs(p[i][0] - p[i - 1][0]), abs(p[i][1] - p[i - 1][1])) + return Ans diff --git a/tests/1001-1500/1266. minimum-time-visiting-all-points/sol.py2 b/tests/1001-1500/1266. minimum-time-visiting-all-points/sol.py2 new file mode 100644 index 00000000..4c37c080 --- /dev/null +++ b/tests/1001-1500/1266. minimum-time-visiting-all-points/sol.py2 @@ -0,0 +1,13 @@ +class Solution(object): + def minTimeToVisitAllPoints(self, points): + """ + :type points: List[List[int]] + :rtype: int + """ + ans = 0 + for i in range(1, len(points)): + ans += max( + abs(points[i][0] - points[i - 1][0]), + abs(points[i][1] - points[i - 1][1]) + ) + return ans diff --git a/tests/1001-1500/1266. minimum-time-visiting-all-points/sol.rb b/tests/1001-1500/1266. minimum-time-visiting-all-points/sol.rb new file mode 100644 index 00000000..a0a4d35b --- /dev/null +++ b/tests/1001-1500/1266. minimum-time-visiting-all-points/sol.rb @@ -0,0 +1,12 @@ +# @param {Integer[][]} points +# @return {Integer} +def min_time_to_visit_all_points(points) + ans = 0 + (1...points.length).each do |i| + ans += [ + (points[i][0] - points[i - 1][0]).abs, + (points[i][1] - points[i - 1][1]).abs + ].max + end + ans +end diff --git a/tests/1001-1500/1266. minimum-time-visiting-all-points/sol.rs b/tests/1001-1500/1266. minimum-time-visiting-all-points/sol.rs new file mode 100644 index 00000000..e152cd62 --- /dev/null +++ b/tests/1001-1500/1266. minimum-time-visiting-all-points/sol.rs @@ -0,0 +1,11 @@ +impl Solution { + pub fn min_time_to_visit_all_points(points: Vec>) -> i32 { + let mut ans = 0; + for i in 1..points.len() { + let dx = (points[i][0] - points[i - 1][0]).abs(); + let dy = (points[i][1] - points[i - 1][1]).abs(); + ans += dx.max(dy); + } + ans + } +} diff --git a/tests/1001-1500/1266. minimum-time-visiting-all-points/sol.swift b/tests/1001-1500/1266. minimum-time-visiting-all-points/sol.swift new file mode 100644 index 00000000..c4fbf11e --- /dev/null +++ b/tests/1001-1500/1266. minimum-time-visiting-all-points/sol.swift @@ -0,0 +1,11 @@ +class Solution { + func minTimeToVisitAllPoints(_ points: [[Int]]) -> Int { + var ans = 0 + for i in 1.. 1 or col_counts[col] > 1) + ) + return result == expected +seed: 1267 +tests: + - name: "example_diagonal_isolated" + in: + grid: + - [1, 0] + - [0, 1] + out: 0 + - name: "example_three_communicate" + in: + grid: + - [1, 0] + - [1, 1] + out: 3 + - name: "example_mixed_components" + in: + grid: + - [1, 1, 0, 0] + - [0, 0, 1, 0] + - [0, 0, 1, 0] + - [0, 0, 0, 1] + out: 4 + - name: "single_server" + in: + grid: + - [1] + out: 0 + - name: "single_empty_cell" + in: + grid: + - [0] + out: 0 + - name: "one_row_two_servers" + in: + grid: + - [1, 1] + out: 2 + - name: "one_column_two_servers" + in: + grid: + - [1] + - [1] + out: 2 + - name: "one_row_sparse_servers" + in: + grid: + - [1, 0, 1, 0, 1] + out: 3 + - name: "one_column_sparse_servers" + in: + grid: + - [1] + - [0] + - [1] + - [0] + - [1] + out: 3 + - name: "all_empty_rectangle" + in: + grid: + - [0, 0, 0, 0] + - [0, 0, 0, 0] + - [0, 0, 0, 0] + out: 0 + - name: "single_center_server" + in: + grid: + - [0, 0, 0] + - [0, 1, 0] + - [0, 0, 0] + out: 0 + - name: "four_by_four_diagonal" + in: + grid: + - [1, 0, 0, 0] + - [0, 1, 0, 0] + - [0, 0, 1, 0] + - [0, 0, 0, 1] + out: 0 + - name: "row_pair_with_isolated_server" + in: + grid: + - [1, 1, 0] + - [0, 0, 1] + - [0, 0, 0] + out: 2 + - name: "two_independent_column_pairs" + in: + grid: + - [1, 0, 1] + - [1, 0, 0] + - [0, 0, 1] + out: 4 + - name: "cross_shape" + in: + grid: + - [0, 1, 0] + - [1, 1, 1] + - [0, 1, 0] + out: 5 + - name: "full_two_by_three" + in: + grid: + - [1, 1, 1] + - [1, 1, 1] + out: 6 + - name: "checkerboard_four_by_four" + in: + grid: + - [1, 0, 1, 0] + - [0, 1, 0, 1] + - [1, 0, 1, 0] + - [0, 1, 0, 1] + out: 8 + - name: "full_first_row" + in: + grid: + - [1, 1, 1, 1, 1] + - [0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0] + out: 5 + - name: "full_first_column" + in: + grid: + - [1, 0, 0, 0, 0] + - [1, 0, 0, 0, 0] + - [1, 0, 0, 0, 0] + - [1, 0, 0, 0, 0] + - [1, 0, 0, 0, 0] + out: 5 + - name: "two_pairs_and_corner_isolated" + in: + grid: + - [1, 1, 0, 0] + - [0, 0, 1, 0] + - [0, 0, 1, 0] + - [0, 0, 0, 1] + out: 4 + - name: "full_three_by_three" + in: + grid: + - [1, 1, 1] + - [1, 1, 1] + - [1, 1, 1] + out: 9 + - name: "row_pair_linked_by_column" + in: + grid: + - [1, 1, 0] + - [0, 1, 0] + - [0, 0, 0] + out: 3 + - name: "separate_row_and_column_pairs" + in: + grid: + - [1, 0, 1, 0] + - [0, 0, 0, 1] + - [0, 0, 1, 0] + - [0, 0, 0, 1] + out: 5 + - name: "five_by_five_permutation" + in: + grid: + - [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: 0 + - name: "row_pair_and_column_pair" + in: + grid: + - [1, 0, 0, 1] + - [0, 0, 1, 0] + - [0, 0, 1, 0] + - [1, 0, 0, 0] + out: 5 + - name: "communicators_with_two_isolated" + in: + grid: + - [1, 0, 0, 0, 0] + - [0, 1, 1, 0, 0] + - [0, 0, 0, 1, 0] + - [0, 0, 0, 0, 1] + - [1, 0, 0, 0, 0] + out: 4 + - name: "alternating_two_rows" + in: + grid: + - [1, 0, 1, 0, 1] + - [0, 1, 0, 1, 0] + out: 5 + - name: "one_repeated_column" + in: + grid: + - [1, 0, 0, 0, 0] + - [0, 1, 0, 0, 0] + - [1, 0, 0, 0, 0] + out: 2 + - name: "corner_row_and_column" + in: + grid: + - [1, 0, 1] + - [0, 0, 0] + - [1, 0, 0] + out: 3 + - name: "six_servers_all_connected" + in: + grid: + - [1, 1, 0, 0, 0] + - [0, 0, 1, 0, 1] + - [0, 0, 1, 0, 0] + - [0, 0, 0, 0, 1] + out: 6 + - name: "six_by_one_three_servers" + in: + grid: + - [1] + - [0] + - [1] + - [0] + - [0] + - [1] + out: 3 + - name: "one_by_six_single_server" + in: + grid: + - [0, 0, 0, 1, 0, 0] + out: 0 + - name: "full_two_by_two" + in: + grid: + - [1, 1] + - [1, 1] + out: 4 + - name: "three_components_plus_isolated" + in: + grid: + - [1, 0, 0, 0, 0, 1] + - [0, 0, 1, 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, 1, 0] + out: 6 + - name: "generated_dense_250_square" + seed: 126701 + in: + grid: + gen: "array" + len: 250 + distinct: false + sorted: false + of: + gen: "array" + len: 250 + distinct: false + sorted: false + elemType: "int" + of: + gen: "int" + min: 0 + max: 1 + - name: "generated_tall_250_by_249" + seed: 126702 + in: + grid: + gen: "array" + len: 250 + distinct: false + sorted: false + of: + gen: "array" + len: 249 + distinct: false + sorted: false + elemType: "int" + of: + gen: "int" + min: 0 + max: 1 + - name: "generated_wide_249_by_250" + seed: 126703 + in: + grid: + gen: "array" + len: 249 + distinct: false + sorted: false + of: + gen: "array" + len: 250 + distinct: false + sorted: false + elemType: "int" + of: + gen: "int" + min: 0 + max: 1 + - name: "generated_200_by_250" + seed: 126704 + in: + grid: + gen: "array" + len: 200 + distinct: false + sorted: false + of: + gen: "array" + len: 250 + distinct: false + sorted: false + elemType: "int" + of: + gen: "int" + min: 0 + max: 1 + - name: "generated_250_by_200" + seed: 126705 + in: + grid: + gen: "array" + len: 250 + distinct: false + sorted: false + of: + gen: "array" + len: 200 + distinct: false + sorted: false + elemType: "int" + of: + gen: "int" + min: 0 + max: 1 + - name: "generated_225_square" + seed: 126706 + in: + grid: + gen: "array" + len: 225 + distinct: false + sorted: false + of: + gen: "array" + len: 225 + distinct: false + sorted: false + elemType: "int" + of: + gen: "int" + min: 0 + max: 1 diff --git a/tests/1001-1500/1267. count-servers-that-communicate/sol.cpp b/tests/1001-1500/1267. count-servers-that-communicate/sol.cpp new file mode 100644 index 00000000..ba7627ba --- /dev/null +++ b/tests/1001-1500/1267. count-servers-that-communicate/sol.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int countServers(vector>& grid) { + int m = grid.size(); + int n = grid[0].size(); + vector rowCounts(m, 0); + vector colCounts(n, 0); + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == 1) { + rowCounts[i]++; + colCounts[j]++; + } + } + } + int result = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == 1 && (rowCounts[i] > 1 || colCounts[j] > 1)) { + result++; + } + } + } + return result; + } +}; diff --git a/tests/1001-1500/1267. count-servers-that-communicate/sol.cs b/tests/1001-1500/1267. count-servers-that-communicate/sol.cs new file mode 100644 index 00000000..f5b5fae4 --- /dev/null +++ b/tests/1001-1500/1267. count-servers-that-communicate/sol.cs @@ -0,0 +1,25 @@ +public class Solution { + public int CountServers(int[][] grid) { + int m = grid.Length; + int n = grid[0].Length; + int[] rowCounts = new int[m]; + int[] colCounts = new int[n]; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == 1) { + rowCounts[i]++; + colCounts[j]++; + } + } + } + int result = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == 1 && (rowCounts[i] > 1 || colCounts[j] > 1)) { + result++; + } + } + } + return result; + } +} diff --git a/tests/1001-1500/1267. count-servers-that-communicate/sol.dart b/tests/1001-1500/1267. count-servers-that-communicate/sol.dart new file mode 100644 index 00000000..d0cfc9a4 --- /dev/null +++ b/tests/1001-1500/1267. count-servers-that-communicate/sol.dart @@ -0,0 +1,25 @@ +class Solution { + int countServers(List> grid) { + int m = grid.length; + int n = grid[0].length; + List rowCounts = List.filled(m, 0); + List colCounts = List.filled(n, 0); + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == 1) { + rowCounts[i]++; + colCounts[j]++; + } + } + } + int result = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == 1 && (rowCounts[i] > 1 || colCounts[j] > 1)) { + result++; + } + } + } + return result; + } +} diff --git a/tests/1001-1500/1267. count-servers-that-communicate/sol.go b/tests/1001-1500/1267. count-servers-that-communicate/sol.go new file mode 100644 index 00000000..dbb6f109 --- /dev/null +++ b/tests/1001-1500/1267. count-servers-that-communicate/sol.go @@ -0,0 +1,23 @@ +func countServers(grid [][]int) int { + m := len(grid) + n := len(grid[0]) + rowCounts := make([]int, m) + colCounts := make([]int, n) + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if grid[i][j] == 1 { + rowCounts[i]++ + colCounts[j]++ + } + } + } + result := 0 + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if grid[i][j] == 1 && (rowCounts[i] > 1 || colCounts[j] > 1) { + result++ + } + } + } + return result +} diff --git a/tests/1001-1500/1267. count-servers-that-communicate/sol.java b/tests/1001-1500/1267. count-servers-that-communicate/sol.java new file mode 100644 index 00000000..62d036a4 --- /dev/null +++ b/tests/1001-1500/1267. count-servers-that-communicate/sol.java @@ -0,0 +1,25 @@ +class Solution { + public int countServers(int[][] grid) { + int m = grid.length; + int n = grid[0].length; + int[] rowCounts = new int[m]; + int[] colCounts = new int[n]; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == 1) { + rowCounts[i]++; + colCounts[j]++; + } + } + } + int result = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == 1 && (rowCounts[i] > 1 || colCounts[j] > 1)) { + result++; + } + } + } + return result; + } +} diff --git a/tests/1001-1500/1267. count-servers-that-communicate/sol.kt b/tests/1001-1500/1267. count-servers-that-communicate/sol.kt new file mode 100644 index 00000000..09397eac --- /dev/null +++ b/tests/1001-1500/1267. count-servers-that-communicate/sol.kt @@ -0,0 +1,25 @@ +class Solution { + fun countServers(grid: Array): Int { + val m = grid.size + val n = grid[0].size + val rowCounts = IntArray(m) + val colCounts = IntArray(n) + for (i in 0 until m) { + for (j in 0 until n) { + if (grid[i][j] == 1) { + rowCounts[i]++ + colCounts[j]++ + } + } + } + var result = 0 + for (i in 0 until m) { + for (j in 0 until n) { + if (grid[i][j] == 1 && (rowCounts[i] > 1 || colCounts[j] > 1)) { + result++ + } + } + } + return result + } +} diff --git a/tests/1001-1500/1267. count-servers-that-communicate/sol.py b/tests/1001-1500/1267. count-servers-that-communicate/sol.py new file mode 100644 index 00000000..f4c8b6e9 --- /dev/null +++ b/tests/1001-1500/1267. count-servers-that-communicate/sol.py @@ -0,0 +1,13 @@ +class Solution: + def countServers(self, grid): + row_counts = [sum(row) for row in grid] + col_counts = [ + sum(grid[row][col] for row in range(len(grid))) + for col in range(len(grid[0])) + ] + return sum( + cell + for row, values in enumerate(grid) + for col, cell in enumerate(values) + if cell and (row_counts[row] > 1 or col_counts[col] > 1) + ) diff --git a/tests/1001-1500/1267. count-servers-that-communicate/sol.py2 b/tests/1001-1500/1267. count-servers-that-communicate/sol.py2 new file mode 100644 index 00000000..64c8d19b --- /dev/null +++ b/tests/1001-1500/1267. count-servers-that-communicate/sol.py2 @@ -0,0 +1,15 @@ +class Solution(object): + def countServers(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + row_counts = [sum(row) for row in grid] + col_counts = [sum(grid[row][col] for row in range(len(grid))) + for col in range(len(grid[0]))] + return sum( + cell + for row, values in enumerate(grid) + for col, cell in enumerate(values) + if cell and (row_counts[row] > 1 or col_counts[col] > 1) + ) diff --git a/tests/1001-1500/1267. count-servers-that-communicate/sol.rb b/tests/1001-1500/1267. count-servers-that-communicate/sol.rb new file mode 100644 index 00000000..fe3638f4 --- /dev/null +++ b/tests/1001-1500/1267. count-servers-that-communicate/sol.rb @@ -0,0 +1,11 @@ +# @param {Integer[][]} grid +# @return {Integer} +def count_servers(grid) + row_counts = grid.map { |row| row.sum } + col_counts = (0...grid[0].length).map { |col| grid.sum { |row| row[col] } } + grid.each_with_index.sum do |row, r| + row.each_with_index.sum do |cell, c| + cell == 1 && (row_counts[r] > 1 || col_counts[c] > 1) ? 1 : 0 + end + end +end diff --git a/tests/1001-1500/1267. count-servers-that-communicate/sol.rs b/tests/1001-1500/1267. count-servers-that-communicate/sol.rs new file mode 100644 index 00000000..017383bd --- /dev/null +++ b/tests/1001-1500/1267. count-servers-that-communicate/sol.rs @@ -0,0 +1,25 @@ +impl Solution { + pub fn count_servers(grid: Vec>) -> i32 { + let m = grid.len(); + let n = grid[0].len(); + let mut row_counts = vec![0; m]; + let mut col_counts = vec![0; n]; + for i in 0..m { + for j in 0..n { + if grid[i][j] == 1 { + row_counts[i] += 1; + col_counts[j] += 1; + } + } + } + let mut result = 0; + for i in 0..m { + for j in 0..n { + if grid[i][j] == 1 && (row_counts[i] > 1 || col_counts[j] > 1) { + result += 1; + } + } + } + result + } +} diff --git a/tests/1001-1500/1267. count-servers-that-communicate/sol.swift b/tests/1001-1500/1267. count-servers-that-communicate/sol.swift new file mode 100644 index 00000000..0d5888be --- /dev/null +++ b/tests/1001-1500/1267. count-servers-that-communicate/sol.swift @@ -0,0 +1,25 @@ +class Solution { + func countServers(_ grid: [[Int]]) -> Int { + let m = grid.count + let n = grid[0].count + var rowCounts = [Int](repeating: 0, count: m) + var colCounts = [Int](repeating: 0, count: n) + for i in 0.. 1 || colCounts[j] > 1) { + result += 1 + } + } + } + return result + } +} diff --git a/tests/1001-1500/1267. count-servers-that-communicate/sol.ts b/tests/1001-1500/1267. count-servers-that-communicate/sol.ts new file mode 100644 index 00000000..20d921a8 --- /dev/null +++ b/tests/1001-1500/1267. count-servers-that-communicate/sol.ts @@ -0,0 +1,23 @@ +function countServers(grid: number[][]): number { + const m = grid.length; + const n = grid[0].length; + const rowCounts: number[] = new Array(m).fill(0); + const colCounts: number[] = new Array(n).fill(0); + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + if (grid[i][j] === 1) { + rowCounts[i]++; + colCounts[j]++; + } + } + } + let result = 0; + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + if (grid[i][j] === 1 && (rowCounts[i] > 1 || colCounts[j] > 1)) { + result++; + } + } + } + return result; +} diff --git a/tests/1001-1500/1268. search-suggestions-system/manifest.yaml b/tests/1001-1500/1268. search-suggestions-system/manifest.yaml new file mode 100644 index 00000000..df4145f7 --- /dev/null +++ b/tests/1001-1500/1268. search-suggestions-system/manifest.yaml @@ -0,0 +1,525 @@ +entry: + id: 1268 + title: "search-suggestions-system" + params: + products: + type: array + items: + type: string + searchWord: + type: string + call: + cpp: "Solution().suggestedProducts({products}, {searchWord})" + rust: "Solution::suggested_products({products}, {searchWord})" + python3: "Solution().suggestedProducts({products}, {searchWord})" + python2: "Solution().suggestedProducts({products}, {searchWord})" + ruby: "suggested_products({products}, {searchWord})" + java: "new Solution().suggestedProducts({products}, {searchWord})" + csharp: "new Solution().SuggestedProducts({products}, {searchWord})" + kotlin: "Solution().suggestedProducts({products}, {searchWord})" + go: "suggestedProducts({products}, {searchWord})" + dart: "Solution().suggestedProducts({products}, {searchWord})" + swift: "Solution().suggestedProducts({products}, {searchWord})" + typescript: "suggestedProducts({products}, {searchWord})" +judge: + type: exact +limits: + time_ms: 500 + memory_mb: 300 +oracle: + python3: + call: "Checker().suggestedProducts(products, searchWord, {result})" + checker: | + class Checker: + def suggestedProducts(self, products, searchWord, result): + if not isinstance(result, list) or len(result) != len(searchWord): + return False + for index in range(1, len(searchWord) + 1): + expected = sorted( + product for product in products + if product.startswith(searchWord[:index]) + )[:3] + if result[index - 1] != expected: + return False + return True +seed: 1268 +tests: + - name: example_mouse + in: + products: ["mobile", "mouse", "moneypot", "monitor", "mousepad"] + searchWord: "mouse" + out: + - ["mobile", "moneypot", "monitor"] + - ["mobile", "moneypot", "monitor"] + - ["mouse", "mousepad"] + - ["mouse", "mousepad"] + - ["mouse", "mousepad"] + - name: example_single_product + in: + products: ["havana"] + searchWord: "havana" + out: + - ["havana"] + - ["havana"] + - ["havana"] + - ["havana"] + - ["havana"] + - ["havana"] + - name: no_matching_prefix + in: + products: ["bags", "baggage", "banner", "box", "cloths"] + searchWord: "toys" + out: + - [] + - [] + - [] + - [] + - name: one_exact_product + in: + products: ["apple"] + searchWord: "apple" + out: + - ["apple"] + - ["apple"] + - ["apple"] + - ["apple"] + - ["apple"] + - name: one_character_query + in: + products: ["a", "ab", "abc"] + searchWord: "a" + out: + - ["a", "ab", "abc"] + - name: product_then_missing_suffix + in: + products: ["car", "cart"] + searchWord: "care" + out: + - ["car", "cart"] + - ["car", "cart"] + - ["car", "cart"] + - [] + - name: query_outgrows_short_product + in: + products: ["go", "gone"] + searchWord: "good" + out: + - ["go", "gone"] + - ["go", "gone"] + - [] + - [] + - name: exactly_three_unsorted_input + in: + products: ["zebra", "zeus", "zero"] + searchWord: "ze" + out: + - ["zebra", "zero", "zeus"] + - ["zebra", "zero", "zeus"] + - name: four_candidates_top_three + in: + products: ["cat", "cab", "can", "cap"] + searchWord: "ca" + out: + - ["cab", "can", "cap"] + - ["cab", "can", "cap"] + - name: lexical_prefix_order + in: + products: ["apple", "app", "application", "apply", "apt"] + searchWord: "app" + out: + - ["app", "apple", "application"] + - ["app", "apple", "application"] + - ["app", "apple", "application"] + - name: branch_after_first_character + in: + products: ["dog", "deer", "deal", "cat"] + searchWord: "de" + out: + - ["deal", "deer", "dog"] + - ["deal", "deer"] + - name: match_then_permanent_miss + in: + products: ["ant", "anchor", "angle", "bear"] + searchWord: "anx" + out: + - ["anchor", "angle", "ant"] + - ["anchor", "angle", "ant"] + - [] + - name: common_prefix_many_depths + in: + products: ["star", "start", "stare", "stack", "stamp", "stand"] + searchWord: "star" + out: + - ["stack", "stamp", "stand"] + - ["stack", "stamp", "stand"] + - ["stack", "stamp", "stand"] + - ["star", "stare", "start"] + - name: initial_character_absent + in: + products: ["apple", "banana", "cherry"] + searchWord: "zoo" + out: + - [] + - [] + - [] + - name: lowest_letter_and_short_prefixes + in: + products: ["a", "aa", "aaa", "aab", "b"] + searchWord: "aa" + out: + - ["a", "aa", "aaa"] + - ["aa", "aaa", "aab"] + - name: highest_letter_prefix + in: + products: ["z", "za", "zebra", "zoo", "zoom"] + searchWord: "zoo" + out: + - ["z", "za", "zebra"] + - ["zoo", "zoom"] + - ["zoo", "zoom"] + - name: identical_long_prefix_selection + in: + products: ["flower", "flow", "flight", "flock", "flute"] + searchWord: "flo" + out: + - ["flight", "flock", "flow"] + - ["flight", "flock", "flow"] + - ["flock", "flow", "flower"] + - name: input_sorting_required + in: + products: ["mop", "map", "moon", "milk", "mouse"] + searchWord: "m" + out: + - ["map", "milk", "moon"] + - name: one_match_among_many + in: + products: ["alpha", "beta", "gamma", "delta", "omega"] + searchWord: "ome" + out: + - ["omega"] + - ["omega"] + - ["omega"] + - name: complete_prefix_chain + in: + products: ["i", "in", "inn", "inner", "into"] + searchWord: "inner" + out: + - ["i", "in", "inn"] + - ["in", "inn", "inner"] + - ["inn", "inner"] + - ["inner"] + - ["inner"] + - name: absent_first_letter + in: + products: ["red", "green", "blue"] + searchWord: "yellow" + out: + - [] + - [] + - [] + - [] + - [] + - [] + - name: exact_three_refine + in: + products: ["train", "trap", "trace"] + searchWord: "tra" + out: + - ["trace", "train", "trap"] + - ["trace", "train", "trap"] + - ["trace", "train", "trap"] + - name: sparse_lexical_intervals + in: + products: ["az", "aa", "ab", "b", "baa"] + searchWord: "a" + out: + - ["aa", "ab", "az"] + - name: deeper_candidate_replacement + in: + products: ["preach", "prefix", "prepare", "present", "press", "pretty"] + searchWord: "pre" + out: + - ["preach", "prefix", "prepare"] + - ["preach", "prefix", "prepare"] + - ["preach", "prefix", "prepare"] + - name: later_character_miss + in: + products: ["table", "tablet", "tabby", "taco"] + searchWord: "tabs" + out: + - ["tabby", "table", "tablet"] + - ["tabby", "table", "tablet"] + - ["tabby", "table", "tablet"] + - [] + - name: query_is_not_a_product + in: + products: ["code", "coder", "coding", "coffee"] + searchWord: "codex" + out: + - ["code", "coder", "coding"] + - ["code", "coder", "coding"] + - ["code", "coder", "coding"] + - ["code", "coder"] + - [] + - name: single_letter_products + in: + products: ["a", "b", "c", "d"] + searchWord: "c" + out: + - ["c"] + - name: shared_prefix_beyond_three + in: + products: ["aaaa", "aaab", "aaac", "aaad", "aaae", "b"] + searchWord: "aaa" + out: + - ["aaaa", "aaab", "aaac"] + - ["aaaa", "aaab", "aaac"] + - ["aaaa", "aaab", "aaac"] + - name: search_ends_at_internal_node + in: + products: ["network", "net", "neutral", "new", "next"] + searchWord: "net" + out: + - ["net", "network", "neutral"] + - ["net", "network", "neutral"] + - ["net", "network"] + - name: alphabetical_not_length_order + in: + products: ["aaz", "aa", "aab", "aaaa"] + searchWord: "aa" + out: + - ["aa", "aaaa", "aab"] + - ["aa", "aaaa", "aab"] + - name: word_after_matching_prefix + in: + products: ["sun", "sunday", "sunny", "super", "supply"] + searchWord: "sunset" + out: + - ["sun", "sunday", "sunny"] + - ["sun", "sunday", "sunny"] + - ["sun", "sunday", "sunny"] + - [] + - [] + - [] + - name: products_at_multiple_lengths + in: + products: ["x", "xy", "xyz", "xyzz", "xz"] + searchWord: "xyz" + out: + - ["x", "xy", "xyz"] + - ["xy", "xyz", "xyzz"] + - ["xyz", "xyzz"] + - name: only_later_lexical_words_match + in: + products: ["aardvark", "azure", "bake", "ball", "bat", "zebra"] + searchWord: "ba" + out: + - ["bake", "ball", "bat"] + - ["bake", "ball", "bat"] + - name: prefix_with_one_of_three_remaining + in: + products: ["plane", "planet", "plant", "plate", "play"] + searchWord: "platen" + out: + - ["plane", "planet", "plant"] + - ["plane", "planet", "plant"] + - ["plane", "planet", "plant"] + - ["plate"] + - ["plate"] + - [] + - name: stress_many_transport_products + in: + products: + [ + "tram", + "train", + "transact", + "transfer", + "transform", + "transit", + "translate", + "transmit", + "transparent", + "trap", + "travel", + "tree", + "triangle", + "truck", + "turtle", + ] + searchWord: "transformation" + out: + - ["train", "tram", "transact"] + - ["train", "tram", "transact"] + - ["train", "tram", "transact"] + - ["transact", "transfer", "transform"] + - ["transact", "transfer", "transform"] + - ["transfer", "transform"] + - ["transform"] + - ["transform"] + - ["transform"] + - [] + - [] + - [] + - [] + - [] + - name: stress_deep_shared_prefix + in: + products: + [ + "abcdefgha", + "abcdefghi", + "abcdefghj", + "abcdefghk", + "abcdefgzz", + "abcdefh", + "abcde", + "abcdx", + "abcz", + "ax", + ] + searchWord: "abcdefghj" + out: + - ["abcde", "abcdefgha", "abcdefghi"] + - ["abcde", "abcdefgha", "abcdefghi"] + - ["abcde", "abcdefgha", "abcdefghi"] + - ["abcde", "abcdefgha", "abcdefghi"] + - ["abcde", "abcdefgha", "abcdefghi"] + - ["abcdefgha", "abcdefghi", "abcdefghj"] + - ["abcdefgha", "abcdefghi", "abcdefghj"] + - ["abcdefgha", "abcdefghi", "abcdefghj"] + - ["abcdefghj"] + - name: stress_dense_book_catalog + in: + products: + [ + "book", + "bookcase", + "bookend", + "bookkeeper", + "bookkeeping", + "booklet", + "bookmark", + "bookmobile", + "bookshelf", + "bookstore", + "boost", + "boot", + "border", + "bottle", + ] + searchWord: "bookkeeper" + out: + - ["book", "bookcase", "bookend"] + - ["book", "bookcase", "bookend"] + - ["book", "bookcase", "bookend"] + - ["book", "bookcase", "bookend"] + - ["bookkeeper", "bookkeeping"] + - ["bookkeeper", "bookkeeping"] + - ["bookkeeper", "bookkeeping"] + - ["bookkeeper", "bookkeeping"] + - ["bookkeeper"] + - ["bookkeeper"] + - name: stress_long_words_and_late_miss + in: + products: + [ + "characteristically", + "characterization", + "characterize", + "characterless", + "charcoal", + "charge", + "chart", + "chase", + ] + searchWord: "characterizationz" + out: + - ["characteristically", "characterization", "characterize"] + - ["characteristically", "characterization", "characterize"] + - ["characteristically", "characterization", "characterize"] + - ["characteristically", "characterization", "characterize"] + - ["characteristically", "characterization", "characterize"] + - ["characteristically", "characterization", "characterize"] + - ["characteristically", "characterization", "characterize"] + - ["characteristically", "characterization", "characterize"] + - ["characteristically", "characterization", "characterize"] + - ["characteristically", "characterization", "characterize"] + - ["characterization", "characterize"] + - ["characterization"] + - ["characterization"] + - ["characterization"] + - ["characterization"] + - ["characterization"] + - [] + - name: stress_international_prefixes + in: + products: + [ + "integer", + "integral", + "integrate", + "integration", + "intellect", + "intelligence", + "intense", + "interest", + "internal", + "internet", + "international", + "interval", + "into", + "intricate", + "intro", + ] + searchWord: "international" + out: + - ["integer", "integral", "integrate"] + - ["integer", "integral", "integrate"] + - ["integer", "integral", "integrate"] + - ["integer", "integral", "integrate"] + - ["interest", "internal", "international"] + - ["internal", "international", "internet"] + - ["internal", "international"] + - ["international"] + - ["international"] + - ["international"] + - ["international"] + - ["international"] + - ["international"] + - name: stress_wide_prefix_catalog + in: + products: + [ + "program", + "programmer", + "programming", + "progress", + "project", + "promise", + "promote", + "prompt", + "pronoun", + "proof", + "propel", + "proper", + "property", + "prose", + "protect", + "protein", + "proton", + "provide", + ] + searchWord: "programming" + out: + - ["program", "programmer", "programming"] + - ["program", "programmer", "programming"] + - ["program", "programmer", "programming"] + - ["program", "programmer", "programming"] + - ["program", "programmer", "programming"] + - ["program", "programmer", "programming"] + - ["program", "programmer", "programming"] + - ["programmer", "programming"] + - ["programming"] + - ["programming"] + - ["programming"] diff --git a/tests/1001-1500/1268. search-suggestions-system/sol.cpp b/tests/1001-1500/1268. search-suggestions-system/sol.cpp new file mode 100644 index 00000000..f885368d --- /dev/null +++ b/tests/1001-1500/1268. search-suggestions-system/sol.cpp @@ -0,0 +1,40 @@ +class Solution { +public: + vector> suggestedProducts(vector& products, string searchWord) { + sort(products.begin(), products.end()); + struct TrieNode { + map children; + vector suggestions; + }; + TrieNode* root = new TrieNode(); + + // Insert each product into the Trie and store top 3 suggestions + for (const string& product : products) { + TrieNode* node = root; + for (char ch : product) { + if (node->children.find(ch) == node->children.end()) { + node->children[ch] = new TrieNode(); + } + node = node->children[ch]; + if (node->suggestions.size() < 3) { + node->suggestions.push_back(product); + } + } + } + + // Search each character of searchWord in the Trie + vector> result; + TrieNode* node = root; + for (char ch : searchWord) { + if (node && node->children.find(ch) != node->children.end()) { + node = node->children[ch]; + result.push_back(node->suggestions); + } else { + node = nullptr; + result.push_back({}); + } + } + + return result; + } +}; diff --git a/tests/1001-1500/1268. search-suggestions-system/sol.cs b/tests/1001-1500/1268. search-suggestions-system/sol.cs new file mode 100644 index 00000000..8d5b9a85 --- /dev/null +++ b/tests/1001-1500/1268. search-suggestions-system/sol.cs @@ -0,0 +1,19 @@ +public class Solution { + public IList> SuggestedProducts(string[] products, string searchWord) { + Array.Sort(products); + var answer = new List>(); + var prefix = ""; + foreach (char ch in searchWord) { + prefix += ch; + var current = new List(); + foreach (string product in products) { + if (product.StartsWith(prefix)) { + current.Add(product); + if (current.Count == 3) break; + } + } + answer.Add(current); + } + return answer; + } +} diff --git a/tests/1001-1500/1268. search-suggestions-system/sol.dart b/tests/1001-1500/1268. search-suggestions-system/sol.dart new file mode 100644 index 00000000..32ab769a --- /dev/null +++ b/tests/1001-1500/1268. search-suggestions-system/sol.dart @@ -0,0 +1,40 @@ +class Solution { + List> suggestedProducts(List products, String searchWord) { + products.sort(); + var root = >{}; + + // Insert each product into the Trie and store top 3 suggestions + for (var product in products) { + var node = root; + for (var i = 0; i < product.length; i++) { + var ch = product[i]; + if (!node.containsKey(ch)) { + node[ch] = [>{}, []]; + } + var pair = node[ch]!; + var suggestions = pair[1] as List; + if (suggestions.length < 3) { + suggestions.add(product); + } + node = pair[0] as Map>; + } + } + + // Search each character of searchWord in the Trie + var result = >[]; + Map>? node = root; + for (var i = 0; i < searchWord.length; i++) { + var ch = searchWord[i]; + if (node != null && node.containsKey(ch)) { + var pair = node[ch]!; + result.add(List.from(pair[1] as List)); + node = pair[0] as Map>; + } else { + node = null; + result.add([]); + } + } + + return result; + } +} diff --git a/tests/1001-1500/1268. search-suggestions-system/sol.go b/tests/1001-1500/1268. search-suggestions-system/sol.go new file mode 100644 index 00000000..075810bc --- /dev/null +++ b/tests/1001-1500/1268. search-suggestions-system/sol.go @@ -0,0 +1,41 @@ +func suggestedProducts(products []string, searchWord string) [][]string { + sort.Strings(products) + type node struct { + children map[rune]*node + suggestions []string + } + root := &node{children: make(map[rune]*node)} + + // Insert each product into the Trie and store top 3 suggestions + for _, product := range products { + curr := root + for _, ch := range product { + if _, ok := curr.children[ch]; !ok { + curr.children[ch] = &node{children: make(map[rune]*node)} + } + curr = curr.children[ch] + if len(curr.suggestions) < 3 { + curr.suggestions = append(curr.suggestions, product) + } + } + } + + // Search each character of searchWord in the Trie + result := make([][]string, 0) + curr := root + for _, ch := range searchWord { + if curr != nil { + if next, ok := curr.children[ch]; ok { + curr = next + result = append(result, curr.suggestions) + } else { + curr = nil + result = append(result, []string{}) + } + } else { + result = append(result, []string{}) + } + } + + return result +} diff --git a/tests/1001-1500/1268. search-suggestions-system/sol.java b/tests/1001-1500/1268. search-suggestions-system/sol.java new file mode 100644 index 00000000..cb239783 --- /dev/null +++ b/tests/1001-1500/1268. search-suggestions-system/sol.java @@ -0,0 +1,19 @@ +class Solution { + public List> suggestedProducts(String[] products, String searchWord) { + Arrays.sort(products); + List> answer = new ArrayList<>(); + String prefix = ""; + for (char ch : searchWord.toCharArray()) { + prefix += ch; + List current = new ArrayList<>(); + for (String product : products) { + if (product.startsWith(prefix)) { + current.add(product); + if (current.size() == 3) break; + } + } + answer.add(current); + } + return answer; + } +} diff --git a/tests/1001-1500/1268. search-suggestions-system/sol.kt b/tests/1001-1500/1268. search-suggestions-system/sol.kt new file mode 100644 index 00000000..65557958 --- /dev/null +++ b/tests/1001-1500/1268. search-suggestions-system/sol.kt @@ -0,0 +1,12 @@ +class Solution { + fun suggestedProducts(products: Array, searchWord: String): List> { + products.sort() + val answer = mutableListOf>() + var prefix = "" + for (ch in searchWord) { + prefix += ch + answer.add(products.asSequence().filter { it.startsWith(prefix) }.take(3).toList()) + } + return answer + } +} diff --git a/tests/1001-1500/1268. search-suggestions-system/sol.py b/tests/1001-1500/1268. search-suggestions-system/sol.py new file mode 100644 index 00000000..fa3bbfe9 --- /dev/null +++ b/tests/1001-1500/1268. search-suggestions-system/sol.py @@ -0,0 +1,33 @@ +class TrieNode: + def __init__(self): + self.children = {} + self.suggestions = [] + + +class Solution: + def suggestedProducts(self, products, searchWord): + products.sort() + root = TrieNode() + + # Insert each product into the Trie and store top 3 suggestions + for product in products: + node = root + for char in product: + if char not in node.children: + node.children[char] = TrieNode() + node = node.children[char] + if len(node.suggestions) < 3: + node.suggestions.append(product) + + # Search each character of searchWord in the Trie + result = [] + node = root + for char in searchWord: + if node and char in node.children: + node = node.children[char] + result.append(node.suggestions) + else: + node = None + result.append([]) + + return result diff --git a/tests/1001-1500/1268. search-suggestions-system/sol.py2 b/tests/1001-1500/1268. search-suggestions-system/sol.py2 new file mode 100644 index 00000000..953b852c --- /dev/null +++ b/tests/1001-1500/1268. search-suggestions-system/sol.py2 @@ -0,0 +1,32 @@ +class Solution(object): + def suggestedProducts(self, products, searchWord): + """ + :type products: List[str] + :type searchWord: str + :rtype: List[List[str]] + """ + products.sort() + root = {} + + # Insert each product into the Trie and store top 3 suggestions + for product in products: + node = root + for ch in product: + if ch not in node: + node[ch] = [{}, []] + if len(node[ch][1]) < 3: + node[ch][1].append(product) + node = node[ch][0] + + # Search each character of searchWord in the Trie + result = [] + node = root + for ch in searchWord: + if node and ch in node: + result.append(node[ch][1]) + node = node[ch][0] + else: + node = None + result.append([]) + + return result diff --git a/tests/1001-1500/1268. search-suggestions-system/sol.rb b/tests/1001-1500/1268. search-suggestions-system/sol.rb new file mode 100644 index 00000000..ebb642f0 --- /dev/null +++ b/tests/1001-1500/1268. search-suggestions-system/sol.rb @@ -0,0 +1,36 @@ +# @param {String[]} products +# @param {String} search_word +# @return {String[][]} +def suggested_products(products, search_word) + products.sort! + root = {} + + # Insert each product into the Trie and store top 3 suggestions + products.each do |product| + node = root + product.each_char do |ch| + if !node.key?(ch) + node[ch] = [{}, []] + end + if node[ch][1].length < 3 + node[ch][1] << product + end + node = node[ch][0] + end + end + + # Search each character of searchWord in the Trie + result = [] + node = root + search_word.each_char do |ch| + if node && node.key?(ch) + result << node[ch][1] + node = node[ch][0] + else + node = nil + result << [] + end + end + + result +end diff --git a/tests/1001-1500/1268. search-suggestions-system/sol.rs b/tests/1001-1500/1268. search-suggestions-system/sol.rs new file mode 100644 index 00000000..517f19e2 --- /dev/null +++ b/tests/1001-1500/1268. search-suggestions-system/sol.rs @@ -0,0 +1,12 @@ +impl Solution { + pub fn suggested_products(mut products: Vec, search_word: String) -> Vec> { + products.sort(); + let mut answer = Vec::new(); + let mut prefix = String::new(); + for ch in search_word.chars() { + prefix.push(ch); + answer.push(products.iter().filter(|product| product.starts_with(&prefix)).take(3).cloned().collect()); + } + answer + } +} diff --git a/tests/1001-1500/1268. search-suggestions-system/sol.swift b/tests/1001-1500/1268. search-suggestions-system/sol.swift new file mode 100644 index 00000000..3daef5f8 --- /dev/null +++ b/tests/1001-1500/1268. search-suggestions-system/sol.swift @@ -0,0 +1,12 @@ +class Solution { + func suggestedProducts(_ products: [String], _ searchWord: String) -> [[String]] { + let products = products.sorted() + var answer = [[String]]() + var prefix = "" + for ch in searchWord { + prefix.append(ch) + answer.append(Array(products.filter { $0.hasPrefix(prefix) }.prefix(3))) + } + return answer + } +} diff --git a/tests/1001-1500/1268. search-suggestions-system/sol.ts b/tests/1001-1500/1268. search-suggestions-system/sol.ts new file mode 100644 index 00000000..ac3d8c34 --- /dev/null +++ b/tests/1001-1500/1268. search-suggestions-system/sol.ts @@ -0,0 +1,35 @@ +function suggestedProducts(products: string[], searchWord: string): string[][] { + products.sort(); + const root: Map, string[]]> = new Map(); + + // Insert each product into the Trie and store top 3 suggestions + for (const product of products) { + let node = root; + for (const ch of product) { + if (!node.has(ch)) { + node.set(ch, [new Map(), []]); + } + const pair = node.get(ch)!; + if (pair[1].length < 3) { + pair[1].push(product); + } + node = pair[0]; + } + } + + // Search each character of searchWord in the Trie + const result: string[][] = []; + let node: Map | null = root; + for (const ch of searchWord) { + if (node && node.has(ch)) { + const pair = node.get(ch)!; + result.push([...pair[1]]); + node = pair[0]; + } else { + node = null; + result.push([]); + } + } + + return result; +} diff --git a/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/manifest.yaml b/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/manifest.yaml new file mode 100644 index 00000000..3735b537 --- /dev/null +++ b/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/manifest.yaml @@ -0,0 +1,286 @@ +entry: + id: 1269 + title: "number-of-ways-to-stay-in-the-same-place-after-some-steps" + params: + steps: + type: int + arrLen: + type: int + call: + cpp: "Solution().numWays({steps}, {arrLen})" + rust: "Solution::num_ways({steps}, {arrLen})" + python3: "Solution().numWays({steps}, {arrLen})" + python2: "Solution().numWays({steps}, {arrLen})" + ruby: "num_ways({steps}, {arrLen})" + java: "new Solution().numWays({steps}, {arrLen})" + csharp: "new Solution().NumWays({steps}, {arrLen})" + kotlin: "Solution().numWays({steps}, {arrLen})" + go: "numWays({steps}, {arrLen})" + dart: "Solution().numWays({steps}, {arrLen})" + swift: "Solution().numWays({steps}, {arrLen})" + typescript: "numWays({steps}, {arrLen})" + +judge: + type: "exact" + +limits: + time_ms: 700 + memory_mb: 300 + +oracle: + python3: + call: "Checker().numWays(steps, arrLen, {result})" + checker: | + from functools import lru_cache + + class Checker: + def numWays(self, steps, arrLen, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if not (1 <= steps <= 500 and 1 <= arrLen <= 1000000): + return False + mod = 1000000007 + + @lru_cache(None) + def count(remaining, position): + if remaining == 0: + return int(position == 0) + total = count(remaining - 1, position) + if position > 0: + total += count(remaining - 1, position - 1) + if position + 1 < arrLen: + total += count(remaining - 1, position + 1) + return total % mod + + return result == count(steps, 0) + +seed: 126900 + +tests: + - name: "example_one" + in: + steps: 3 + arrLen: 2 + out: 4 + - name: "example_two" + in: + steps: 2 + arrLen: 4 + out: 2 + - name: "example_three" + in: + steps: 4 + arrLen: 2 + out: 8 + - name: "one_step_one_cell" + in: + steps: 1 + arrLen: 1 + out: 1 + - name: "one_step_maximum_array" + in: + steps: 1 + arrLen: 1000000 + out: 1 + - name: "two_steps_one_cell" + in: + steps: 2 + arrLen: 1 + out: 1 + - name: "two_steps_two_cells" + in: + steps: 2 + arrLen: 2 + out: 2 + - name: "two_steps_maximum_array" + in: + steps: 2 + arrLen: 1000000 + out: 2 + - name: "three_steps_one_cell" + in: + steps: 3 + arrLen: 1 + out: 1 + - name: "three_steps_wide_enough" + in: + steps: 3 + arrLen: 3 + out: 4 + - name: "four_steps_one_cell" + in: + steps: 4 + arrLen: 1 + out: 1 + - name: "four_steps_two_cells" + in: + steps: 4 + arrLen: 2 + out: 8 + - name: "four_steps_three_cells" + in: + steps: 4 + arrLen: 3 + out: 9 + - name: "four_steps_maximum_array" + in: + steps: 4 + arrLen: 1000000 + out: 9 + - name: "five_steps_two_cells" + in: + steps: 5 + arrLen: 2 + out: 16 + - name: "five_steps_three_cells" + in: + steps: 5 + arrLen: 3 + out: 21 + - name: "five_steps_large_array" + in: + steps: 5 + arrLen: 100 + out: 21 + - name: "six_steps_two_cells" + in: + steps: 6 + arrLen: 2 + out: 32 + - name: "six_steps_three_cells" + in: + steps: 6 + arrLen: 3 + out: 50 + - name: "six_steps_four_cells" + in: + steps: 6 + arrLen: 4 + out: 51 + - name: "eight_steps_one_cell" + in: + steps: 8 + arrLen: 1 + out: 1 + - name: "eight_steps_two_cells" + in: + steps: 8 + arrLen: 2 + out: 128 + - name: "eight_steps_four_cells" + in: + steps: 8 + arrLen: 4 + out: 322 + - name: "ten_steps_two_cells" + in: + steps: 10 + arrLen: 2 + out: 512 + - name: "ten_steps_three_cells" + in: + steps: 10 + arrLen: 3 + out: 1682 + - name: "ten_steps_six_cells" + in: + steps: 10 + arrLen: 6 + out: 2188 + - name: "twenty_steps_one_cell" + in: + steps: 20 + arrLen: 1 + out: 1 + - name: "twenty_steps_three_cells" + in: + steps: 20 + arrLen: 3 + out: 11309769 + - name: "fifty_steps_two_cells_modulo" + in: + steps: 50 + arrLen: 2 + out: 949480669 + - name: "fifty_steps_width_boundary" + in: + steps: 50 + arrLen: 25 + out: 852867641 + - name: "hundred_steps_two_cells_modulo" + in: + steps: 100 + arrLen: 2 + out: 988185646 + - name: "hundred_steps_wide_enough" + in: + steps: 100 + arrLen: 50 + out: 345787717 + - name: "maximum_steps_one_cell" + in: + steps: 500 + arrLen: 1 + out: 1 + - name: "maximum_steps_two_cells" + in: + steps: 500 + arrLen: 2 + out: 695241507 + - name: "generated_near_maximum_array" + seed: 126901 + in: + steps: 500 + arrLen: + gen: "int" + min: 999000 + max: 1000000 + - name: "generated_near_maximum_steps" + seed: 126902 + in: + steps: + gen: "int" + min: 495 + max: 500 + arrLen: 1000000 + - name: "generated_full_width_boundary" + seed: 126903 + in: + steps: + gen: "int" + min: 450 + max: 500 + arrLen: + gen: "int" + min: 250 + max: 500 + - name: "generated_large_array_range" + seed: 126904 + in: + steps: + gen: "int" + min: 450 + max: 500 + arrLen: + gen: "int" + min: 10000 + max: 1000000 + - name: "generated_high_steps_narrow_boundary" + seed: 126905 + in: + steps: 500 + arrLen: + gen: "int" + min: 2 + max: 250 + - name: "generated_maximum_width_range" + seed: 126906 + in: + steps: + gen: "int" + min: 490 + max: 500 + arrLen: + gen: "int" + min: 251 + max: 1000000 diff --git a/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.cpp b/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.cpp new file mode 100644 index 00000000..e74aec35 --- /dev/null +++ b/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int numWays(int steps, int arrLen) { + const int MOD = 1000000007; + int maxPos = min(steps / 2, arrLen - 1); + vector dp(maxPos + 1, 0); + dp[0] = 1; + for (int step = 0; step < steps; step++) { + vector newDp(maxPos + 1, 0); + for (int pos = 0; pos <= maxPos; pos++) { + if (dp[pos] == 0) continue; + newDp[pos] = (newDp[pos] + dp[pos]) % MOD; + if (pos > 0) newDp[pos - 1] = (newDp[pos - 1] + dp[pos]) % MOD; + if (pos < maxPos) newDp[pos + 1] = (newDp[pos + 1] + dp[pos]) % MOD; + } + dp = newDp; + } + return dp[0]; + } +}; diff --git a/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.cs b/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.cs new file mode 100644 index 00000000..ea918a93 --- /dev/null +++ b/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.cs @@ -0,0 +1,19 @@ +public class Solution { + public int NumWays(int steps, int arrLen) { + const int MOD = 1000000007; + int maxPos = Math.Min(steps / 2, arrLen - 1); + int[] dp = new int[maxPos + 1]; + dp[0] = 1; + for (int step = 0; step < steps; step++) { + int[] newDp = new int[maxPos + 1]; + for (int pos = 0; pos <= maxPos; pos++) { + if (dp[pos] == 0) continue; + newDp[pos] = (newDp[pos] + dp[pos]) % MOD; + if (pos > 0) newDp[pos - 1] = (newDp[pos - 1] + dp[pos]) % MOD; + if (pos < maxPos) newDp[pos + 1] = (newDp[pos + 1] + dp[pos]) % MOD; + } + dp = newDp; + } + return dp[0]; + } +} diff --git a/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.dart b/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.dart new file mode 100644 index 00000000..ea9fa4fd --- /dev/null +++ b/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.dart @@ -0,0 +1,19 @@ +class Solution { + int numWays(int steps, int arrLen) { + const int MOD = 1000000007; + int maxPos = (steps ~/ 2) < (arrLen - 1) ? (steps ~/ 2) : (arrLen - 1); + List dp = List.filled(maxPos + 1, 0); + dp[0] = 1; + for (int step = 0; step < steps; step++) { + List newDp = List.filled(maxPos + 1, 0); + for (int pos = 0; pos <= maxPos; pos++) { + if (dp[pos] == 0) continue; + newDp[pos] = (newDp[pos] + dp[pos]) % MOD; + if (pos > 0) newDp[pos - 1] = (newDp[pos - 1] + dp[pos]) % MOD; + if (pos < maxPos) newDp[pos + 1] = (newDp[pos + 1] + dp[pos]) % MOD; + } + dp = newDp; + } + return dp[0]; + } +} diff --git a/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.go b/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.go new file mode 100644 index 00000000..f882bb8d --- /dev/null +++ b/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.go @@ -0,0 +1,26 @@ +func numWays(steps int, arrLen int) int { + const MOD = 1000000007 + maxPos := steps / 2 + if arrLen-1 < maxPos { + maxPos = arrLen - 1 + } + dp := make([]int, maxPos+1) + dp[0] = 1 + for step := 0; step < steps; step++ { + newDp := make([]int, maxPos+1) + for pos := 0; pos <= maxPos; pos++ { + if dp[pos] == 0 { + continue + } + newDp[pos] = (newDp[pos] + dp[pos]) % MOD + if pos > 0 { + newDp[pos-1] = (newDp[pos-1] + dp[pos]) % MOD + } + if pos < maxPos { + newDp[pos+1] = (newDp[pos+1] + dp[pos]) % MOD + } + } + dp = newDp + } + return dp[0] +} diff --git a/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.java b/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.java new file mode 100644 index 00000000..196a465f --- /dev/null +++ b/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.java @@ -0,0 +1,19 @@ +class Solution { + public int numWays(int steps, int arrLen) { + final int MOD = 1000000007; + int maxPos = Math.min(steps / 2, arrLen - 1); + int[] dp = new int[maxPos + 1]; + dp[0] = 1; + for (int step = 0; step < steps; step++) { + int[] newDp = new int[maxPos + 1]; + for (int pos = 0; pos <= maxPos; pos++) { + if (dp[pos] == 0) continue; + newDp[pos] = (newDp[pos] + dp[pos]) % MOD; + if (pos > 0) newDp[pos - 1] = (newDp[pos - 1] + dp[pos]) % MOD; + if (pos < maxPos) newDp[pos + 1] = (newDp[pos + 1] + dp[pos]) % MOD; + } + dp = newDp; + } + return dp[0]; + } +} diff --git a/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.kt b/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.kt new file mode 100644 index 00000000..10a72f44 --- /dev/null +++ b/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.kt @@ -0,0 +1,19 @@ +class Solution { + fun numWays(steps: Int, arrLen: Int): Int { + val MOD = 1000000007 + val maxPos = minOf(steps / 2, arrLen - 1) + var dp = IntArray(maxPos + 1) + dp[0] = 1 + repeat(steps) { + val newDp = IntArray(maxPos + 1) + for (pos in 0..maxPos) { + if (dp[pos] == 0) continue + newDp[pos] = (newDp[pos] + dp[pos]) % MOD + if (pos > 0) newDp[pos - 1] = (newDp[pos - 1] + dp[pos]) % MOD + if (pos < maxPos) newDp[pos + 1] = (newDp[pos + 1] + dp[pos]) % MOD + } + dp = newDp + } + return dp[0] + } +} diff --git a/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.py b/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.py new file mode 100644 index 00000000..ace90a71 --- /dev/null +++ b/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.py @@ -0,0 +1,21 @@ +class Solution: + def numWays(self, steps: int, arrLen: int) -> int: + MOD = 10**9 + 7 + maxPos = min(steps // 2, arrLen - 1) + dp = [0] * (maxPos + 1) + dp[0] = 1 + for step in range(steps): + newDp = [0] * (maxPos + 1) + + for pos in range(maxPos + 1): + if dp[pos] == 0: + continue + newDp[pos] = (newDp[pos] + dp[pos]) % MOD + if pos > 0: + newDp[pos - 1] = (newDp[pos - 1] + dp[pos]) % MOD + if pos < maxPos: + newDp[pos + 1] = (newDp[pos + 1] + dp[pos]) % MOD + + dp = newDp + + return dp[0] diff --git a/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.py2 b/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.py2 new file mode 100644 index 00000000..6a4edcf8 --- /dev/null +++ b/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.py2 @@ -0,0 +1,23 @@ +class Solution(object): + def numWays(self, steps, arrLen): + """ + :type steps: int + :type arrLen: int + :rtype: int + """ + MOD = 10**9 + 7 + maxPos = min(steps // 2, arrLen - 1) + dp = [0] * (maxPos + 1) + dp[0] = 1 + for step in range(steps): + newDp = [0] * (maxPos + 1) + for pos in range(maxPos + 1): + if dp[pos] == 0: + continue + newDp[pos] = (newDp[pos] + dp[pos]) % MOD + if pos > 0: + newDp[pos - 1] = (newDp[pos - 1] + dp[pos]) % MOD + if pos < maxPos: + newDp[pos + 1] = (newDp[pos + 1] + dp[pos]) % MOD + dp = newDp + return dp[0] diff --git a/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.rb b/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.rb new file mode 100644 index 00000000..83e58691 --- /dev/null +++ b/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.rb @@ -0,0 +1,20 @@ +# @param {Integer} steps +# @param {Integer} arr_len +# @return {Integer} +def num_ways(steps, arr_len) + mod = 10**9 + 7 + max_pos = [steps / 2, arr_len - 1].min + dp = [0] * (max_pos + 1) + dp[0] = 1 + steps.times do + new_dp = [0] * (max_pos + 1) + (0..max_pos).each do |pos| + next if dp[pos] == 0 + new_dp[pos] = (new_dp[pos] + dp[pos]) % mod + new_dp[pos - 1] = (new_dp[pos - 1] + dp[pos]) % mod if pos > 0 + new_dp[pos + 1] = (new_dp[pos + 1] + dp[pos]) % mod if pos < max_pos + end + dp = new_dp + end + dp[0] +end diff --git a/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.rs b/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.rs new file mode 100644 index 00000000..e7569dc1 --- /dev/null +++ b/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.rs @@ -0,0 +1,25 @@ +impl Solution { + pub fn num_ways(steps: i32, arr_len: i32) -> i32 { + const MOD: i32 = 1_000_000_007; + let max_pos = (steps / 2).min(arr_len - 1) as usize; + let mut dp = vec![0; max_pos + 1]; + dp[0] = 1; + for _ in 0..steps { + let mut new_dp = vec![0; max_pos + 1]; + for pos in 0..=max_pos { + if dp[pos] == 0 { + continue; + } + new_dp[pos] = (new_dp[pos] + dp[pos]) % MOD; + if pos > 0 { + new_dp[pos - 1] = (new_dp[pos - 1] + dp[pos]) % MOD; + } + if pos < max_pos { + new_dp[pos + 1] = (new_dp[pos + 1] + dp[pos]) % MOD; + } + } + dp = new_dp; + } + dp[0] + } +} diff --git a/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.swift b/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.swift new file mode 100644 index 00000000..e3aa3036 --- /dev/null +++ b/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.swift @@ -0,0 +1,19 @@ +class Solution { + func numWays(_ steps: Int, _ arrLen: Int) -> Int { + let MOD = 1000000007 + let maxPos = min(steps / 2, arrLen - 1) + var dp = [Int](repeating: 0, count: maxPos + 1) + dp[0] = 1 + for _ in 0.. 0 { newDp[pos - 1] = (newDp[pos - 1] + dp[pos]) % MOD } + if pos < maxPos { newDp[pos + 1] = (newDp[pos + 1] + dp[pos]) % MOD } + } + dp = newDp + } + return dp[0] + } +} diff --git a/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.ts b/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.ts new file mode 100644 index 00000000..f8c608d5 --- /dev/null +++ b/tests/1001-1500/1269. number-of-ways-to-stay-in-the-same-place-after-some-steps/sol.ts @@ -0,0 +1,17 @@ +function numWays(steps: number, arrLen: number): number { + const MOD = 1000000007; + const maxPos = Math.min(Math.floor(steps / 2), arrLen - 1); + let dp: number[] = new Array(maxPos + 1).fill(0); + dp[0] = 1; + for (let step = 0; step < steps; step++) { + const newDp: number[] = new Array(maxPos + 1).fill(0); + for (let pos = 0; pos <= maxPos; pos++) { + if (dp[pos] === 0) continue; + newDp[pos] = (newDp[pos] + dp[pos]) % MOD; + if (pos > 0) newDp[pos - 1] = (newDp[pos - 1] + dp[pos]) % MOD; + if (pos < maxPos) newDp[pos + 1] = (newDp[pos + 1] + dp[pos]) % MOD; + } + dp = newDp; + } + return dp[0]; +} diff --git a/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/manifest.yaml b/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/manifest.yaml new file mode 100644 index 00000000..18017fbf --- /dev/null +++ b/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/manifest.yaml @@ -0,0 +1,473 @@ +entry: + id: 1275 + title: find-winner-on-a-tic-tac-toe-game + params: + moves: + type: array + items: + type: array + items: + type: int + call: + python3: "Solution().tictactoe({moves})" + python2: "Solution().tictactoe({moves})" + ruby: "tictactoe({moves})" + java: "new Solution().tictactoe({moves})" + csharp: "new Solution().Tictactoe({moves})" + kotlin: "Solution().tictactoe({moves})" + go: "tictactoe({moves})" + dart: "Solution().tictactoe({moves})" + swift: "Solution().tictactoe({moves})" + typescript: "tictactoe({moves})" + rust: "Solution::tictactoe({moves})" + cpp: "Solution().tictactoe({moves})" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().tictactoe(moves, {result})" + checker: | + class Checker: + def tictactoe(self, moves, result): + if not isinstance(result, str) or not (1 <= len(moves) <= 9): + return False + + board = [[None] * 3 for _ in range(3)] + lines = [ + ((0, 0), (0, 1), (0, 2)), + ((1, 0), (1, 1), (1, 2)), + ((2, 0), (2, 1), (2, 2)), + ((0, 0), (1, 0), (2, 0)), + ((0, 1), (1, 1), (2, 1)), + ((0, 2), (1, 2), (2, 2)), + ((0, 0), (1, 1), (2, 2)), + ((0, 2), (1, 1), (2, 0)), + ] + + for turn, move in enumerate(moves): + if not isinstance(move, list) or len(move) != 2: + return False + row, col = move + if not isinstance(row, int) or not isinstance(col, int): + return False + if not (0 <= row < 3 and 0 <= col < 3) or board[row][col] is not None: + return False + player = "A" if turn % 2 == 0 else "B" + board[row][col] = player + for line in lines: + if all(board[r][c] == player for r, c in line): + return turn == len(moves) - 1 and result == player + + return result == ("Draw" if len(moves) == 9 else "Pending") +seed: 1275 +tests: + - name: pending-one + in: + moves: + - [0, 0] + out: "Pending" + - name: pending-two + in: + moves: + - [0, 0] + - [1, 1] + out: "Pending" + - name: pending-four + in: + moves: + - [0, 0] + - [1, 1] + - [0, 1] + - [2, 2] + out: "Pending" + - name: a-top-row-at-seven + in: + moves: + - [0, 0] + - [1, 1] + - [0, 1] + - [2, 2] + - [1, 0] + - [2, 0] + - [0, 2] + out: "A" + - name: b-middle-column-at-six + in: + moves: + - [0, 0] + - [1, 1] + - [2, 2] + - [0, 1] + - [1, 0] + - [2, 1] + out: "B" + - name: a-top-row + in: + moves: + - [0, 0] + - [1, 0] + - [0, 1] + - [1, 1] + - [0, 2] + out: "A" + - name: a-middle-row + in: + moves: + - [1, 0] + - [0, 0] + - [1, 1] + - [0, 1] + - [1, 2] + out: "A" + - name: a-bottom-row + in: + moves: + - [2, 0] + - [0, 0] + - [2, 1] + - [0, 1] + - [2, 2] + out: "A" + - name: a-left-column + in: + moves: + - [0, 0] + - [0, 1] + - [1, 0] + - [1, 1] + - [2, 0] + out: "A" + - name: a-middle-column + in: + moves: + - [0, 1] + - [0, 0] + - [1, 1] + - [0, 2] + - [2, 1] + out: "A" + - name: a-right-column + in: + moves: + - [0, 2] + - [0, 0] + - [1, 2] + - [0, 1] + - [2, 2] + out: "A" + - name: a-main-diagonal + in: + moves: + - [0, 0] + - [0, 1] + - [1, 1] + - [0, 2] + - [2, 2] + out: "A" + - name: a-anti-diagonal + in: + moves: + - [0, 2] + - [0, 0] + - [1, 1] + - [0, 1] + - [2, 0] + out: "A" + - name: b-top-row + in: + moves: + - [1, 0] + - [0, 0] + - [2, 2] + - [0, 1] + - [1, 1] + - [0, 2] + out: "B" + - name: b-middle-row + in: + moves: + - [0, 0] + - [1, 0] + - [0, 1] + - [1, 1] + - [2, 2] + - [1, 2] + out: "B" + - name: b-bottom-row + in: + moves: + - [0, 0] + - [2, 0] + - [0, 1] + - [2, 1] + - [1, 2] + - [2, 2] + out: "B" + - name: b-left-column + in: + moves: + - [0, 2] + - [0, 0] + - [1, 1] + - [1, 0] + - [1, 2] + - [2, 0] + out: "B" + - name: b-middle-column + in: + moves: + - [0, 0] + - [0, 1] + - [1, 0] + - [1, 1] + - [2, 2] + - [2, 1] + out: "B" + - name: b-right-column + in: + moves: + - [0, 0] + - [0, 2] + - [1, 0] + - [1, 2] + - [2, 1] + - [2, 2] + out: "B" + - name: b-main-diagonal + in: + moves: + - [0, 1] + - [0, 0] + - [0, 2] + - [1, 1] + - [1, 2] + - [2, 2] + out: "B" + - name: b-anti-diagonal + in: + moves: + - [0, 0] + - [0, 2] + - [0, 1] + - [1, 1] + - [1, 2] + - [2, 0] + out: "B" + - name: draw-example + in: + moves: + - [0, 0] + - [1, 1] + - [2, 0] + - [1, 0] + - [1, 2] + - [2, 1] + - [0, 1] + - [0, 2] + - [2, 2] + out: "Draw" + - name: a-middle-row-on-final-move + in: + moves: + - [1, 1] + - [0, 0] + - [2, 2] + - [0, 2] + - [0, 1] + - [2, 1] + - [1, 0] + - [2, 0] + - [1, 2] + out: "A" + - name: draw-corners + in: + moves: + - [0, 0] + - [1, 0] + - [1, 1] + - [2, 1] + - [1, 2] + - [2, 2] + - [0, 1] + - [0, 2] + - [2, 0] + out: "Draw" + - name: a-right-column-on-final-move + in: + moves: + - [0, 1] + - [1, 1] + - [1, 0] + - [0, 0] + - [1, 2] + - [2, 0] + - [2, 2] + - [2, 1] + - [0, 2] + out: "A" + - name: draw-asymmetric + in: + moves: + - [0, 1] + - [2, 0] + - [2, 1] + - [1, 1] + - [1, 0] + - [0, 0] + - [0, 2] + - [1, 2] + - [2, 2] + out: "Draw" + - name: draw-alternate + in: + moves: + - [1, 0] + - [0, 0] + - [0, 2] + - [2, 0] + - [2, 1] + - [1, 1] + - [0, 1] + - [1, 2] + - [2, 2] + out: "Draw" + - name: pending-corner-center + in: + moves: + - [2, 2] + - [1, 1] + out: "Pending" + - name: pending-five + in: + moves: + - [0, 2] + - [1, 1] + - [2, 0] + - [0, 0] + - [1, 0] + out: "Pending" + - name: pending-seven + in: + moves: + - [0, 0] + - [1, 0] + - [1, 1] + - [2, 1] + - [1, 2] + - [2, 2] + - [0, 1] + out: "Pending" + - name: b-main-diagonal-at-eight + in: + moves: + - [0, 1] + - [2, 2] + - [1, 0] + - [0, 0] + - [1, 2] + - [2, 0] + - [2, 1] + - [1, 1] + out: "B" + - name: b-left-column-at-eight + in: + moves: + - [2, 1] + - [0, 0] + - [1, 1] + - [1, 0] + - [2, 2] + - [0, 2] + - [1, 2] + - [2, 0] + out: "B" + - name: a-row-with-center + in: + moves: + - [0, 1] + - [2, 2] + - [1, 1] + - [2, 0] + - [0, 0] + - [1, 0] + - [0, 2] + out: "A" + - name: pending-seven-mixed + in: + moves: + - [2, 1] + - [0, 0] + - [0, 1] + - [1, 1] + - [1, 0] + - [2, 0] + - [2, 2] + out: "Pending" + - name: a-diagonal-late + in: + moves: + - [0, 0] + - [1, 0] + - [2, 2] + - [0, 1] + - [1, 1] + out: "A" + - name: b-win-after-six + in: + moves: + - [2, 1] + - [0, 0] + - [0, 1] + - [1, 0] + - [2, 2] + - [2, 0] + out: "B" + - name: b-diagonal-with-center + in: + moves: + - [0, 1] + - [0, 2] + - [1, 0] + - [1, 1] + - [2, 1] + - [2, 0] + out: "B" + - name: b-column-varied + in: + moves: + - [1, 1] + - [0, 2] + - [0, 0] + - [1, 2] + - [2, 1] + - [2, 2] + out: "B" + - name: draw-last-move-center + in: + moves: + - [1, 1] + - [1, 2] + - [2, 1] + - [2, 0] + - [2, 2] + - [0, 0] + - [0, 2] + - [0, 1] + - [1, 0] + out: "Draw" + - name: draw-last-move-corner + in: + moves: + - [1, 2] + - [2, 2] + - [2, 1] + - [1, 0] + - [1, 1] + - [0, 1] + - [0, 2] + - [2, 0] + - [0, 0] + out: "Draw" diff --git a/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.cpp b/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.cpp new file mode 100644 index 00000000..a25cb75e --- /dev/null +++ b/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + string tictactoe(vector>& moves) { + vector> board(3, vector(3, "")); + bool isA = true; + for (auto& move : moves) { + int r = move[0], c = move[1]; + board[r][c] = isA ? "X" : "O"; + isA = !isA; + } + + for (int i = 0; i < 3; i++) { + if (!board[i][0].empty() && board[i][0] == board[i][1] && board[i][1] == board[i][2]) { + return board[i][0] == "X" ? "A" : "B"; + } + if (!board[0][i].empty() && board[0][i] == board[1][i] && board[1][i] == board[2][i]) { + return board[0][i] == "X" ? "A" : "B"; + } + } + + if (!board[1][1].empty() && ((board[0][0] == board[1][1] && board[1][1] == board[2][2]) || (board[0][2] == board[1][1] && board[1][1] == board[2][0]))) { + return board[1][1] == "X" ? "A" : "B"; + } + + return moves.size() == 9 ? "Draw" : "Pending"; + } +}; diff --git a/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.cs b/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.cs new file mode 100644 index 00000000..b07473e4 --- /dev/null +++ b/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.cs @@ -0,0 +1,32 @@ +public class Solution { + public string Tictactoe(int[][] moves) { + string[][] board = new string[3][]; + for (int i = 0; i < 3; i++) { + board[i] = new string[3]; + for (int j = 0; j < 3; j++) { + board[i][j] = ""; + } + } + bool isA = true; + foreach (var move in moves) { + int r = move[0], c = move[1]; + board[r][c] = isA ? "X" : "O"; + isA = !isA; + } + + for (int i = 0; i < 3; i++) { + if (!string.IsNullOrEmpty(board[i][0]) && board[i][0] == board[i][1] && board[i][1] == board[i][2]) { + return board[i][0] == "X" ? "A" : "B"; + } + if (!string.IsNullOrEmpty(board[0][i]) && board[0][i] == board[1][i] && board[1][i] == board[2][i]) { + return board[0][i] == "X" ? "A" : "B"; + } + } + + if (!string.IsNullOrEmpty(board[1][1]) && ((board[0][0] == board[1][1] && board[1][1] == board[2][2]) || (board[0][2] == board[1][1] && board[1][1] == board[2][0]))) { + return board[1][1] == "X" ? "A" : "B"; + } + + return moves.Length == 9 ? "Draw" : "Pending"; + } +} diff --git a/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.dart b/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.dart new file mode 100644 index 00000000..2198704e --- /dev/null +++ b/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.dart @@ -0,0 +1,26 @@ +class Solution { + String tictactoe(List> moves) { + List> board = List.generate(3, (_) => List.filled(3, "")); + bool isA = true; + for (var move in moves) { + int r = move[0], c = move[1]; + board[r][c] = isA ? "X" : "O"; + isA = !isA; + } + + for (int i = 0; i < 3; i++) { + if (board[i][0].isNotEmpty && board[i][0] == board[i][1] && board[i][1] == board[i][2]) { + return board[i][0] == "X" ? "A" : "B"; + } + if (board[0][i].isNotEmpty && board[0][i] == board[1][i] && board[1][i] == board[2][i]) { + return board[0][i] == "X" ? "A" : "B"; + } + } + + if (board[1][1].isNotEmpty && ((board[0][0] == board[1][1] && board[1][1] == board[2][2]) || (board[0][2] == board[1][1] && board[1][1] == board[2][0]))) { + return board[1][1] == "X" ? "A" : "B"; + } + + return moves.length == 9 ? "Draw" : "Pending"; + } +} diff --git a/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.go b/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.go new file mode 100644 index 00000000..6684165c --- /dev/null +++ b/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.go @@ -0,0 +1,47 @@ +func tictactoe(moves [][]int) string { + board := make([][]string, 3) + for i := range board { + board[i] = make([]string, 3) + for j := range board[i] { + board[i][j] = "" + } + } + + isA := true + for _, move := range moves { + r, c := move[0], move[1] + if isA { + board[r][c] = "X" + } else { + board[r][c] = "O" + } + isA = !isA + } + + for i := 0; i < 3; i++ { + if board[i][0] != "" && board[i][0] == board[i][1] && board[i][1] == board[i][2] { + if board[i][0] == "X" { + return "A" + } + return "B" + } + if board[0][i] != "" && board[0][i] == board[1][i] && board[1][i] == board[2][i] { + if board[0][i] == "X" { + return "A" + } + return "B" + } + } + + if board[1][1] != "" && ((board[0][0] == board[1][1] && board[1][1] == board[2][2]) || (board[0][2] == board[1][1] && board[1][1] == board[2][0])) { + if board[1][1] == "X" { + return "A" + } + return "B" + } + + if len(moves) == 9 { + return "Draw" + } + return "Pending" +} diff --git a/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.java b/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.java new file mode 100644 index 00000000..87d8612d --- /dev/null +++ b/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.java @@ -0,0 +1,31 @@ +class Solution { + public String tictactoe(int[][] moves) { + String[][] board = new String[3][3]; + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + board[i][j] = ""; + } + } + boolean isA = true; + for (int[] move : moves) { + int r = move[0], c = move[1]; + board[r][c] = isA ? "X" : "O"; + isA = !isA; + } + + for (int i = 0; i < 3; i++) { + if (!board[i][0].isEmpty() && board[i][0].equals(board[i][1]) && board[i][1].equals(board[i][2])) { + return board[i][0].equals("X") ? "A" : "B"; + } + if (!board[0][i].isEmpty() && board[0][i].equals(board[1][i]) && board[1][i].equals(board[2][i])) { + return board[0][i].equals("X") ? "A" : "B"; + } + } + + if (!board[1][1].isEmpty() && ((board[0][0].equals(board[1][1]) && board[1][1].equals(board[2][2])) || (board[0][2].equals(board[1][1]) && board[1][1].equals(board[2][0])))) { + return board[1][1].equals("X") ? "A" : "B"; + } + + return moves.length == 9 ? "Draw" : "Pending"; + } +} diff --git a/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.kt b/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.kt new file mode 100644 index 00000000..3932159a --- /dev/null +++ b/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.kt @@ -0,0 +1,27 @@ +class Solution { + fun tictactoe(moves: Array): String { + val board = Array(3) { Array(3) { "" } } + var isA = true + for (move in moves) { + val r = move[0] + val c = move[1] + board[r][c] = if (isA) "X" else "O" + isA = !isA + } + + for (i in 0..2) { + if (board[i][0].isNotEmpty() && board[i][0] == board[i][1] && board[i][1] == board[i][2]) { + return if (board[i][0] == "X") "A" else "B" + } + if (board[0][i].isNotEmpty() && board[0][i] == board[1][i] && board[1][i] == board[2][i]) { + return if (board[0][i] == "X") "A" else "B" + } + } + + if (board[1][1].isNotEmpty() && ((board[0][0] == board[1][1] && board[1][1] == board[2][2]) || (board[0][2] == board[1][1] && board[1][1] == board[2][0]))) { + return if (board[1][1] == "X") "A" else "B" + } + + return if (moves.size == 9) "Draw" else "Pending" + } +} diff --git a/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.py b/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.py new file mode 100644 index 00000000..eeaa31bf --- /dev/null +++ b/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.py @@ -0,0 +1,25 @@ +class Solution: + def tictactoe(self, moves: List[List[int]]) -> str: + board = [[""] * 3 for _ in range(3)] + + # Fill board + is_A = True + for r, c in moves: + board[r][c] = "X" if is_A else "O" + is_A = not is_A + + # Check rows and columns + for i in range(3): + if board[i][0] and board[i][0] == board[i][1] == board[i][2]: + return "A" if board[i][0] == "X" else "B" + if board[0][i] and board[0][i] == board[1][i] == board[2][i]: + return "A" if board[0][i] == "X" else "B" + + # Check diagonals + if board[1][1] and ( + (board[0][0] == board[1][1] == board[2][2]) + or (board[0][2] == board[1][1] == board[2][0]) + ): + return "A" if board[1][1] == "X" else "B" + + return "Draw" if len(moves) == 9 else "Pending" diff --git a/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.py2 b/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.py2 new file mode 100644 index 00000000..60eab4b1 --- /dev/null +++ b/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.py2 @@ -0,0 +1,22 @@ +class Solution(object): + def tictactoe(self, moves): + """ + :type moves: List[List[int]] + :rtype: str + """ + board = [[""] * 3 for _ in range(3)] + is_A = True + for r, c in moves: + board[r][c] = "X" if is_A else "O" + is_A = not is_A + + for i in range(3): + if board[i][0] and board[i][0] == board[i][1] == board[i][2]: + return "A" if board[i][0] == "X" else "B" + if board[0][i] and board[0][i] == board[1][i] == board[2][i]: + return "A" if board[0][i] == "X" else "B" + + if board[1][1] and ((board[0][0] == board[1][1] == board[2][2]) or (board[0][2] == board[1][1] == board[2][0])): + return "A" if board[1][1] == "X" else "B" + + return "Draw" if len(moves) == 9 else "Pending" diff --git a/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.rb b/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.rb new file mode 100644 index 00000000..467e93d3 --- /dev/null +++ b/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.rb @@ -0,0 +1,25 @@ +# @param {Integer[][]} moves +# @return {String} +def tictactoe(moves) + board = Array.new(3) { Array.new(3, "") } + is_a = true + moves.each do |r, c| + board[r][c] = is_a ? "X" : "O" + is_a = !is_a + end + + (0..2).each do |i| + if board[i][0] != "" && board[i][0] == board[i][1] && board[i][1] == board[i][2] + return board[i][0] == "X" ? "A" : "B" + end + if board[0][i] != "" && board[0][i] == board[1][i] && board[1][i] == board[2][i] + return board[0][i] == "X" ? "A" : "B" + end + end + + if board[1][1] != "" && ((board[0][0] == board[1][1] && board[1][1] == board[2][2]) || (board[0][2] == board[1][1] && board[1][1] == board[2][0])) + return board[1][1] == "X" ? "A" : "B" + end + + moves.length == 9 ? "Draw" : "Pending" +end diff --git a/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.rs b/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.rs new file mode 100644 index 00000000..ebc3fafe --- /dev/null +++ b/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.rs @@ -0,0 +1,27 @@ +impl Solution { + pub fn tictactoe(moves: Vec>) -> String { + let mut board = vec![vec![String::new(); 3]; 3]; + let mut is_a = true; + for mv in &moves { + let r = mv[0] as usize; + let c = mv[1] as usize; + board[r][c] = if is_a { "X".to_string() } else { "O".to_string() }; + is_a = !is_a; + } + + for i in 0..3 { + if !board[i][0].is_empty() && board[i][0] == board[i][1] && board[i][1] == board[i][2] { + return if board[i][0] == "X" { "A".to_string() } else { "B".to_string() }; + } + if !board[0][i].is_empty() && board[0][i] == board[1][i] && board[1][i] == board[2][i] { + return if board[0][i] == "X" { "A".to_string() } else { "B".to_string() }; + } + } + + if !board[1][1].is_empty() && ((board[0][0] == board[1][1] && board[1][1] == board[2][2]) || (board[0][2] == board[1][1] && board[1][1] == board[2][0])) { + return if board[1][1] == "X" { "A".to_string() } else { "B".to_string() }; + } + + if moves.len() == 9 { "Draw".to_string() } else { "Pending".to_string() } + } +} diff --git a/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.swift b/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.swift new file mode 100644 index 00000000..95e7df6a --- /dev/null +++ b/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.swift @@ -0,0 +1,26 @@ +class Solution { + func tictactoe(_ moves: [[Int]]) -> String { + var board = Array(repeating: Array(repeating: "", count: 3), count: 3) + var isA = true + for move in moves { + let r = move[0], c = move[1] + board[r][c] = isA ? "X" : "O" + isA.toggle() + } + + for i in 0..<3 { + if !board[i][0].isEmpty && board[i][0] == board[i][1] && board[i][1] == board[i][2] { + return board[i][0] == "X" ? "A" : "B" + } + if !board[0][i].isEmpty && board[0][i] == board[1][i] && board[1][i] == board[2][i] { + return board[0][i] == "X" ? "A" : "B" + } + } + + if !board[1][1].isEmpty && ((board[0][0] == board[1][1] && board[1][1] == board[2][2]) || (board[0][2] == board[1][1] && board[1][1] == board[2][0])) { + return board[1][1] == "X" ? "A" : "B" + } + + return moves.count == 9 ? "Draw" : "Pending" + } +} diff --git a/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.ts b/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.ts new file mode 100644 index 00000000..79745dbf --- /dev/null +++ b/tests/1001-1500/1275. find-winner-on-a-tic-tac-toe-game/sol.ts @@ -0,0 +1,35 @@ +function tictactoe(moves: number[][]): string { + const board: string[][] = Array.from({ length: 3 }, () => Array(3).fill("")); + let isA = true; + for (const [r, c] of moves) { + board[r][c] = isA ? "X" : "O"; + isA = !isA; + } + + for (let i = 0; i < 3; i++) { + if ( + board[i][0] && + board[i][0] === board[i][1] && + board[i][1] === board[i][2] + ) { + return board[i][0] === "X" ? "A" : "B"; + } + if ( + board[0][i] && + board[0][i] === board[1][i] && + board[1][i] === board[2][i] + ) { + return board[0][i] === "X" ? "A" : "B"; + } + } + + if ( + board[1][1] && + ((board[0][0] === board[1][1] && board[1][1] === board[2][2]) || + (board[0][2] === board[1][1] && board[1][1] === board[2][0])) + ) { + return board[1][1] === "X" ? "A" : "B"; + } + + return moves.length === 9 ? "Draw" : "Pending"; +} diff --git a/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/manifest.yaml b/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/manifest.yaml new file mode 100644 index 00000000..bb26824e --- /dev/null +++ b/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/manifest.yaml @@ -0,0 +1,279 @@ +entry: + id: 1276 + title: number-of-burgers-with-no-waste-of-ingredients + params: + tomatoSlices: + type: int + cheeseSlices: + type: int + call: + cpp: "Solution().numOfBurgers({tomatoSlices}, {cheeseSlices})" + rust: "Solution::num_of_burgers({tomatoSlices}, {cheeseSlices})" + python3: "Solution().numOfBurgers({tomatoSlices}, {cheeseSlices})" + python2: "Solution().numOfBurgers({tomatoSlices}, {cheeseSlices})" + ruby: "num_of_burgers({tomatoSlices}, {cheeseSlices})" + java: "new Solution().numOfBurgers({tomatoSlices}, {cheeseSlices})" + csharp: "new Solution().NumOfBurgers({tomatoSlices}, {cheeseSlices})" + kotlin: "Solution().numOfBurgers({tomatoSlices}, {cheeseSlices})" + go: "numOfBurgers({tomatoSlices}, {cheeseSlices})" + dart: "Solution().numOfBurgers({tomatoSlices}, {cheeseSlices})" + swift: "Solution().numOfBurgers({tomatoSlices}, {cheeseSlices})" + typescript: "numOfBurgers({tomatoSlices}, {cheeseSlices})" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().numOfBurgers(tomatoSlices, cheeseSlices, {result})" + checker: | + class Checker: + def numOfBurgers(self, tomatoSlices, cheeseSlices, result): + if not isinstance(result, list): + return False + feasible = ( + tomatoSlices % 2 == 0 + and 2 * cheeseSlices <= tomatoSlices <= 4 * cheeseSlices + ) + if not feasible: + return result == [] + if len(result) != 2 or not all(isinstance(x, int) and x >= 0 for x in result): + return False + jumbo, small = result + return ( + jumbo + small == cheeseSlices + and 4 * jumbo + 2 * small == tomatoSlices + ) +seed: 1276 +tests: + - name: zero-ingredients + in: + tomatoSlices: 0 + cheeseSlices: 0 + out: [0, 0] + - name: example-mixed + in: + tomatoSlices: 16 + cheeseSlices: 7 + out: [1, 6] + - name: example-odd-tomato + in: + tomatoSlices: 17 + cheeseSlices: 4 + out: [] + - name: example-too-little-tomato + in: + tomatoSlices: 4 + cheeseSlices: 17 + out: [] + - name: one-small + in: + tomatoSlices: 2 + cheeseSlices: 1 + out: [0, 1] + - name: one-jumbo + in: + tomatoSlices: 4 + cheeseSlices: 1 + out: [1, 0] + - name: one-of-each + in: + tomatoSlices: 6 + cheeseSlices: 2 + out: [1, 1] + - name: generated-large-full-range + seed: 127601 + in: + tomatoSlices: + gen: "int" + min: 0 + max: 10000000 + cheeseSlices: + gen: "int" + min: 0 + max: 10000000 + - name: generated-large-high-tomato + seed: 127602 + in: + tomatoSlices: + gen: "int" + min: 9000000 + max: 10000000 + cheeseSlices: + gen: "int" + min: 2250000 + max: 5000000 + - name: generated-large-low-cheese + seed: 127603 + in: + tomatoSlices: + gen: "int" + min: 8000000 + max: 10000000 + cheeseSlices: + gen: "int" + min: 0 + max: 3000000 + - name: generated-large-high-cheese + seed: 127604 + in: + tomatoSlices: + gen: "int" + min: 0 + max: 10000000 + cheeseSlices: + gen: "int" + min: 4000000 + max: 5000000 + - name: generated-large-boundary-band + seed: 127605 + in: + tomatoSlices: + gen: "int" + min: 9999990 + max: 10000000 + cheeseSlices: + gen: "int" + min: 2499990 + max: 5000000 + - name: equal-mix + in: + tomatoSlices: 30 + cheeseSlices: 10 + out: [5, 5] + - name: three-jumbo-two-small + in: + tomatoSlices: 16 + cheeseSlices: 5 + out: [3, 2] + - name: two-jumbo-five-small + in: + tomatoSlices: 18 + cheeseSlices: 7 + out: [2, 5] + - name: odd-minimum-range + in: + tomatoSlices: 3 + cheeseSlices: 1 + out: [] + - name: odd-maximum-range + in: + tomatoSlices: 19 + cheeseSlices: 5 + out: [] + - name: odd-outside-low + in: + tomatoSlices: 1 + cheeseSlices: 3 + out: [] + - name: odd-outside-high + in: + tomatoSlices: 21 + cheeseSlices: 5 + out: [] + - name: zero-tomato-positive-cheese + in: + tomatoSlices: 0 + cheeseSlices: 1 + out: [] + - name: positive-tomato-zero-cheese + in: + tomatoSlices: 2 + cheeseSlices: 0 + out: [] + - name: below-two-per-cheese + in: + tomatoSlices: 18 + cheeseSlices: 10 + out: [] + - name: above-four-per-cheese + in: + tomatoSlices: 42 + cheeseSlices: 10 + out: [] + - name: just-below-minimum + in: + tomatoSlices: 198 + cheeseSlices: 100 + out: [] + - name: just-above-maximum + in: + tomatoSlices: 402 + cheeseSlices: 100 + out: [] + - name: medium-all-small + in: + tomatoSlices: 200 + cheeseSlices: 100 + out: [0, 100] + - name: medium-all-jumbo + in: + tomatoSlices: 400 + cheeseSlices: 100 + out: [100, 0] + - name: medium-asymmetric + in: + tomatoSlices: 246 + cheeseSlices: 100 + out: [23, 77] + - name: medium-near-jumbo + in: + tomatoSlices: 394 + cheeseSlices: 100 + out: [97, 3] + - name: large-all-small-limit + in: + tomatoSlices: 10000000 + cheeseSlices: 5000000 + out: [0, 5000000] + - name: large-all-jumbo-limit + in: + tomatoSlices: 10000000 + cheeseSlices: 2500000 + out: [2500000, 0] + - name: large-near-upper-limit + in: + tomatoSlices: 9999998 + cheeseSlices: 2500000 + out: [2499999, 1] + - name: large-near-lower-limit + in: + tomatoSlices: 9999998 + cheeseSlices: 4999999 + out: [0, 4999999] + - name: large-balanced + in: + tomatoSlices: 6000000 + cheeseSlices: 2000000 + out: [1000000, 1000000] + - name: large-asymmetric + in: + tomatoSlices: 7654322 + cheeseSlices: 2500000 + out: [1327161, 1172839] + - name: maximum-odd-tomato + in: + tomatoSlices: 9999999 + cheeseSlices: 2500000 + out: [] + - name: maximum-even-too-few-cheese + in: + tomatoSlices: 10000000 + cheeseSlices: 2499999 + out: [] + - name: maximum-even-too-many-cheese + in: + tomatoSlices: 10000000 + cheeseSlices: 5000001 + out: [] + - name: small-even-below-range + in: + tomatoSlices: 12 + cheeseSlices: 7 + out: [] + - name: small-even-above-range + in: + tomatoSlices: 30 + cheeseSlices: 7 + out: [] diff --git a/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.cpp b/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.cpp new file mode 100644 index 00000000..68432025 --- /dev/null +++ b/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + vector numOfBurgers(int tomatoSlices, int cheeseSlices) { + if ((tomatoSlices - 2 * cheeseSlices) % 2 != 0) { + return {}; + } + + int x = (tomatoSlices - 2 * cheeseSlices) / 2; + int y = cheeseSlices - x; + + if (x < 0 || y < 0) { + return {}; + } + + return {x, y}; + } +}; diff --git a/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.cs b/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.cs new file mode 100644 index 00000000..54e5fefe --- /dev/null +++ b/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.cs @@ -0,0 +1,16 @@ +public class Solution { + public IList NumOfBurgers(int tomatoSlices, int cheeseSlices) { + if ((tomatoSlices - 2 * cheeseSlices) % 2 != 0) { + return new List(); + } + + int x = (tomatoSlices - 2 * cheeseSlices) / 2; + int y = cheeseSlices - x; + + if (x < 0 || y < 0) { + return new List(); + } + + return new List { x, y }; + } +} diff --git a/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.dart b/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.dart new file mode 100644 index 00000000..53f48e01 --- /dev/null +++ b/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.dart @@ -0,0 +1,16 @@ +class Solution { + List numOfBurgers(int tomatoSlices, int cheeseSlices) { + if ((tomatoSlices - 2 * cheeseSlices) % 2 != 0) { + return []; + } + + int x = (tomatoSlices - 2 * cheeseSlices) ~/ 2; + int y = cheeseSlices - x; + + if (x < 0 || y < 0) { + return []; + } + + return [x, y]; + } +} diff --git a/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.go b/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.go new file mode 100644 index 00000000..341ae75d --- /dev/null +++ b/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.go @@ -0,0 +1,14 @@ +func numOfBurgers(tomatoSlices int, cheeseSlices int) []int { + if (tomatoSlices - 2 * cheeseSlices) % 2 != 0 { + return []int{} + } + + x := (tomatoSlices - 2 * cheeseSlices) / 2 + y := cheeseSlices - x + + if x < 0 || y < 0 { + return []int{} + } + + return []int{x, y} +} diff --git a/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.java b/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.java new file mode 100644 index 00000000..64adb82b --- /dev/null +++ b/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.java @@ -0,0 +1,19 @@ +class Solution { + public List numOfBurgers(int tomatoSlices, int cheeseSlices) { + if ((tomatoSlices - 2 * cheeseSlices) % 2 != 0) { + return new ArrayList<>(); + } + + int x = (tomatoSlices - 2 * cheeseSlices) / 2; + int y = cheeseSlices - x; + + if (x < 0 || y < 0) { + return new ArrayList<>(); + } + + List result = new ArrayList<>(); + result.add(x); + result.add(y); + return result; + } +} diff --git a/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.kt b/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.kt new file mode 100644 index 00000000..50ef2ecf --- /dev/null +++ b/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun numOfBurgers(tomatoSlices: Int, cheeseSlices: Int): List { + if ((tomatoSlices - 2 * cheeseSlices) % 2 != 0) { + return emptyList() + } + + val x = (tomatoSlices - 2 * cheeseSlices) / 2 + val y = cheeseSlices - x + + if (x < 0 || y < 0) { + return emptyList() + } + + return listOf(x, y) + } +} diff --git a/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.py b/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.py new file mode 100644 index 00000000..3694a141 --- /dev/null +++ b/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.py @@ -0,0 +1,17 @@ +class Solution(object): + def numOfBurgers(self, tomatoSlices, cheeseSlices): + """ + :type tomatoSlices: int + :type cheeseSlices: int + :rtype: List[int] + """ + if (tomatoSlices - 2 * cheeseSlices) % 2 != 0: + return [] + + x = (tomatoSlices - 2 * cheeseSlices) // 2 + y = cheeseSlices - x + + if x < 0 or y < 0: + return [] + + return [x, y] diff --git a/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.py2 b/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.py2 new file mode 100644 index 00000000..3694a141 --- /dev/null +++ b/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.py2 @@ -0,0 +1,17 @@ +class Solution(object): + def numOfBurgers(self, tomatoSlices, cheeseSlices): + """ + :type tomatoSlices: int + :type cheeseSlices: int + :rtype: List[int] + """ + if (tomatoSlices - 2 * cheeseSlices) % 2 != 0: + return [] + + x = (tomatoSlices - 2 * cheeseSlices) // 2 + y = cheeseSlices - x + + if x < 0 or y < 0: + return [] + + return [x, y] diff --git a/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.rb b/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.rb new file mode 100644 index 00000000..52f98110 --- /dev/null +++ b/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.rb @@ -0,0 +1,17 @@ +# @param {Integer} tomato_slices +# @param {Integer} cheese_slices +# @return {Integer[]} +def num_of_burgers(tomato_slices, cheese_slices) + if (tomato_slices - 2 * cheese_slices) % 2 != 0 + return [] + end + + x = (tomato_slices - 2 * cheese_slices) / 2 + y = cheese_slices - x + + if x < 0 || y < 0 + return [] + end + + return [x, y] +end diff --git a/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.rs b/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.rs new file mode 100644 index 00000000..09749d0a --- /dev/null +++ b/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn num_of_burgers(tomato_slices: i32, cheese_slices: i32) -> Vec { + if (tomato_slices - 2 * cheese_slices) % 2 != 0 { + return vec![]; + } + + let x = (tomato_slices - 2 * cheese_slices) / 2; + let y = cheese_slices - x; + + if x < 0 || y < 0 { + return vec![]; + } + + vec![x, y] + } +} diff --git a/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.swift b/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.swift new file mode 100644 index 00000000..d40bb451 --- /dev/null +++ b/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.swift @@ -0,0 +1,16 @@ +class Solution { + func numOfBurgers(_ tomatoSlices: Int, _ cheeseSlices: Int) -> [Int] { + if (tomatoSlices - 2 * cheeseSlices) % 2 != 0 { + return [] + } + + let x = (tomatoSlices - 2 * cheeseSlices) / 2 + let y = cheeseSlices - x + + if x < 0 || y < 0 { + return [] + } + + return [x, y] + } +} diff --git a/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.ts b/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.ts new file mode 100644 index 00000000..64a3f417 --- /dev/null +++ b/tests/1001-1500/1276. number-of-burgers-with-no-waste-of-ingredients/sol.ts @@ -0,0 +1,14 @@ +function numOfBurgers(tomatoSlices: number, cheeseSlices: number): number[] { + if ((tomatoSlices - 2 * cheeseSlices) % 2 !== 0) { + return []; + } + + const x = (tomatoSlices - 2 * cheeseSlices) / 2; + const y = cheeseSlices - x; + + if (x < 0 || y < 0) { + return []; + } + + return [x, y]; +} diff --git a/tests/1001-1500/1277. count-square-submatrices-with-all-ones/manifest.yaml b/tests/1001-1500/1277. count-square-submatrices-with-all-ones/manifest.yaml new file mode 100644 index 00000000..b71b7ca6 --- /dev/null +++ b/tests/1001-1500/1277. count-square-submatrices-with-all-ones/manifest.yaml @@ -0,0 +1,399 @@ +entry: + id: 1277 + title: "count-square-submatrices-with-all-ones" + params: + matrix: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().countSquares({matrix})" + rust: "Solution::count_squares({matrix})" + python3: "Solution().countSquares({matrix})" + python2: "Solution().countSquares({matrix})" + ruby: "count_squares({matrix})" + java: "new Solution().countSquares({matrix})" + csharp: "new Solution().CountSquares({matrix})" + kotlin: "Solution().countSquares({matrix})" + go: "countSquares({matrix})" + dart: "Solution().countSquares({matrix})" + swift: "Solution().countSquares({matrix})" + typescript: "countSquares({matrix})" +judge: + type: "exact" +limits: + time_ms: 500 + memory_mb: 300 +oracle: + python3: + call: "Checker().countSquares(matrix, {result})" + checker: | + class Checker: + def countSquares(self, matrix, result): + rows = len(matrix) + cols = len(matrix[0]) if rows else 0 + total = 0 + previous = [0] * (cols + 1) + for row in range(rows): + current = [0] * (cols + 1) + for col in range(1, cols + 1): + if matrix[row][col - 1] == 1: + current[col] = min( + previous[col], current[col - 1], previous[col - 1] + ) + 1 + total += current[col] + previous = current + return result == total +seed: 1277 +tests: + - name: "example_one" + in: + matrix: + - [0, 1, 1, 1] + - [1, 1, 1, 1] + - [0, 1, 1, 1] + out: 15 + - name: "example_two" + in: + matrix: + - [1, 0, 1] + - [1, 1, 0] + - [1, 1, 0] + out: 7 + - name: "single_zero" + in: + matrix: + - [0] + out: 0 + - name: "single_one" + in: + matrix: + - [1] + out: 1 + - name: "zero_row" + in: + matrix: + - [0, 0, 0, 0, 0] + out: 0 + - name: "mixed_row" + in: + matrix: + - [1, 0, 1, 1, 0, 1] + out: 4 + - name: "mixed_column" + in: + matrix: + - [1] + - [0] + - [1] + - [1] + - [0] + - [1] + out: 4 + - name: "full_two_by_two" + in: + matrix: + - [1, 1] + - [1, 1] + out: 5 + - name: "full_three_by_three" + in: + matrix: + - [1, 1, 1] + - [1, 1, 1] + - [1, 1, 1] + out: 14 + - name: "full_four_by_four" + in: + matrix: + - [1, 1, 1, 1] + - [1, 1, 1, 1] + - [1, 1, 1, 1] + - [1, 1, 1, 1] + out: 30 + - name: "checkerboard" + in: + matrix: + - [1, 0, 1, 0] + - [0, 1, 0, 1] + - [1, 0, 1, 0] + - [0, 1, 0, 1] + out: 8 + - name: "full_three_by_four" + in: + matrix: + - [1, 1, 1, 1] + - [1, 1, 1, 1] + - [1, 1, 1, 1] + out: 20 + - name: "full_two_by_three" + in: + matrix: + - [1, 1, 1] + - [1, 1, 1] + out: 8 + - name: "two_rows_with_gap" + in: + matrix: + - [1, 1, 0, 1] + - [1, 1, 1, 1] + out: 8 + - name: "isolated_cross" + in: + matrix: + - [0, 1, 0] + - [1, 1, 1] + - [0, 1, 0] + out: 5 + - name: "hollow_three_by_three" + in: + matrix: + - [1, 1, 1] + - [1, 0, 1] + - [1, 1, 1] + out: 8 + - name: "bottom_left_l_shape" + in: + matrix: + - [1, 0, 0] + - [1, 0, 0] + - [1, 1, 1] + out: 5 + - name: "embedded_three_by_three" + in: + matrix: + - [0, 0, 0, 0, 0] + - [0, 1, 1, 1, 0] + - [0, 1, 1, 1, 0] + - [0, 1, 1, 1, 0] + - [0, 0, 0, 0, 0] + out: 14 + - name: "four_by_four_missing_corner" + in: + matrix: + - [1, 1, 1, 1] + - [1, 1, 1, 1] + - [1, 1, 1, 1] + - [1, 1, 1, 0] + out: 26 + - name: "upper_left_triangle" + in: + matrix: + - [1, 1, 1, 1] + - [1, 1, 1, 0] + - [1, 1, 0, 0] + - [1, 0, 0, 0] + out: 13 + - name: "diamond" + in: + matrix: + - [0, 0, 1, 0, 0] + - [0, 1, 1, 1, 0] + - [1, 1, 1, 1, 1] + - [0, 1, 1, 1, 0] + - [0, 0, 1, 0, 0] + out: 18 + - name: "full_five_by_five" + 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] + out: 55 + - name: "full_three_by_five" + in: + matrix: + - [1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1] + out: 26 + - name: "full_five_by_three" + in: + matrix: + - [1, 1, 1] + - [1, 1, 1] + - [1, 1, 1] + - [1, 1, 1] + - [1, 1, 1] + out: 26 + - name: "full_one_by_ten" + in: + matrix: + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + out: 10 + - name: "full_ten_by_one" + in: + matrix: + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + out: 10 + - name: "full_four_by_five" + in: + matrix: + - [1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1] + out: 40 + - name: "vertical_bands" + in: + matrix: + - [1, 1, 0, 1, 1] + - [1, 1, 0, 1, 1] + - [1, 1, 0, 1, 1] + - [1, 1, 0, 1, 1] + out: 22 + - name: "horizontal_bands" + in: + matrix: + - [1, 1, 1, 1] + - [1, 1, 1, 1] + - [0, 0, 0, 0] + - [1, 1, 1, 1] + - [1, 1, 1, 1] + out: 22 + - name: "top_left_three_by_three" + in: + matrix: + - [1, 1, 1, 0] + - [1, 1, 1, 0] + - [1, 1, 1, 0] + - [0, 0, 0, 0] + out: 14 + - name: "bottom_right_three_by_three" + in: + matrix: + - [0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0] + - [0, 0, 1, 1, 1] + - [0, 0, 1, 1, 1] + - [0, 0, 1, 1, 1] + out: 14 + - name: "alternating_full_rows" + in: + matrix: + - [1, 0, 1, 0, 1] + - [1, 1, 1, 1, 1] + - [1, 0, 1, 0, 1] + - [1, 1, 1, 1, 1] + - [1, 0, 1, 0, 1] + out: 19 + - name: "one_offset_hole" + in: + matrix: + - [1, 1, 1, 1] + - [1, 1, 1, 1] + - [0, 1, 1, 1] + - [1, 1, 1, 1] + out: 24 + - name: "full_zero_five_by_five" + in: + matrix: + - [0, 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: "generator_max_dense_square" + seed: 127701 + in: + matrix: + gen: "array" + len: 300 + elemType: "int" + of: + gen: "array" + len: 300 + elemType: "int" + of: + gen: "int" + min: 0 + max: 1 + - name: "generator_max_wide" + seed: 127702 + in: + matrix: + gen: "array" + len: 299 + elemType: "int" + of: + gen: "array" + len: 300 + elemType: "int" + of: + gen: "int" + min: 0 + max: 1 + - name: "generator_max_tall" + seed: 127703 + in: + matrix: + gen: "array" + len: 300 + elemType: "int" + of: + gen: "array" + len: 299 + elemType: "int" + of: + gen: "int" + min: 0 + max: 1 + - name: "generator_max_single_column" + seed: 127704 + in: + matrix: + gen: "array" + len: 300 + elemType: "int" + of: + gen: "array" + len: 1 + elemType: "int" + of: + gen: "int" + min: 0 + max: 1 + - name: "generator_max_single_row" + seed: 127705 + in: + matrix: + gen: "array" + len: 1 + elemType: "int" + of: + gen: "array" + len: 300 + elemType: "int" + of: + gen: "int" + min: 0 + max: 1 + - name: "generator_large_rectangular" + seed: 127706 + in: + matrix: + gen: "array" + len: 257 + elemType: "int" + of: + gen: "array" + len: 263 + elemType: "int" + of: + gen: "int" + min: 0 + max: 1 diff --git a/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.cpp b/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.cpp new file mode 100644 index 00000000..1ef7af73 --- /dev/null +++ b/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int countSquares(vector>& matrix) { + if (matrix.empty() || matrix[0].empty()) { + return 0; + } + + int m = matrix.size(); + int n = matrix[0].size(); + int res = 0; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (matrix[i][j] == 1 && i > 0 && j > 0) { + matrix[i][j] = min( + min(matrix[i-1][j], matrix[i][j-1]), + matrix[i-1][j-1] + ) + 1; + } + res += matrix[i][j]; + } + } + + return res; + } +}; diff --git a/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.cs b/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.cs new file mode 100644 index 00000000..a40f6d7a --- /dev/null +++ b/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.cs @@ -0,0 +1,25 @@ +public class Solution { + public int CountSquares(int[][] matrix) { + if (matrix == null || matrix.Length == 0 || matrix[0].Length == 0) { + return 0; + } + + int m = matrix.Length; + int n = matrix[0].Length; + int res = 0; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (matrix[i][j] == 1 && i > 0 && j > 0) { + matrix[i][j] = Math.Min( + Math.Min(matrix[i-1][j], matrix[i][j-1]), + matrix[i-1][j-1] + ) + 1; + } + res += matrix[i][j]; + } + } + + return res; + } +} diff --git a/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.dart b/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.dart new file mode 100644 index 00000000..b7181220 --- /dev/null +++ b/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.dart @@ -0,0 +1,26 @@ +class Solution { + int countSquares(List> matrix) { + if (matrix.isEmpty || matrix[0].isEmpty) { + return 0; + } + + int m = matrix.length; + int n = matrix[0].length; + int res = 0; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (matrix[i][j] == 1 && i > 0 && j > 0) { + matrix[i][j] = [ + matrix[i-1][j], + matrix[i][j-1], + matrix[i-1][j-1] + ].reduce((a, b) => a < b ? a : b) + 1; + } + res += matrix[i][j]; + } + } + + return res; + } +} diff --git a/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.go b/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.go new file mode 100644 index 00000000..1f0d8a7d --- /dev/null +++ b/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.go @@ -0,0 +1,22 @@ +func countSquares(matrix [][]int) int { + if len(matrix) == 0 || len(matrix[0]) == 0 { + return 0 + } + + m, n := len(matrix), len(matrix[0]) + res := 0 + + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if matrix[i][j] == 1 && i > 0 && j > 0 { + matrix[i][j] = min( + min(matrix[i-1][j], matrix[i][j-1]), + matrix[i-1][j-1], + ) + 1 + } + res += matrix[i][j] + } + } + + return res +} diff --git a/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.java b/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.java new file mode 100644 index 00000000..21863934 --- /dev/null +++ b/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.java @@ -0,0 +1,25 @@ +class Solution { + public int countSquares(int[][] matrix) { + if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { + return 0; + } + + int m = matrix.length; + int n = matrix[0].length; + int res = 0; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (matrix[i][j] == 1 && i > 0 && j > 0) { + matrix[i][j] = Math.min( + Math.min(matrix[i-1][j], matrix[i][j-1]), + matrix[i-1][j-1] + ) + 1; + } + res += matrix[i][j]; + } + } + + return res; + } +} diff --git a/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.kt b/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.kt new file mode 100644 index 00000000..271a2470 --- /dev/null +++ b/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.kt @@ -0,0 +1,26 @@ +class Solution { + fun countSquares(matrix: Array): Int { + if (matrix.isEmpty() || matrix[0].isEmpty()) { + return 0 + } + + val m = matrix.size + val n = matrix[0].size + var res = 0 + + for (i in 0 until m) { + for (j in 0 until n) { + if (matrix[i][j] == 1 && i > 0 && j > 0) { + matrix[i][j] = minOf( + matrix[i-1][j], + matrix[i][j-1], + matrix[i-1][j-1] + ) + 1 + } + res += matrix[i][j] + } + } + + return res + } +} diff --git a/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.py b/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.py new file mode 100644 index 00000000..fbfe268e --- /dev/null +++ b/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.py @@ -0,0 +1,18 @@ +class Solution: + def countSquares(self, matrix: List[List[int]]) -> int: + if not matrix or not matrix[0]: + return 0 + + m, n = len(matrix), len(matrix[0]) + res = 0 + + for i in range(m): + for j in range(n): + if matrix[i][j] == 1 and i > 0 and j > 0: + matrix[i][j] = ( + min(matrix[i - 1][j], matrix[i][j - 1], matrix[i - 1][j - 1]) + + 1 + ) + res += matrix[i][j] + + return res diff --git a/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.py2 b/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.py2 new file mode 100644 index 00000000..ab6591d7 --- /dev/null +++ b/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.py2 @@ -0,0 +1,23 @@ +class Solution(object): + def countSquares(self, matrix): + """ + :type matrix: List[List[int]] + :rtype: int + """ + if not matrix or not matrix[0]: + return 0 + + m, n = len(matrix), len(matrix[0]) + res = 0 + + for i in range(m): + for j in range(n): + if matrix[i][j] == 1 and i > 0 and j > 0: + matrix[i][j] = min( + matrix[i-1][j], + matrix[i][j-1], + matrix[i-1][j-1] + ) + 1 + res += matrix[i][j] + + return res diff --git a/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.rb b/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.rb new file mode 100644 index 00000000..7870f91a --- /dev/null +++ b/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.rb @@ -0,0 +1,23 @@ +# @param {Integer[][]} matrix +# @return {Integer} +def count_squares(matrix) + return 0 if matrix.nil? || matrix.empty? || matrix[0].empty? + + m, n = matrix.length, matrix[0].length + res = 0 + + (0...m).each do |i| + (0...n).each do |j| + if matrix[i][j] == 1 && i > 0 && j > 0 + matrix[i][j] = [ + matrix[i-1][j], + matrix[i][j-1], + matrix[i-1][j-1] + ].min + 1 + end + res += matrix[i][j] + end + end + + res +end diff --git a/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.rs b/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.rs new file mode 100644 index 00000000..8465dedc --- /dev/null +++ b/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.rs @@ -0,0 +1,26 @@ +impl Solution { + pub fn count_squares(matrix: Vec>) -> i32 { + if matrix.is_empty() || matrix[0].is_empty() { + return 0; + } + + let mut matrix = matrix; + let m = matrix.len(); + let n = matrix[0].len(); + let mut res = 0; + + for i in 0..m { + for j in 0..n { + if matrix[i][j] == 1 && i > 0 && j > 0 { + matrix[i][j] = std::cmp::min( + std::cmp::min(matrix[i-1][j], matrix[i][j-1]), + matrix[i-1][j-1] + ) + 1; + } + res += matrix[i][j]; + } + } + + res + } +} diff --git a/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.swift b/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.swift new file mode 100644 index 00000000..636b10a5 --- /dev/null +++ b/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.swift @@ -0,0 +1,27 @@ +class Solution { + func countSquares(_ matrix: [[Int]]) -> Int { + if matrix.isEmpty || matrix[0].isEmpty { + return 0 + } + + var matrix = matrix + let m = matrix.count + let n = matrix[0].count + var res = 0 + + for i in 0.. 0 && j > 0 { + matrix[i][j] = min( + matrix[i-1][j], + matrix[i][j-1], + matrix[i-1][j-1] + ) + 1 + } + res += matrix[i][j] + } + } + + return res + } +} diff --git a/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.ts b/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.ts new file mode 100644 index 00000000..98705377 --- /dev/null +++ b/tests/1001-1500/1277. count-square-submatrices-with-all-ones/sol.ts @@ -0,0 +1,22 @@ +function countSquares(matrix: number[][]): number { + if (!matrix || matrix.length === 0 || matrix[0].length === 0) { + return 0; + } + + const m = matrix.length; + const n = matrix[0].length; + let res = 0; + + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + if (matrix[i][j] === 1 && i > 0 && j > 0) { + matrix[i][j] = + Math.min(matrix[i - 1][j], matrix[i][j - 1], matrix[i - 1][j - 1]) + + 1; + } + res += matrix[i][j]; + } + } + + return res; +} diff --git a/tests/1001-1500/1278. palindrome-partitioning-iii/manifest.yaml b/tests/1001-1500/1278. palindrome-partitioning-iii/manifest.yaml new file mode 100644 index 00000000..1dca4ff2 --- /dev/null +++ b/tests/1001-1500/1278. palindrome-partitioning-iii/manifest.yaml @@ -0,0 +1,282 @@ +entry: + id: 1278 + title: palindrome-partitioning-iii + params: + s: + type: string + k: + type: int + call: + cpp: "Solution().palindromePartition({s}, {k})" + rust: "Solution::palindrome_partition({s}, {k})" + python3: "Solution().palindromePartition({s}, {k})" + python2: "Solution().palindromePartition({s}, {k})" + ruby: "palindrome_partition({s}, {k})" + java: "new Solution().palindromePartition({s}, {k})" + csharp: "new Solution().PalindromePartition({s}, {k})" + kotlin: "Solution().palindromePartition({s}, {k})" + go: "palindromePartition({s}, {k})" + dart: "Solution().palindromePartition({s}, {k})" + swift: "Solution().palindromePartition({s}, {k})" + typescript: "palindromePartition({s}, {k})" +judge: + type: exact +limits: + time_ms: 500 + memory_mb: 300 +oracle: + python3: + call: "Checker().palindromePartition(s, k, {result})" + checker: | + class Checker: + def palindromePartition(self, s, k, result): + n = len(s) + changes = [[0] * n for _ in range(n)] + for length in range(2, n + 1): + for left in range(n - length + 1): + right = left + length - 1 + changes[left][right] = changes[left + 1][right - 1] + (s[left] != s[right]) if length > 2 else (s[left] != s[right]) + best = [[n + 1] * (n + 1) for _ in range(k + 1)] + best[0][0] = 0 + for parts in range(1, k + 1): + for end in range(parts, n + 1): + best[parts][end] = min(best[parts - 1][split] + changes[split][end - 1] for split in range(parts - 1, end)) + return result == best[k][n] +seed: 1278 +tests: + - name: ex1 + in: + s: abc + k: 2 + out: 1 + - name: ex2 + in: + s: aabbc + k: 3 + out: 0 + - name: ex3 + in: + s: leetcode + k: 8 + out: 0 + - name: one + in: + s: a + k: 1 + out: 0 + - name: ab_one + in: + s: ab + k: 1 + out: 1 + - name: ab_each + in: + s: ab + k: 2 + out: 0 + - name: aa + in: + s: aa + k: 1 + out: 0 + - name: abc_one + in: + s: abc + k: 1 + out: 1 + - name: abcd_one + in: + s: abcd + k: 1 + out: 2 + - name: abcd_two + in: + s: abcd + k: 2 + out: 1 + - name: abba_one + in: + s: abba + k: 1 + out: 0 + - name: abba_two + in: + s: abba + k: 2 + out: 1 + - name: abcba_one + in: + s: abcba + k: 1 + out: 0 + - name: abcba_two + in: + s: abcba + k: 2 + out: 2 + - name: uniform + in: + s: aaaaaa + k: 3 + out: 0 + - name: ready_pairs + in: + s: aabbaa + k: 3 + out: 0 + - name: mixed_parts + in: + s: aabccb + k: 3 + out: 0 + - name: racecar_two + in: + s: racecar + k: 2 + out: 3 + - name: racecar_three + in: + s: racecar + k: 3 + out: 0 + - name: three_palindromes + in: + s: noonabbad + k: 3 + out: 0 + - name: coding + in: + s: coding + k: 2 + out: 2 + - name: banana_one + in: + s: banana + k: 1 + out: 3 + - name: banana_two + in: + s: banana + k: 2 + out: 0 + - name: banana_three + in: + s: banana + k: 3 + out: 1 + - name: ten_distinct + in: + s: abcdefghij + k: 2 + out: 4 + - name: all_mismatch + in: + s: azbycxdwev + k: 1 + out: 5 + - name: repeated_abc + in: + s: abcabc + k: 2 + out: 2 + - name: cbbd + in: + s: cbbd + k: 2 + out: 1 + - name: known_hard + in: + s: aacabdkacaa + k: 3 + out: 1 + - name: leetcode_three + in: + s: leetcode + k: 3 + out: 2 + - name: overlap + in: + s: abcbaabc + k: 3 + out: 0 + - name: six_pairs + in: + s: aabbccddeeff + k: 6 + out: 0 + - name: alternating + in: + s: abababab + k: 3 + out: 1 + - name: generated_max_length_broad_k + seed: 127801 + in: + s: + gen: str + len: 100 + alphabet: "abcdefghijklmnopqrstuvwxyz" + k: + gen: int + min: 1 + max: 100 + - name: generated_max_length_low_k + seed: 127802 + in: + s: + gen: str + len: 100 + alphabet: "abcdefghijklmnopqrstuvwxyz" + k: + gen: int + min: 1 + max: 10 + - name: generated_max_length_high_k + seed: 127803 + in: + s: + gen: str + len: 100 + alphabet: "abcdefghijklmnopqrstuvwxyz" + k: + gen: int + min: 90 + max: 100 + - name: generated_max_length_mid_k + seed: 127804 + in: + s: + gen: str + len: 100 + alphabet: "abcdefghijklmnopqrstuvwxyz" + k: + gen: int + min: 40 + max: 60 + - name: generated_max_length_small_alphabet + seed: 127805 + in: + s: + gen: str + len: 100 + alphabet: "abc" + k: + gen: int + min: 2 + max: 99 + - name: large_palindrome + in: + s: abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxxwvutsrqponmlkjihgfedcbazyxwvutsrqponmlkjihgfedcba + k: 1 + out: 0 + - name: generated_max_length_binary + seed: 127806 + in: + s: + gen: str + len: 100 + alphabet: "ab" + k: + gen: int + min: 1 + max: 100 diff --git a/tests/1001-1500/1278. palindrome-partitioning-iii/sol.cpp b/tests/1001-1500/1278. palindrome-partitioning-iii/sol.cpp new file mode 100644 index 00000000..e081c9fb --- /dev/null +++ b/tests/1001-1500/1278. palindrome-partitioning-iii/sol.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int palindromePartition(string s, int k) { + int n = s.size(); + vector> c(n, vector(n, 0)); + for (int l = 2; l <= n; l++) { + for (int i = 0; i <= n - l; i++) { + int j = i + l - 1; + c[i][j] = (l > 2 ? c[i + 1][j - 1] : 0) + (s[i] != s[j] ? 1 : 0); + } + } + vector> dp(k + 1, vector(n + 1, 1e9)); + dp[0][0] = 0; + for (int i = 1; i <= n; i++) { + dp[1][i] = c[0][i - 1]; + } + for (int p = 2; p <= k; p++) { + for (int i = p; i <= n; i++) { + int mn = 1e9; + for (int t = p - 1; t < i; t++) { + mn = min(mn, dp[p - 1][t] + c[t][i - 1]); + } + dp[p][i] = mn; + } + } + return dp[k][n]; + } +}; diff --git a/tests/1001-1500/1278. palindrome-partitioning-iii/sol.cs b/tests/1001-1500/1278. palindrome-partitioning-iii/sol.cs new file mode 100644 index 00000000..1c2ee00e --- /dev/null +++ b/tests/1001-1500/1278. palindrome-partitioning-iii/sol.cs @@ -0,0 +1,32 @@ +public class Solution { + public int PalindromePartition(string s, int k) { + int n = s.Length; + int[,] c = new int[n, n]; + for (int l = 2; l <= n; l++) { + for (int i = 0; i <= n - l; i++) { + int j = i + l - 1; + c[i, j] = (l > 2 ? c[i + 1, j - 1] : 0) + (s[i] != s[j] ? 1 : 0); + } + } + int[,] dp = new int[k + 1, n + 1]; + for (int i = 0; i <= k; i++) { + for (int j = 0; j <= n; j++) { + dp[i, j] = int.MaxValue / 2; + } + } + dp[0, 0] = 0; + for (int i = 1; i <= n; i++) { + dp[1, i] = c[0, i - 1]; + } + for (int p = 2; p <= k; p++) { + for (int i = p; i <= n; i++) { + int mn = int.MaxValue / 2; + for (int t = p - 1; t < i; t++) { + mn = Math.Min(mn, dp[p - 1, t] + c[t, i - 1]); + } + dp[p, i] = mn; + } + } + return dp[k, n]; + } +} diff --git a/tests/1001-1500/1278. palindrome-partitioning-iii/sol.dart b/tests/1001-1500/1278. palindrome-partitioning-iii/sol.dart new file mode 100644 index 00000000..6282e7d7 --- /dev/null +++ b/tests/1001-1500/1278. palindrome-partitioning-iii/sol.dart @@ -0,0 +1,27 @@ +class Solution { + int palindromePartition(String s, int k) { + int n = s.length; + List> c = List.generate(n, (_) => List.filled(n, 0)); + for (int l = 2; l <= n; l++) { + for (int i = 0; i <= n - l; i++) { + int j = i + l - 1; + c[i][j] = (l > 2 ? c[i + 1][j - 1] : 0) + (s[i] != s[j] ? 1 : 0); + } + } + List> dp = List.generate(k + 1, (_) => List.filled(n + 1, 1 << 30)); + dp[0][0] = 0; + for (int i = 1; i <= n; i++) { + dp[1][i] = c[0][i - 1]; + } + for (int p = 2; p <= k; p++) { + for (int i = p; i <= n; i++) { + int mn = 1 << 30; + for (int t = p - 1; t < i; t++) { + mn = mn < dp[p - 1][t] + c[t][i - 1] ? mn : dp[p - 1][t] + c[t][i - 1]; + } + dp[p][i] = mn; + } + } + return dp[k][n]; + } +} diff --git a/tests/1001-1500/1278. palindrome-partitioning-iii/sol.go b/tests/1001-1500/1278. palindrome-partitioning-iii/sol.go new file mode 100644 index 00000000..5e16a1e1 --- /dev/null +++ b/tests/1001-1500/1278. palindrome-partitioning-iii/sol.go @@ -0,0 +1,45 @@ +func palindromePartition(s string, k int) int { + n := len(s) + c := make([][]int, n) + for i := range c { + c[i] = make([]int, n) + } + for l := 2; l <= n; l++ { + for i := 0; i <= n-l; i++ { + j := i + l - 1 + prev := 0 + if l > 2 { + prev = c[i+1][j-1] + } + add := 0 + if s[i] != s[j] { + add = 1 + } + c[i][j] = prev + add + } + } + dp := make([][]int, k+1) + for i := range dp { + dp[i] = make([]int, n+1) + for j := range dp[i] { + dp[i][j] = 1 << 30 + } + } + dp[0][0] = 0 + for i := 1; i <= n; i++ { + dp[1][i] = c[0][i-1] + } + for p := 2; p <= k; p++ { + for i := p; i <= n; i++ { + mn := 1 << 30 + for t := p - 1; t < i; t++ { + val := dp[p-1][t] + c[t][i-1] + if val < mn { + mn = val + } + } + dp[p][i] = mn + } + } + return dp[k][n] +} diff --git a/tests/1001-1500/1278. palindrome-partitioning-iii/sol.java b/tests/1001-1500/1278. palindrome-partitioning-iii/sol.java new file mode 100644 index 00000000..cbdc55ec --- /dev/null +++ b/tests/1001-1500/1278. palindrome-partitioning-iii/sol.java @@ -0,0 +1,32 @@ +class Solution { + public int palindromePartition(String s, int k) { + int n = s.length(); + int[][] c = new int[n][n]; + for (int l = 2; l <= n; l++) { + for (int i = 0; i <= n - l; i++) { + int j = i + l - 1; + c[i][j] = (l > 2 ? c[i + 1][j - 1] : 0) + (s.charAt(i) != s.charAt(j) ? 1 : 0); + } + } + int[][] dp = new int[k + 1][n + 1]; + for (int i = 0; i <= k; i++) { + for (int j = 0; j <= n; j++) { + dp[i][j] = Integer.MAX_VALUE / 2; + } + } + dp[0][0] = 0; + for (int i = 1; i <= n; i++) { + dp[1][i] = c[0][i - 1]; + } + for (int p = 2; p <= k; p++) { + for (int i = p; i <= n; i++) { + int mn = Integer.MAX_VALUE / 2; + for (int t = p - 1; t < i; t++) { + mn = Math.min(mn, dp[p - 1][t] + c[t][i - 1]); + } + dp[p][i] = mn; + } + } + return dp[k][n]; + } +} diff --git a/tests/1001-1500/1278. palindrome-partitioning-iii/sol.kt b/tests/1001-1500/1278. palindrome-partitioning-iii/sol.kt new file mode 100644 index 00000000..0afba92b --- /dev/null +++ b/tests/1001-1500/1278. palindrome-partitioning-iii/sol.kt @@ -0,0 +1,27 @@ +class Solution { + fun palindromePartition(s: String, k: Int): Int { + val n = s.length + val c = Array(n) { IntArray(n) } + for (l in 2..n) { + for (i in 0..n - l) { + val j = i + l - 1 + c[i][j] = (if (l > 2) c[i + 1][j - 1] else 0) + if (s[i] != s[j]) 1 else 0 + } + } + val dp = Array(k + 1) { IntArray(n + 1) { Int.MAX_VALUE / 2 } } + dp[0][0] = 0 + for (i in 1..n) { + dp[1][i] = c[0][i - 1] + } + for (p in 2..k) { + for (i in p..n) { + var mn = Int.MAX_VALUE / 2 + for (t in p - 1 until i) { + mn = minOf(mn, dp[p - 1][t] + c[t][i - 1]) + } + dp[p][i] = mn + } + } + return dp[k][n] + } +} diff --git a/tests/1001-1500/1278. palindrome-partitioning-iii/sol.py b/tests/1001-1500/1278. palindrome-partitioning-iii/sol.py new file mode 100644 index 00000000..3ff6f9ce --- /dev/null +++ b/tests/1001-1500/1278. palindrome-partitioning-iii/sol.py @@ -0,0 +1,19 @@ +class Solution: + def palindromePartition(self, s: str, k: int) -> int: + n = len(s) + c = [[0] * n for _ in range(n)] + for l in range(2, n + 1): + for i in range(n - l + 1): + j = i + l - 1 + c[i][j] = (c[i + 1][j - 1] if l > 2 else 0) + (s[i] != s[j]) + dp = [[float("inf")] * (n + 1) for _ in range(k + 1)] + dp[0][0] = 0 + for i in range(1, n + 1): + dp[1][i] = c[0][i - 1] + for p in range(2, k + 1): + for i in range(p, n + 1): + mn = float("inf") + for t in range(p - 1, i): + mn = min(mn, dp[p - 1][t] + c[t][i - 1]) + dp[p][i] = mn + return dp[k][n] diff --git a/tests/1001-1500/1278. palindrome-partitioning-iii/sol.py2 b/tests/1001-1500/1278. palindrome-partitioning-iii/sol.py2 new file mode 100644 index 00000000..744991a7 --- /dev/null +++ b/tests/1001-1500/1278. palindrome-partitioning-iii/sol.py2 @@ -0,0 +1,24 @@ +class Solution(object): + def palindromePartition(self, s, k): + """ + :type s: str + :type k: int + :rtype: int + """ + n = len(s) + c = [[0] * n for _ in range(n)] + for l in range(2, n + 1): + for i in range(n - l + 1): + j = i + l - 1 + c[i][j] = (c[i + 1][j - 1] if l > 2 else 0) + (s[i] != s[j]) + dp = [[float("inf")] * (n + 1) for _ in range(k + 1)] + dp[0][0] = 0 + for i in range(1, n + 1): + dp[1][i] = c[0][i - 1] + for p in range(2, k + 1): + for i in range(p, n + 1): + mn = float("inf") + for t in range(p - 1, i): + mn = min(mn, dp[p - 1][t] + c[t][i - 1]) + dp[p][i] = mn + return dp[k][n] diff --git a/tests/1001-1500/1278. palindrome-partitioning-iii/sol.rb b/tests/1001-1500/1278. palindrome-partitioning-iii/sol.rb new file mode 100644 index 00000000..358ae8bf --- /dev/null +++ b/tests/1001-1500/1278. palindrome-partitioning-iii/sol.rb @@ -0,0 +1,28 @@ +# @param {String} s +# @param {Integer} k +# @return {Integer} +def palindrome_partition(s, k) + n = s.length + c = Array.new(n) { Array.new(n, 0) } + (2..n).each do |l| + (0..n - l).each do |i| + j = i + l - 1 + c[i][j] = (l > 2 ? c[i + 1][j - 1] : 0) + (s[i] != s[j] ? 1 : 0) + end + end + dp = Array.new(k + 1) { Array.new(n + 1, Float::INFINITY) } + dp[0][0] = 0 + (1..n).each do |i| + dp[1][i] = c[0][i - 1] + end + (2..k).each do |p| + (p..n).each do |i| + mn = Float::INFINITY + (p - 1...i).each do |t| + mn = [mn, dp[p - 1][t] + c[t][i - 1]].min + end + dp[p][i] = mn + end + end + dp[k][n].to_i +end diff --git a/tests/1001-1500/1278. palindrome-partitioning-iii/sol.rs b/tests/1001-1500/1278. palindrome-partitioning-iii/sol.rs new file mode 100644 index 00000000..33d891fe --- /dev/null +++ b/tests/1001-1500/1278. palindrome-partitioning-iii/sol.rs @@ -0,0 +1,29 @@ +impl Solution { + pub fn palindrome_partition(s: String, k: i32) -> i32 { + let n = s.len(); + let k = k as usize; + let bytes = s.as_bytes(); + let mut c = vec![vec![0; n]; n]; + for l in 2..=n { + for i in 0..=n - l { + let j = i + l - 1; + c[i][j] = if l > 2 { c[i + 1][j - 1] } else { 0 } + if bytes[i] != bytes[j] { 1 } else { 0 }; + } + } + let mut dp = vec![vec![i32::MAX / 2; n + 1]; k + 1]; + dp[0][0] = 0; + for i in 1..=n { + dp[1][i] = c[0][i - 1]; + } + for p in 2..=k { + for i in p..=n { + let mut mn = i32::MAX / 2; + for t in (p - 1)..i { + mn = mn.min(dp[p - 1][t] + c[t][i - 1]); + } + dp[p][i] = mn; + } + } + dp[k][n] + } +} diff --git a/tests/1001-1500/1278. palindrome-partitioning-iii/sol.swift b/tests/1001-1500/1278. palindrome-partitioning-iii/sol.swift new file mode 100644 index 00000000..07cdc4c5 --- /dev/null +++ b/tests/1001-1500/1278. palindrome-partitioning-iii/sol.swift @@ -0,0 +1,32 @@ +class Solution { + func palindromePartition(_ s: String, _ k: Int) -> Int { + let n = s.count + let chars = Array(s) + var c = Array(repeating: Array(repeating: 0, count: n), count: n) + if n >= 2 { + for l in 2...n { + for i in 0...(n - l) { + let j = i + l - 1 + c[i][j] = (l > 2 ? c[i + 1][j - 1] : 0) + (chars[i] != chars[j] ? 1 : 0) + } + } + } + var dp = Array(repeating: Array(repeating: Int.max / 2, count: n + 1), count: k + 1) + dp[0][0] = 0 + for i in 1...n { + dp[1][i] = c[0][i - 1] + } + if k >= 2 { + for p in 2...k { + for i in p...n { + var mn = Int.max / 2 + for t in (p - 1).. Array(n).fill(0)); + for (let l = 2; l <= n; l++) { + for (let i = 0; i <= n - l; i++) { + const j = i + l - 1; + c[i][j] = (l > 2 ? c[i + 1][j - 1] : 0) + (s[i] !== s[j] ? 1 : 0); + } + } + const dp: number[][] = Array.from({ length: k + 1 }, () => + Array(n + 1).fill(1 << 30), + ); + dp[0][0] = 0; + for (let i = 1; i <= n; i++) { + dp[1][i] = c[0][i - 1]; + } + for (let p = 2; p <= k; p++) { + for (let i = p; i <= n; i++) { + let mn = 1 << 30; + for (let t = p - 1; t < i; t++) { + mn = Math.min(mn, dp[p - 1][t] + c[t][i - 1]); + } + dp[p][i] = mn; + } + } + return dp[k][n]; +} diff --git a/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/manifest.yaml b/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/manifest.yaml new file mode 100644 index 00000000..c03da689 --- /dev/null +++ b/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/manifest.yaml @@ -0,0 +1,228 @@ +entry: + id: 1281 + title: "subtract-the-product-and-sum-of-digits-of-an-integer" + params: + n: + type: int + call: + cpp: "Solution().subtractProductAndSum({n})" + rust: "Solution::subtract_product_and_sum({n})" + python3: "Solution().subtractProductAndSum({n})" + python2: "Solution().subtractProductAndSum({n})" + ruby: "subtract_product_and_sum({n})" + java: "new Solution().subtractProductAndSum({n})" + csharp: "new Solution().SubtractProductAndSum({n})" + kotlin: "Solution().subtractProductAndSum({n})" + go: "subtractProductAndSum({n})" + dart: "Solution().subtractProductAndSum({n})" + swift: "Solution().subtractProductAndSum({n})" + typescript: "subtractProductAndSum({n})" + +judge: + type: "exact" + +limits: + time_ms: 300 + memory_mb: 300 + +oracle: + python3: + call: "Checker().subtractProductAndSum(n, {result})" + checker: | + class Checker: + def subtractProductAndSum(self, n, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if not isinstance(n, int) or isinstance(n, bool) or not 1 <= n <= 100000: + return False + product = 1 + digit_sum = 0 + remaining = n + while remaining: + digit = remaining % 10 + product *= digit + digit_sum += digit + remaining //= 10 + return result == product - digit_sum + +seed: 128100 + +tests: + - name: "example_234" + in: + n: 234 + out: 15 + - name: "example_4421" + in: + n: 4421 + out: 21 + - name: "minimum_one" + in: + n: 1 + out: 0 + - name: "single_digit_nine" + in: + n: 9 + out: 0 + - name: "two_digits_with_trailing_zero" + in: + n: 10 + out: -1 + - name: "two_identical_ones" + in: + n: 11 + out: -1 + - name: "two_digits_zero_last" + in: + n: 20 + out: -2 + - name: "hundred_with_two_zeroes" + in: + n: 100 + out: -1 + - name: "zero_between_ones" + in: + n: 101 + out: -2 + - name: "three_nines" + in: + n: 999 + out: 702 + - name: "four_ones" + in: + n: 1111 + out: -3 + - name: "zero_in_middle" + in: + n: 202 + out: -4 + - name: "zero_at_end" + in: + n: 120 + out: -3 + - name: "three_trailing_zeroes" + in: + n: 1000 + out: -1 + - name: "palindrome" + in: + n: 1221 + out: -2 + - name: "ascending_four_digits" + in: + n: 1234 + out: 14 + - name: "descending_four_digits" + in: + n: 4321 + out: 14 + - name: "descending_five_digits" + in: + n: 54321 + out: 105 + - name: "constraint_maximum" + in: + n: 100000 + out: -1 + - name: "all_nines_near_maximum" + in: + n: 99999 + out: 59004 + - name: "large_with_zeroes" + in: + n: 90000 + out: -9 + - name: "alternating_zeroes" + in: + n: 90909 + out: -27 + - name: "five_twos" + in: + n: 22222 + out: 22 + - name: "five_fives" + in: + n: 55555 + out: 3100 + - name: "zero_before_nonzero_suffix" + in: + n: 1023 + out: -6 + - name: "high_product_four_digits" + in: + n: 9876 + out: 2994 + - name: "large_two_digit_product" + in: + n: 98 + out: 55 + - name: "smallest_three_digit_with_zero" + in: + n: 102 + out: -3 + - name: "four_digit_nonzero_suffix" + in: + n: 1002 + out: -3 + - name: "pi_prefix_digits" + in: + n: 31415 + out: 46 + - name: "reordered_pi_prefix_digits" + in: + n: 51413 + out: 46 + - name: "four_trailing_zeroes" + in: + n: 10000 + out: -1 + - name: "five_ones" + in: + n: 11111 + out: -4 + - name: "four_nines" + in: + n: 9999 + out: 6525 + - name: "generated_two_digits" + seed: 128101 + in: + n: + gen: "int" + min: 10 + max: 99 + - name: "generated_three_digits" + seed: 128102 + in: + n: + gen: "int" + min: 100 + max: 999 + - name: "generated_four_digits" + seed: 128103 + in: + n: + gen: "int" + min: 1000 + max: 9999 + - name: "generated_five_digits" + seed: 128104 + in: + n: + gen: "int" + min: 10000 + max: 99999 + - name: "generated_upper_boundary_band" + seed: 128105 + in: + n: + gen: "int" + min: 99900 + max: 100000 + - name: "generated_full_constraint_range" + seed: 128106 + in: + n: + gen: "int" + min: 1 + max: 100000 diff --git a/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.cpp b/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.cpp new file mode 100644 index 00000000..667ea786 --- /dev/null +++ b/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int subtractProductAndSum(int n) { + int sum_digits = 0; + int product_digits = 1; + + while (n > 0) { + int digit = n % 10; + sum_digits += digit; + product_digits *= digit; + n /= 10; + } + + return product_digits - sum_digits; + } +}; diff --git a/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.cs b/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.cs new file mode 100644 index 00000000..5969039e --- /dev/null +++ b/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.cs @@ -0,0 +1,15 @@ +public class Solution { + public int SubtractProductAndSum(int n) { + int sum_digits = 0; + int product_digits = 1; + + while (n > 0) { + int digit = n % 10; + sum_digits += digit; + product_digits *= digit; + n /= 10; + } + + return product_digits - sum_digits; + } +} diff --git a/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.dart b/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.dart new file mode 100644 index 00000000..8cd7c9d6 --- /dev/null +++ b/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.dart @@ -0,0 +1,15 @@ +class Solution { + int subtractProductAndSum(int n) { + int sum_digits = 0; + int product_digits = 1; + + while (n > 0) { + int digit = n % 10; + sum_digits += digit; + product_digits *= digit; + n ~/= 10; + } + + return product_digits - sum_digits; + } +} diff --git a/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.go b/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.go new file mode 100644 index 00000000..3ed019e1 --- /dev/null +++ b/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.go @@ -0,0 +1,13 @@ +func subtractProductAndSum(n int) int { + sum_digits := 0 + product_digits := 1 + + for n > 0 { + digit := n % 10 + sum_digits += digit + product_digits *= digit + n /= 10 + } + + return product_digits - sum_digits +} diff --git a/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.java b/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.java new file mode 100644 index 00000000..da917c86 --- /dev/null +++ b/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.java @@ -0,0 +1,15 @@ +class Solution { + public int subtractProductAndSum(int n) { + int sum_digits = 0; + int product_digits = 1; + + while (n > 0) { + int digit = n % 10; + sum_digits += digit; + product_digits *= digit; + n /= 10; + } + + return product_digits - sum_digits; + } +} diff --git a/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.kt b/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.kt new file mode 100644 index 00000000..3335382e --- /dev/null +++ b/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun subtractProductAndSum(n: Int): Int { + var sum_digits = 0 + var product_digits = 1 + var num = n + + while (num > 0) { + val digit = num % 10 + sum_digits += digit + product_digits *= digit + num /= 10 + } + + return product_digits - sum_digits + } +} diff --git a/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.py b/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.py new file mode 100644 index 00000000..2074fc70 --- /dev/null +++ b/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.py @@ -0,0 +1,12 @@ +class Solution: + def subtractProductAndSum(self, n: int) -> int: + sum_digits = 0 + product_digits = 1 + + while n > 0: + digit = n % 10 + sum_digits += digit + product_digits *= digit + n //= 10 + + return product_digits - sum_digits diff --git a/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.py2 b/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.py2 new file mode 100644 index 00000000..301401b7 --- /dev/null +++ b/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def subtractProductAndSum(self, n): + """ + :type n: int + :rtype: int + """ + sum_digits = 0 + product_digits = 1 + + while n > 0: + digit = n % 10 + sum_digits += digit + product_digits *= digit + n //= 10 + + return product_digits - sum_digits diff --git a/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.rb b/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.rb new file mode 100644 index 00000000..b0fc3a16 --- /dev/null +++ b/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.rb @@ -0,0 +1,15 @@ +# @param {Integer} n +# @return {Integer} +def subtract_product_and_sum(n) + sum_digits = 0 + product_digits = 1 + + while n > 0 + digit = n % 10 + sum_digits += digit + product_digits *= digit + n /= 10 + end + + return product_digits - sum_digits +end diff --git a/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.rs b/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.rs new file mode 100644 index 00000000..8c3f9264 --- /dev/null +++ b/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn subtract_product_and_sum(n: i32) -> i32 { + let mut sum_digits = 0; + let mut product_digits = 1; + let mut n = n; + + while n > 0 { + let digit = n % 10; + sum_digits += digit; + product_digits *= digit; + n /= 10; + } + + product_digits - sum_digits + } +} diff --git a/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.swift b/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.swift new file mode 100644 index 00000000..8b4322a2 --- /dev/null +++ b/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.swift @@ -0,0 +1,16 @@ +class Solution { + func subtractProductAndSum(_ n: Int) -> Int { + var sum_digits = 0 + var product_digits = 1 + var num = n + + while num > 0 { + let digit = num % 10 + sum_digits += digit + product_digits *= digit + num /= 10 + } + + return product_digits - sum_digits + } +} diff --git a/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.ts b/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.ts new file mode 100644 index 00000000..374aa556 --- /dev/null +++ b/tests/1001-1500/1281. subtract-the-product-and-sum-of-digits-of-an-integer/sol.ts @@ -0,0 +1,13 @@ +function subtractProductAndSum(n: number): number { + let sum_digits = 0; + let product_digits = 1; + + while (n > 0) { + const digit = n % 10; + sum_digits += digit; + product_digits *= digit; + n = Math.floor(n / 10); + } + + return product_digits - sum_digits; +} diff --git a/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/manifest.yaml b/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/manifest.yaml new file mode 100644 index 00000000..037ddc06 --- /dev/null +++ b/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/manifest.yaml @@ -0,0 +1,333 @@ +entry: + id: 1282 + title: "group-the-people-given-the-group-size-they-belong-to" + params: + groupSizes: + type: array + items: + type: int + call: + cpp: "Solution().groupThePeople({groupSizes})" + rust: "Solution::group_the_people({groupSizes})" + python3: "Solution().groupThePeople({groupSizes})" + python2: "Solution().groupThePeople({groupSizes})" + ruby: "group_the_people({groupSizes})" + java: "new Solution().groupThePeople({groupSizes})" + csharp: "new Solution().GroupThePeople({groupSizes})" + kotlin: "Solution().groupThePeople({groupSizes})" + go: "groupThePeople({groupSizes})" + dart: "Solution().groupThePeople({groupSizes})" + swift: "Solution().groupThePeople({groupSizes})" + typescript: "groupThePeople({groupSizes})" + +judge: + type: "exact" + +limits: + time_ms: 700 + memory_mb: 300 + +oracle: + python3: + call: "Checker().groupThePeople(groupSizes, {result})" + checker: | + class Checker: + def groupThePeople(self, groupSizes, result): + if not isinstance(result, list): + return False + n = len(groupSizes) + seen = [] + for group in result: + if not isinstance(group, list) or not group: + return False + first = group[0] + if type(first) is not int or first < 0 or first >= n: + return False + size = groupSizes[first] + if size != len(group) or any(type(person) is not int or person < 0 or person >= n or groupSizes[person] != size for person in group): + return False + seen.extend(group) + return sorted(seen) == list(range(n)) and len(seen) == len(set(seen)) + +seed: 128200 + +tests: + - name: "example_one" + in: + groupSizes: [3, 3, 3, 3, 3, 1, 3] + - name: "example_two" + in: + groupSizes: [2, 1, 3, 3, 3, 2] + - name: "single_person" + in: + groupSizes: [1] + - name: "all_singletons_four" + in: + groupSizes: [1, 1, 1, 1] + - name: "one_pair" + in: + groupSizes: [2, 2] + - name: "two_pairs" + in: + groupSizes: [2, 2, 2, 2] + - name: "three_pairs" + in: + groupSizes: [2, 2, 2, 2, 2, 2] + - name: "one_triple" + in: + groupSizes: [3, 3, 3] + - name: "two_triples" + in: + groupSizes: [3, 3, 3, 3, 3, 3] + - name: "one_quad" + in: + groupSizes: [4, 4, 4, 4] + - name: "two_quads" + in: + groupSizes: [4, 4, 4, 4, 4, 4, 4, 4] + - name: "mixed_one_two" + in: + groupSizes: [1, 2, 2, 1, 2, 2] + - name: "mixed_one_three" + in: + groupSizes: [3, 1, 3, 3, 1, 3, 3, 3] + - name: "mixed_two_three" + in: + groupSizes: [2, 3, 3, 2, 2, 3, 3, 2, 3, 3] + - name: "mixed_one_four" + in: + groupSizes: [4, 1, 4, 4, 1, 4, 4, 4, 1, 4, 1, 4] + - name: "ordered_blocks" + in: + groupSizes: [1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4] + - name: "interleaved_two_three" + in: + groupSizes: [2, 3, 2, 3, 3, 2, 3, 2, 3, 3] + - name: "many_singletons_pair" + in: + groupSizes: [1, 2, 1, 2, 1, 2, 1, 2] + - name: "three_sizes" + in: + groupSizes: [5, 5, 5, 5, 5, 1, 2, 2] + - name: "five_groups" + in: + groupSizes: [5, 5, 5, 5, 5, 2, 2, 1, 1, 2, 2] + - name: "size_six" + in: + groupSizes: [6, 6, 6, 6, 6, 6] + - name: "two_size_six" + in: + groupSizes: [6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6] + - name: "size_seven" + in: + groupSizes: [7, 7, 7, 7, 7, 7, 7] + - name: "mixed_four_five" + in: + groupSizes: [4, 5, 4, 5, 4, 5, 4, 5, 5] + - name: "mixed_many" + in: + groupSizes: [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 3, 3] + - name: "size_eight" + in: + groupSizes: [8, 8, 8, 8, 8, 8, 8, 8] + - name: "size_ten" + in: + groupSizes: [10, 10, 10, 10, 10, 10, 10, 10, 10, 10] + - name: "large_mixed_blocks" + in: + groupSizes: + [1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5] + - name: "alternating_single_pair" + in: + groupSizes: [1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2] + - name: "three_four_five" + in: + groupSizes: [3, 4, 5, 3, 4, 5, 3, 4, 5, 4, 5, 5] + - name: "size_twelve" + in: + groupSizes: [12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12] + - name: "two_size_nine_groups" + in: + groupSizes: [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9] + - name: "single_group_of_fifty" + in: + groupSizes: + [ + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + ] + - name: "two_groups_of_twenty_five" + in: + groupSizes: + [ + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + 25, + ] + - name: "generated_max_singletons" + seed: 128201 + in: + groupSizes: + gen: "array" + len: 500 + of: + gen: "int" + min: 1 + max: 1 + distinct: false + sorted: false + - name: "generated_max_pairs" + seed: 128202 + in: + groupSizes: + gen: "array" + len: 500 + of: + gen: "int" + min: 2 + max: 2 + distinct: false + sorted: false + - name: "generated_max_triples" + seed: 128203 + in: + groupSizes: + gen: "array" + len: 498 + of: + gen: "int" + min: 3 + max: 3 + distinct: false + sorted: false + - name: "generated_max_quintuples" + seed: 128204 + in: + groupSizes: + gen: "array" + len: 500 + of: + gen: "int" + min: 5 + max: 5 + distinct: false + sorted: false + - name: "generated_max_tens" + seed: 128205 + in: + groupSizes: + gen: "array" + len: 500 + of: + gen: "int" + min: 10 + max: 10 + distinct: false + sorted: false + - name: "generated_max_twenty_fives" + seed: 128206 + in: + groupSizes: + gen: "array" + len: 500 + of: + gen: "int" + min: 25 + max: 25 + distinct: false + sorted: false diff --git a/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.cpp b/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.cpp new file mode 100644 index 00000000..c41312f4 --- /dev/null +++ b/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + vector> groupThePeople(vector& groupSizes) { + vector> ans; + unordered_map> mp; + for (int i = 0; i < groupSizes.size(); ++i) { + int v = groupSizes[i]; + mp[v].push_back(i); + if (mp[v].size() == v) { + ans.push_back(mp[v]); + mp[v].clear(); + } + } + return ans; + } +}; diff --git a/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.cs b/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.cs new file mode 100644 index 00000000..6f219ec2 --- /dev/null +++ b/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.cs @@ -0,0 +1,16 @@ +public class Solution { + public IList> GroupThePeople(int[] groupSizes) { + IList> ans = new List>(); + Dictionary> mp = new Dictionary>(); + for (int i = 0; i < groupSizes.Length; i++) { + int v = groupSizes[i]; + if (!mp.ContainsKey(v)) mp[v] = new List(); + mp[v].Add(i); + if (mp[v].Count == v) { + ans.Add(new List(mp[v])); + mp[v] = new List(); + } + } + return ans; + } +} diff --git a/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.dart b/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.dart new file mode 100644 index 00000000..62556e9e --- /dev/null +++ b/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.dart @@ -0,0 +1,16 @@ +class Solution { + List> groupThePeople(List groupSizes) { + List> ans = []; + Map> mp = {}; + for (int i = 0; i < groupSizes.length; i++) { + int v = groupSizes[i]; + mp.putIfAbsent(v, () => []); + mp[v]!.add(i); + if (mp[v]!.length == v) { + ans.add(List.from(mp[v]!)); + mp[v] = []; + } + } + return ans; + } +} diff --git a/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.go b/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.go new file mode 100644 index 00000000..dc56f97c --- /dev/null +++ b/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.go @@ -0,0 +1,12 @@ +func groupThePeople(groupSizes []int) [][]int { + ans := [][]int{} + mp := map[int][]int{} + for i, v := range groupSizes { + mp[v] = append(mp[v], i) + if len(mp[v]) == v { + ans = append(ans, mp[v]) + mp[v] = []int{} + } + } + return ans +} diff --git a/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.java b/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.java new file mode 100644 index 00000000..861c6aba --- /dev/null +++ b/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.java @@ -0,0 +1,15 @@ +class Solution { + public List> groupThePeople(int[] groupSizes) { + List> ans = new ArrayList<>(); + Map> mp = new HashMap<>(); + for (int i = 0; i < groupSizes.length; i++) { + int val = groupSizes[i]; + mp.computeIfAbsent(val, k -> new ArrayList<>()).add(i); + if (mp.get(val).size() == val) { + ans.add(mp.get(val)); + mp.put(val, new ArrayList<>()); + } + } + return ans; + } +} diff --git a/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.kt b/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.kt new file mode 100644 index 00000000..b9a2ea48 --- /dev/null +++ b/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun groupThePeople(groupSizes: IntArray): List> { + val ans = mutableListOf>() + val mp = mutableMapOf>() + for (i in groupSizes.indices) { + val v = groupSizes[i] + val list = mp.getOrPut(v) { mutableListOf() } + list.add(i) + if (list.size == v) { + ans.add(list.toList()) + mp[v] = mutableListOf() + } + } + return ans + } +} diff --git a/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.py b/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.py new file mode 100644 index 00000000..93d7fb57 --- /dev/null +++ b/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.py @@ -0,0 +1,11 @@ +class Solution: + def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]: + ans = [] + mp = defaultdict(list) + for i, val in enumerate(groupSizes): + if len(mp[val]) < val: + mp[val].append(i) + if len(mp[val]) == val: + ans.append(mp[val]) + mp[val] = [] + return ans diff --git a/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.py2 b/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.py2 new file mode 100644 index 00000000..21b6e558 --- /dev/null +++ b/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def groupThePeople(self, groupSizes): + """ + :type groupSizes: List[int] + :rtype: List[List[int]] + """ + from collections import defaultdict + ans = [] + mp = defaultdict(list) + for i, val in enumerate(groupSizes): + if len(mp[val]) < val: + mp[val].append(i) + if len(mp[val]) == val: + ans.append(mp[val]) + mp[val] = [] + return ans diff --git a/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.rb b/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.rb new file mode 100644 index 00000000..f3fadece --- /dev/null +++ b/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.rb @@ -0,0 +1,16 @@ +# @param {Integer[]} group_sizes +# @return {Integer[][]} +def group_the_people(group_sizes) + ans = [] + mp = Hash.new { |h, k| h[k] = [] } + group_sizes.each_with_index do |val, i| + if mp[val].length < val + mp[val] << i + if mp[val].length == val + ans << mp[val] + mp[val] = [] + end + end + end + ans +end diff --git a/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.rs b/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.rs new file mode 100644 index 00000000..6a63829c --- /dev/null +++ b/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn group_the_people(group_sizes: Vec) -> Vec> { + use std::collections::HashMap; + let mut ans: Vec> = Vec::new(); + let mut mp: HashMap> = HashMap::new(); + for (i, &v) in group_sizes.iter().enumerate() { + let list = mp.entry(v).or_insert_with(Vec::new); + list.push(i as i32); + if list.len() == v as usize { + ans.push(list.clone()); + mp.insert(v, Vec::new()); + } + } + ans + } +} diff --git a/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.swift b/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.swift new file mode 100644 index 00000000..0bf40c81 --- /dev/null +++ b/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.swift @@ -0,0 +1,14 @@ +class Solution { + func groupThePeople(_ groupSizes: [Int]) -> [[Int]] { + var ans: [[Int]] = [] + var mp: [Int: [Int]] = [:] + for (i, v) in groupSizes.enumerated() { + mp[v, default: []].append(i) + if mp[v]!.count == v { + ans.append(mp[v]!) + mp[v] = [] + } + } + return ans + } +} diff --git a/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.ts b/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.ts new file mode 100644 index 00000000..80100fd8 --- /dev/null +++ b/tests/1001-1500/1282. group-the-people-given-the-group-size-they-belong-to/sol.ts @@ -0,0 +1,15 @@ +function groupThePeople(groupSizes: number[]): number[][] { + const ans: number[][] = []; + const mp: Map = new Map(); + for (let i = 0; i < groupSizes.length; i++) { + const v = groupSizes[i]; + if (!mp.has(v)) mp.set(v, []); + const list = mp.get(v)!; + list.push(i); + if (list.length === v) { + ans.push([...list]); + mp.set(v, []); + } + } + return ans; +} diff --git a/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/manifest.yaml b/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/manifest.yaml new file mode 100644 index 00000000..2e03a612 --- /dev/null +++ b/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/manifest.yaml @@ -0,0 +1,296 @@ +entry: + id: 1283 + title: "find-the-smallest-divisor-given-a-threshold" + params: + nums: + type: array + items: + type: int + threshold: + type: int + call: + cpp: "Solution().smallestDivisor({nums}, {threshold})" + rust: "Solution::smallest_divisor({nums}, {threshold})" + python3: "Solution().smallestDivisor({nums}, {threshold})" + python2: "Solution().smallestDivisor({nums}, {threshold})" + ruby: "smallest_divisor({nums}, {threshold})" + java: "new Solution().smallestDivisor({nums}, {threshold})" + csharp: "new Solution().SmallestDivisor({nums}, {threshold})" + kotlin: "Solution().smallestDivisor({nums}, {threshold})" + go: "smallestDivisor({nums}, {threshold})" + dart: "Solution().smallestDivisor({nums}, {threshold})" + swift: "Solution().smallestDivisor({nums}, {threshold})" + typescript: "smallestDivisor({nums}, {threshold})" + +judge: + type: "exact" + +limits: + time_ms: 2500 + memory_mb: 256 + +oracle: + python3: + call: "Checker().smallestDivisor(nums, threshold, {result})" + checker: | + class Checker: + def smallestDivisor(self, nums, threshold, result): + if isinstance(result, bool) or not isinstance(result, int): + return False + if result < 1 or result > max(nums): + return False + total = sum((value + result - 1) // result for value in nums) + if total > threshold: + return False + if result == 1: + return True + previous_total = sum( + (value + result - 2) // (result - 1) for value in nums + ) + return previous_total > threshold + +seed: 1283 + +tests: + - name: "example-one" + in: + nums: [1, 2, 5, 9] + threshold: 6 + out: 5 + - name: "example-two" + in: + nums: [44, 22, 33, 11, 1] + threshold: 5 + out: 44 + - name: "single-exact" + in: + nums: [10] + threshold: 1 + out: 10 + - name: "single-loose" + in: + nums: [10] + threshold: 10 + out: 1 + - name: "all-ones" + in: + nums: [1, 1, 1, 1] + threshold: 4 + out: 1 + - name: "threshold-length" + in: + nums: [10, 20, 30, 40] + threshold: 4 + out: 40 + - name: "threshold-large" + in: + nums: [10, 20, 30, 40] + threshold: 40 + out: 3 + - name: "ceil-boundary" + in: + nums: [7, 10] + threshold: 6 + out: 4 + - name: "equal-values" + in: + nums: [100, 100, 100] + threshold: 6 + out: 50 + - name: "large-single" + in: + nums: [1000000] + threshold: 1 + out: 1000000 + - name: "large-four" + in: + nums: [1000000, 999999, 500000, 1] + threshold: 4 + out: 1000000 + - name: "mixed-small" + in: + nums: [2, 3, 5, 7, 11] + threshold: 10 + out: 4 + - name: "tight-threshold" + in: + nums: [9, 9, 9] + threshold: 4 + out: 9 + - name: "moderate-threshold" + in: + nums: [9, 9, 9] + threshold: 9 + out: 3 + - name: "powers" + in: + nums: [1, 2, 4, 8, 16, 32] + threshold: 12 + out: 8 + - name: "duplicates-and-one" + in: + nums: [100, 100, 100, 1] + threshold: 7 + out: 50 + - name: "divisor-one" + in: + nums: [1, 2, 3, 4, 5] + threshold: 15 + out: 1 + - name: "divisor-maximum" + in: + nums: [6, 6, 6] + threshold: 3 + out: 6 + - name: "odd-ceilings" + in: + nums: [5, 6, 7, 8] + threshold: 8 + out: 4 + - name: "even-ceilings" + in: + nums: [10, 12, 14, 16] + threshold: 8 + out: 8 + - name: "wide-range" + in: + nums: [1, 100, 1000, 10000] + threshold: 10 + out: 1429 + - name: "many-small" + in: + nums: [2, 2, 2, 3, 3, 3, 4, 4] + threshold: 12 + out: 3 + - name: "near-max-values" + in: + nums: [999990, 999991, 999999, 1000000] + threshold: 10 + out: 499996 + - name: "threshold-just-feasible" + in: + nums: [8, 8, 8, 8] + threshold: 5 + out: 8 + - name: "single-two" + in: + nums: [2] + threshold: 1 + out: 2 + - name: "single-prime" + in: + nums: [997] + threshold: 1 + out: 997 + - name: "balanced" + in: + nums: [25, 25, 25, 25, 25] + threshold: 10 + out: 13 + - name: "ascending" + in: + nums: [3, 8, 15, 24, 35] + threshold: 12 + out: 8 + - name: "descending" + in: + nums: [100, 81, 64, 49, 36] + threshold: 15 + out: 25 + - name: "large-threshold" + in: + nums: [100, 200, 300, 400, 500] + threshold: 1000 + out: 2 + - name: "one-large-many-ones" + in: + nums: [19, 1, 1, 1] + threshold: 7 + out: 5 + - name: "multiple-ceiling-transitions" + in: + nums: [12, 13, 24] + threshold: 7 + out: 8 + - name: "skewed-near-multiple" + in: + nums: [1, 1, 1, 999999] + threshold: 10 + out: 142857 + - name: "large-prime-with-small-values" + in: + nums: [999983, 2, 2] + threshold: 5 + out: 333328 + - name: "stress-full-range-tight" + seed: 128301 + in: + nums: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 1000000 + elemType: "int" + threshold: 50000 + - name: "stress-full-range-moderate" + seed: 128302 + in: + nums: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 1000000 + elemType: "int" + threshold: 100000 + - name: "stress-high-values-tight" + seed: 128303 + in: + nums: + gen: "array" + len: 50000 + of: + gen: "int" + min: 900000 + max: 1000000 + elemType: "int" + threshold: 75000 + - name: "stress-small-values-loose" + seed: 128304 + in: + nums: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 20 + elemType: "int" + threshold: 250000 + - name: "stress-upper-band" + seed: 128305 + in: + nums: + gen: "array" + len: 50000 + of: + gen: "int" + min: 999001 + max: 1000000 + elemType: "int" + threshold: 150000 + - name: "stress-full-range-loose" + seed: 128306 + in: + nums: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 1000000 + elemType: "int" + threshold: 1000000 diff --git a/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.cpp b/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.cpp new file mode 100644 index 00000000..ac6222d4 --- /dev/null +++ b/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int smallestDivisor(vector& nums, int threshold) { + int low = 1; + int high = *max_element(nums.begin(), nums.end()); + int ans = high; + + while (low <= high) { + int mid = low + (high - low) / 2; + + int total = 0; + for (int num : nums) { + total += (num + mid - 1) / mid; + } + + if (total <= threshold) { + ans = mid; + high = mid - 1; + } else { + low = mid + 1; + } + } + + return ans; + } +}; diff --git a/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.cs b/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.cs new file mode 100644 index 00000000..74da55ba --- /dev/null +++ b/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.cs @@ -0,0 +1,25 @@ +public class Solution { + public int SmallestDivisor(int[] nums, int threshold) { + int low = 1; + int high = nums.Max(); + int ans = high; + + while (low <= high) { + int mid = low + (high - low) / 2; + + int total = 0; + foreach (int num in nums) { + total += (num + mid - 1) / mid; + } + + if (total <= threshold) { + ans = mid; + high = mid - 1; + } else { + low = mid + 1; + } + } + + return ans; + } +} diff --git a/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.dart b/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.dart new file mode 100644 index 00000000..c50bf0ce --- /dev/null +++ b/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.dart @@ -0,0 +1,25 @@ +class Solution { + int smallestDivisor(List nums, int threshold) { + int low = 1; + int high = nums.reduce((a, b) => a > b ? a : b); + int ans = high; + + while (low <= high) { + int mid = low + (high - low) ~/ 2; + + int total = 0; + for (int num in nums) { + total += (num + mid - 1) ~/ mid; + } + + if (total <= threshold) { + ans = mid; + high = mid - 1; + } else { + low = mid + 1; + } + } + + return ans; + } +} diff --git a/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.go b/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.go new file mode 100644 index 00000000..8e528a39 --- /dev/null +++ b/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.go @@ -0,0 +1,28 @@ +func smallestDivisor(nums []int, threshold int) int { + low := 1 + high := 0 + for _, num := range nums { + if num > high { + high = num + } + } + ans := high + + for low <= high { + mid := low + (high - low) / 2 + + total := 0 + for _, num := range nums { + total += (num + mid - 1) / mid + } + + if total <= threshold { + ans = mid + high = mid - 1 + } else { + low = mid + 1 + } + } + + return ans +} diff --git a/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.java b/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.java new file mode 100644 index 00000000..7517a817 --- /dev/null +++ b/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.java @@ -0,0 +1,28 @@ +class Solution { + public int smallestDivisor(int[] nums, int threshold) { + int low = 1; + int high = 0; + for (int num : nums) { + if (num > high) high = num; + } + int ans = high; + + while (low <= high) { + int mid = low + (high - low) / 2; + + int total = 0; + for (int num : nums) { + total += (num + mid - 1) / mid; + } + + if (total <= threshold) { + ans = mid; + high = mid - 1; + } else { + low = mid + 1; + } + } + + return ans; + } +} diff --git a/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.kt b/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.kt new file mode 100644 index 00000000..9b6f9ca4 --- /dev/null +++ b/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.kt @@ -0,0 +1,25 @@ +class Solution { + fun smallestDivisor(nums: IntArray, threshold: Int): Int { + var low = 1 + var high = nums.max() + var ans = high + + while (low <= high) { + val mid = low + (high - low) / 2 + + var total = 0 + for (num in nums) { + total += (num + mid - 1) / mid + } + + if (total <= threshold) { + ans = mid + high = mid - 1 + } else { + low = mid + 1 + } + } + + return ans + } +} diff --git a/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.py b/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.py new file mode 100644 index 00000000..ad09ee7c --- /dev/null +++ b/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.py @@ -0,0 +1,20 @@ +class Solution: + def smallestDivisor(self, nums, threshold): + low = 1 + high = max(nums) + ans = high + + while low <= high: + mid = low + (high - low) // 2 + + total = 0 + for num in nums: + total += (num + mid - 1) // mid + + if total <= threshold: + ans = mid + high = mid - 1 + else: + low = mid + 1 + + return ans diff --git a/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.py2 b/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.py2 new file mode 100644 index 00000000..d168b53b --- /dev/null +++ b/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.py2 @@ -0,0 +1,25 @@ +class Solution(object): + def smallestDivisor(self, nums, threshold): + """ + :type nums: List[int] + :type threshold: int + :rtype: int + """ + low = 1 + high = max(nums) + ans = high + + while low <= high: + mid = low + (high - low) // 2 + + total = 0 + for num in nums: + total += (num + mid - 1) // mid + + if total <= threshold: + ans = mid + high = mid - 1 + else: + low = mid + 1 + + return ans diff --git a/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.rb b/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.rb new file mode 100644 index 00000000..5f79cda2 --- /dev/null +++ b/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.rb @@ -0,0 +1,26 @@ +# @param {Integer[]} nums +# @param {Integer} threshold +# @return {Integer} +def smallest_divisor(nums, threshold) + low = 1 + high = nums.max + ans = high + + while low <= high + mid = low + (high - low) / 2 + + total = 0 + nums.each do |num| + total += (num + mid - 1) / mid + end + + if total <= threshold + ans = mid + high = mid - 1 + else + low = mid + 1 + end + end + + ans +end diff --git a/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.rs b/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.rs new file mode 100644 index 00000000..b1c8e4c2 --- /dev/null +++ b/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.rs @@ -0,0 +1,25 @@ +impl Solution { + pub fn smallest_divisor(nums: Vec, threshold: i32) -> i32 { + let mut low = 1; + let mut high = *nums.iter().max().unwrap(); + let mut ans = high; + + while low <= high { + let mid = low + (high - low) / 2; + + let mut total: i64 = 0; + for &num in &nums { + total += ((num as i64 + mid as i64 - 1) / mid as i64); + } + + if total <= threshold as i64 { + ans = mid; + high = mid - 1; + } else { + low = mid + 1; + } + } + + ans + } +} diff --git a/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.swift b/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.swift new file mode 100644 index 00000000..7147ec45 --- /dev/null +++ b/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.swift @@ -0,0 +1,25 @@ +class Solution { + func smallestDivisor(_ nums: [Int], _ threshold: Int) -> Int { + var low = 1 + var high = nums.max()! + var ans = high + + while low <= high { + let mid = low + (high - low) / 2 + + var total = 0 + for num in nums { + total += (num + mid - 1) / mid + } + + if total <= threshold { + ans = mid + high = mid - 1 + } else { + low = mid + 1 + } + } + + return ans + } +} diff --git a/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.ts b/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.ts new file mode 100644 index 00000000..92bd5a98 --- /dev/null +++ b/tests/1001-1500/1283. find-the-smallest-divisor-given-a-threshold/sol.ts @@ -0,0 +1,23 @@ +function smallestDivisor(nums: number[], threshold: number): number { + let low = 1; + let high = Math.max(...nums); + let ans = high; + + while (low <= high) { + let mid = low + Math.floor((high - low) / 2); + + let total = 0; + for (let num of nums) { + total += Math.ceil(num / mid); + } + + if (total <= threshold) { + ans = mid; + high = mid - 1; + } else { + low = mid + 1; + } + } + + return ans; +} diff --git a/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/manifest.yaml b/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/manifest.yaml new file mode 100644 index 00000000..9dd98434 --- /dev/null +++ b/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/manifest.yaml @@ -0,0 +1,393 @@ +entry: + id: 1284 + title: "minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix" + params: + mat: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().minFlips({mat})" + rust: "Solution::min_flips({mat})" + python3: "Solution().minFlips({mat})" + python2: "Solution().minFlips({mat})" + ruby: "min_flips({mat})" + java: "new Solution().minFlips({mat})" + csharp: "new Solution().MinFlips({mat})" + kotlin: "Solution().minFlips({mat})" + go: "minFlips({mat})" + dart: "Solution().minFlips({mat})" + swift: "Solution().minFlips({mat})" + typescript: "minFlips({mat})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().minFlips(mat, {result})" + checker: | + from collections import deque + + class Checker: + def minFlips(self, mat, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + rows, cols = len(mat), len(mat[0]) + start = 0 + for row in range(rows): + for col in range(cols): + start |= mat[row][col] << (row * cols + col) + moves = [] + for row in range(rows): + for col in range(cols): + mask = 0 + for dr, dc in ((0, 0), (1, 0), (-1, 0), (0, 1), (0, -1)): + rr, cc = row + dr, col + dc + if 0 <= rr < rows and 0 <= cc < cols: + mask |= 1 << (rr * cols + cc) + moves.append(mask) + queue = deque([(start, 0)]) + seen = {start} + while queue: + state, steps = queue.popleft() + if state == 0: + return result == steps + for move in moves: + nxt = state ^ move + if nxt not in seen: + seen.add(nxt) + queue.append((nxt, steps + 1)) + return result == -1 + +seed: 1284 + +tests: + - name: "example-one" + in: + mat: + - [0, 0] + - [0, 1] + out: 3 + - name: "example-two" + in: + mat: + - [0] + out: 0 + - name: "example-three-unreachable" + in: + mat: + - [1, 0, 0] + - [1, 0, 0] + out: -1 + - name: "one-by-one-one" + in: + mat: + - [1] + out: 1 + - name: "one-by-two-leading-one-unreachable" + in: + mat: + - [1, 0] + out: -1 + - name: "one-by-two-all-ones" + in: + mat: + - [1, 1] + out: 1 + - name: "one-by-three-middle" + in: + mat: + - [0, 1, 0] + out: 3 + - name: "one-by-three-all-ones" + in: + mat: + - [1, 1, 1] + out: 1 + - name: "two-by-two-single-corner" + in: + mat: + - [1, 0] + - [0, 0] + out: 3 + - name: "two-by-two-all-ones" + in: + mat: + - [1, 1] + - [1, 1] + out: 4 + - name: "two-by-two-main-diagonal" + in: + mat: + - [1, 0] + - [0, 1] + out: 2 + - name: "two-by-two-anti-diagonal" + in: + mat: + - [0, 1] + - [1, 0] + out: 2 + - name: "two-by-three-single-corner-unreachable" + in: + mat: + - [1, 0, 0] + - [0, 0, 0] + out: -1 + - name: "two-by-three-corners" + in: + mat: + - [1, 0, 1] + - [1, 0, 1] + out: 2 + - name: "two-by-three-center-column" + in: + mat: + - [0, 1, 0] + - [0, 1, 0] + out: 2 + - name: "two-by-three-all-ones" + in: + mat: + - [1, 1, 1] + - [1, 1, 1] + out: 2 + - name: "two-by-three-asymmetric" + in: + mat: + - [1, 1, 0] + - [0, 0, 1] + out: 2 + - name: "two-by-three-zero" + in: + mat: + - [0, 0, 0] + - [0, 0, 0] + out: 0 + - name: "three-by-one-top" + in: + mat: + - [1] + - [0] + - [0] + out: 2 + - name: "three-by-one-all-ones" + in: + mat: + - [1] + - [1] + - [1] + out: 1 + - name: "three-by-two-single-corner-unreachable" + in: + mat: + - [1, 0] + - [0, 0] + - [0, 0] + out: -1 + - name: "three-by-two-opposite-corners-unreachable" + in: + mat: + - [1, 0] + - [0, 0] + - [0, 1] + out: -1 + - name: "three-by-two-middle-row" + in: + mat: + - [0, 0] + - [1, 1] + - [0, 0] + out: 2 + - name: "three-by-two-all-ones" + in: + mat: + - [1, 1] + - [1, 1] + - [1, 1] + out: 2 + - name: "three-by-three-zero" + in: + mat: + - [0, 0, 0] + - [0, 0, 0] + - [0, 0, 0] + out: 0 + - name: "three-by-three-single-corner" + in: + mat: + - [1, 0, 0] + - [0, 0, 0] + - [0, 0, 0] + out: 5 + - name: "three-by-three-center" + in: + mat: + - [0, 0, 0] + - [0, 1, 0] + - [0, 0, 0] + out: 5 + - name: "three-by-three-corners" + in: + mat: + - [1, 0, 1] + - [0, 0, 0] + - [1, 0, 1] + out: 4 + - name: "three-by-three-cross" + in: + mat: + - [0, 1, 0] + - [1, 1, 1] + - [0, 1, 0] + out: 1 + - name: "three-by-three-border" + in: + mat: + - [1, 1, 1] + - [1, 0, 1] + - [1, 1, 1] + out: 8 + - name: "three-by-three-all-ones" + in: + mat: + - [1, 1, 1] + - [1, 1, 1] + - [1, 1, 1] + out: 5 + - name: "three-by-three-checkerboard" + in: + mat: + - [1, 0, 1] + - [0, 1, 0] + - [1, 0, 1] + out: 9 + - name: "three-by-three-main-diagonal" + in: + mat: + - [1, 0, 0] + - [0, 1, 0] + - [0, 0, 1] + out: 3 + - name: "three-by-three-horizontal-stripes" + in: + mat: + - [1, 1, 1] + - [0, 0, 0] + - [1, 1, 1] + out: 2 + - name: "generated-one-by-three" + seed: 128401 + in: + mat: + gen: "array" + len: 1 + elemType: "int" + distinct: false + sorted: false + of: + gen: "array" + len: 3 + distinct: false + sorted: false + of: + gen: "int" + min: 0 + max: 1 + - name: "generated-two-by-two" + seed: 128402 + in: + mat: + gen: "array" + len: 2 + elemType: "int" + distinct: false + sorted: false + of: + gen: "array" + len: 2 + distinct: false + sorted: false + of: + gen: "int" + min: 0 + max: 1 + - name: "generated-two-by-three" + seed: 128403 + in: + mat: + gen: "array" + len: 2 + elemType: "int" + distinct: false + sorted: false + of: + gen: "array" + len: 3 + distinct: false + sorted: false + of: + gen: "int" + min: 0 + max: 1 + - name: "generated-three-by-one" + seed: 128404 + in: + mat: + gen: "array" + len: 3 + elemType: "int" + distinct: false + sorted: false + of: + gen: "array" + len: 1 + distinct: false + sorted: false + of: + gen: "int" + min: 0 + max: 1 + - name: "generated-three-by-two" + seed: 128405 + in: + mat: + gen: "array" + len: 3 + elemType: "int" + distinct: false + sorted: false + of: + gen: "array" + len: 2 + distinct: false + sorted: false + of: + gen: "int" + min: 0 + max: 1 + - name: "generated-three-by-three" + seed: 128406 + in: + mat: + gen: "array" + len: 3 + elemType: "int" + distinct: false + sorted: false + of: + gen: "array" + len: 3 + distinct: false + sorted: false + of: + gen: "int" + min: 0 + max: 1 diff --git a/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.cpp b/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.cpp new file mode 100644 index 00000000..71534611 --- /dev/null +++ b/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.cpp @@ -0,0 +1,65 @@ +#include +using namespace std; + +class Solution { +public: + int minFlips(vector>& mat) { + int m = (int)mat.size(); + int n = (int)mat[0].size(); + vector masks; + masks.reserve(m * n); + static const int dirs[5][2] = { + {0, 0}, + {1, 0}, + {-1, 0}, + {0, 1}, + {0, -1}, + }; + + for (int r = 0; r < m; ++r) { + for (int c = 0; c < n; ++c) { + int mask = 0; + for (const auto& d : dirs) { + int dr = d[0]; + int dc = d[1]; + int nr = r + dr, nc = c + dc; + if (0 <= nr && nr < m && 0 <= nc && nc < n) { + mask |= 1 << (nr * n + nc); + } + } + masks.push_back(mask); + } + } + + int start = 0; + for (int r = 0; r < m; ++r) { + for (int c = 0; c < n; ++c) { + if (mat[r][c]) { + start |= 1 << (r * n + c); + } + } + } + + queue> q; + vector dist(1 << (m * n), -1); + dist[start] = 0; + q.push({start, 0}); + + while (!q.empty()) { + auto [state, steps] = q.front(); + q.pop(); + if (state == 0) { + return steps; + } + for (int mask : masks) { + int next = state ^ mask; + if (dist[next] == -1) { + dist[next] = steps + 1; + q.push({next, steps + 1}); + } + } + } + + return -1; + } +}; diff --git a/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.cs b/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.cs new file mode 100644 index 00000000..d9ed4b82 --- /dev/null +++ b/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.cs @@ -0,0 +1,72 @@ +using System; +using System.Collections.Generic; + +public class Solution +{ + public int MinFlips(int[][] mat) + { + int m = mat.Length; + int n = mat[0].Length; + var masks = new List(m * n); + int[,] dirs = new int[,] { { 0, 0 }, { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } }; + + for (int r = 0; r < m; ++r) + { + for (int c = 0; c < n; ++c) + { + int mask = 0; + for (int i = 0; i < 5; ++i) + { + int nr = r + dirs[i, 0]; + int nc = c + dirs[i, 1]; + if (0 <= nr && nr < m && 0 <= nc && nc < n) + { + mask |= 1 << (nr * n + nc); + } + } + masks.Add(mask); + } + } + + int start = 0; + for (int r = 0; r < m; ++r) + { + for (int c = 0; c < n; ++c) + { + if (mat[r][c] == 1) + { + start |= 1 << (r * n + c); + } + } + } + + int size = 1 << (m * n); + int[] dist = new int[size]; + Array.Fill(dist, -1); + var q = new Queue(); + dist[start] = 0; + q.Enqueue(start); + + while (q.Count > 0) + { + int state = q.Dequeue(); + int steps = dist[state]; + if (state == 0) + { + return steps; + } + + foreach (int mask in masks) + { + int next = state ^ mask; + if (dist[next] == -1) + { + dist[next] = steps + 1; + q.Enqueue(next); + } + } + } + + return -1; + } +} diff --git a/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.dart b/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.dart new file mode 100644 index 00000000..b4a4ae60 --- /dev/null +++ b/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.dart @@ -0,0 +1,59 @@ +class Solution { + int minFlips(List> mat) { + final m = mat.length; + final n = mat[0].length; + final masks = []; + const dirs = [ + [0, 0], + [1, 0], + [-1, 0], + [0, 1], + [0, -1], + ]; + + for (var r = 0; r < m; r++) { + for (var c = 0; c < n; c++) { + var mask = 0; + for (final d in dirs) { + final nr = r + d[0]; + final nc = c + d[1]; + if (nr >= 0 && nr < m && nc >= 0 && nc < n) { + mask |= 1 << (nr * n + nc); + } + } + masks.add(mask); + } + } + + var start = 0; + for (var r = 0; r < m; r++) { + for (var c = 0; c < n; c++) { + if (mat[r][c] == 1) { + start |= 1 << (r * n + c); + } + } + } + + final size = 1 << (m * n); + final dist = List.filled(size, -1); + final q = [start]; + dist[start] = 0; + + for (var head = 0; head < q.length; head++) { + final state = q[head]; + final steps = dist[state]; + if (state == 0) { + return steps; + } + for (final mask in masks) { + final next = state ^ mask; + if (dist[next] == -1) { + dist[next] = steps + 1; + q.add(next); + } + } + } + + return -1; + } +} diff --git a/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.go b/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.go new file mode 100644 index 00000000..0293b477 --- /dev/null +++ b/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.go @@ -0,0 +1,54 @@ +func minFlips(mat [][]int) int { + m := len(mat) + n := len(mat[0]) + masks := make([]int, 0, m*n) + dirs := [5][2]int{{0, 0}, {1, 0}, {-1, 0}, {0, 1}, {0, -1}} + + for r := 0; r < m; r++ { + for c := 0; c < n; c++ { + mask := 0 + for _, d := range dirs { + nr, nc := r+d[0], c+d[1] + if 0 <= nr && nr < m && 0 <= nc && nc < n { + mask |= 1 << (nr*n + nc) + } + } + masks = append(masks, mask) + } + } + + start := 0 + for r := 0; r < m; r++ { + for c := 0; c < n; c++ { + if mat[r][c] == 1 { + start |= 1 << (r*n + c) + } + } + } + + size := 1 << (m * n) + dist := make([]int, size) + for i := range dist { + dist[i] = -1 + } + q := make([]int, 1, size) + q[0] = start + dist[start] = 0 + + for head := 0; head < len(q); head++ { + state := q[head] + steps := dist[state] + if state == 0 { + return steps + } + for _, mask := range masks { + next := state ^ mask + if dist[next] == -1 { + dist[next] = steps + 1 + q = append(q, next) + } + } + } + + return -1 +} diff --git a/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.java b/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.java new file mode 100644 index 00000000..2a8e92f2 --- /dev/null +++ b/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.java @@ -0,0 +1,60 @@ +import java.util.ArrayDeque; +import java.util.ArrayList; + +class Solution { + public int minFlips(int[][] mat) { + int m = mat.length; + int n = mat[0].length; + ArrayList masks = new ArrayList<>(m * n); + + int[][] dirs = new int[][]{{0, 0}, {1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + for (int r = 0; r < m; ++r) { + for (int c = 0; c < n; ++c) { + int mask = 0; + for (int[] d : dirs) { + int nr = r + d[0]; + int nc = c + d[1]; + if (0 <= nr && nr < m && 0 <= nc && nc < n) { + mask |= 1 << (nr * n + nc); + } + } + masks.add(mask); + } + } + + int start = 0; + for (int r = 0; r < m; ++r) { + for (int c = 0; c < n; ++c) { + if (mat[r][c] == 1) { + start |= 1 << (r * n + c); + } + } + } + + int size = 1 << (m * n); + int[] dist = new int[size]; + for (int i = 0; i < size; ++i) { + dist[i] = -1; + } + ArrayDeque q = new ArrayDeque<>(); + dist[start] = 0; + q.add(start); + + while (!q.isEmpty()) { + int state = q.removeFirst(); + int steps = dist[state]; + if (state == 0) { + return steps; + } + for (int mask : masks) { + int next = state ^ mask; + if (dist[next] == -1) { + dist[next] = steps + 1; + q.addLast(next); + } + } + } + + return -1; + } +} diff --git a/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.kt b/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.kt new file mode 100644 index 00000000..43bbc06f --- /dev/null +++ b/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.kt @@ -0,0 +1,64 @@ +import java.util.ArrayDeque + +class Solution { + fun minFlips(mat: Array): Int { + val m = mat.size + val n = mat[0].size + val masks = IntArray(m * n) + var p = 0 + + val dirs = arrayOf( + intArrayOf(0, 0), + intArrayOf(1, 0), + intArrayOf(-1, 0), + intArrayOf(0, 1), + intArrayOf(0, -1) + ) + + for (r in 0 until m) { + for (c in 0 until n) { + var mask = 0 + for (d in dirs) { + val nr = r + d[0] + val nc = c + d[1] + if (nr in 0 until m && nc in 0 until n) { + mask = mask or (1 shl (nr * n + nc)) + } + } + masks[p++] = mask + } + } + + var start = 0 + for (r in 0 until m) { + for (c in 0 until n) { + if (mat[r][c] == 1) { + start = start or (1 shl (r * n + c)) + } + } + } + + val size = 1 shl (m * n) + val dist = IntArray(size) { -1 } + val q = ArrayDeque() + dist[start] = 0 + q.addLast(start) + + while (q.isNotEmpty()) { + val state = q.removeFirst() + val steps = dist[state] + if (state == 0) { + return steps + } + for (mask in masks) { + val next = state xor mask + if (dist[next] == -1) { + dist[next] = steps + 1 + q.addLast(next) + } + } + } + + return -1 + } +} diff --git a/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.py b/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.py new file mode 100644 index 00000000..0000fa32 --- /dev/null +++ b/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.py @@ -0,0 +1,67 @@ +import numpy as np +from itertools import product + + +class Solution: + def minFlips(self, mat: list[list[int]]) -> int: + m, n = len(mat), len(mat[0]) + N = m * n + A = np.zeros((N, N), dtype=np.int32) + b = np.array(mat).flatten() + + # 1. Build Adjacency + for r in range(m): + for c in range(n): + idx = r * n + c + for dr, dc in [(0, 0), (0, 1), (0, -1), (1, 0), (-1, 0)]: + nr, nc = r + dr, c + dc + if 0 <= nr < m and 0 <= nc < n: + A[nr * n + nc, idx] = 1 + + # 2. Gaussian Elimination to find Row Echelon Form + matrix = np.hstack((A, b.reshape(-1, 1))) + pivot_row = 0 + pivot_cols = [] + for col in range(N): + sel = np.where(matrix[pivot_row:, col] == 1)[0] + if sel.size > 0: + i = sel[0] + pivot_row + matrix[[pivot_row, i]] = matrix[[i, pivot_row]] + # Eliminate all other 1s in this column + for r_idx in range(N): + if r_idx != pivot_row and matrix[r_idx, col] == 1: + matrix[r_idx] ^= matrix[pivot_row] + pivot_cols.append(col) + pivot_row += 1 + + # 3. Feasibility Check + for i in range(pivot_row, N): + if matrix[i, -1] == 1: + return -1 + + # 4. Particular Solution + x_p = np.zeros(N, dtype=np.int32) + for i, col in enumerate(pivot_cols): + x_p[col] = matrix[i, -1] + + # 5. Basis for Null Space + free_cols = [c for c in range(N) if c not in pivot_cols] + null_basis = [] + for f_col in free_cols: + vec = np.zeros(N, dtype=np.int32) + vec[f_col] = 1 + for i, p_col in enumerate(pivot_cols): + if matrix[i, f_col] == 1: + vec[p_col] = 1 + null_basis.append(vec) + + # 6. Minimize Hamming Weight (x_p ^ any combo of null_basis) + min_steps = float("inf") + for combo in product([0, 1], repeat=len(null_basis)): + sol = x_p.copy() + for bit, base_vec in zip(combo, null_basis): + if bit: + sol ^= base_vec + min_steps = min(min_steps, np.sum(sol)) + + return int(min_steps) if min_steps != float("inf") else -1 diff --git a/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.py2 b/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.py2 new file mode 100644 index 00000000..2506b27e --- /dev/null +++ b/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.py2 @@ -0,0 +1,41 @@ +from collections import deque + + +class Solution(object): + def minFlips(self, mat): + m = len(mat) + n = len(mat[0]) + masks = [] + + for r in range(m): + for c in range(n): + mask = 0 + for dr, dc in ((0, 0), (1, 0), (-1, 0), (0, 1), (0, -1)): + nr = r + dr + nc = c + dc + if 0 <= nr < m and 0 <= nc < n: + mask |= 1 << (nr * n + nc) + masks.append(mask) + + start = 0 + for r in range(m): + for c in range(n): + if mat[r][c]: + start |= 1 << (r * n + c) + + dist = [-1] * (1 << (m * n)) + dist[start] = 0 + q = deque([start]) + + while q: + state = q.popleft() + steps = dist[state] + if state == 0: + return steps + for mask in masks: + nxt = state ^ mask + if dist[nxt] == -1: + dist[nxt] = steps + 1 + q.append(nxt) + + return -1 diff --git a/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.rb b/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.rb new file mode 100644 index 00000000..7dd1f957 --- /dev/null +++ b/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.rb @@ -0,0 +1,48 @@ +require 'set' + +def min_flips(mat) + m = mat.length + n = mat[0].length + masks = [] + + m.times do |r| + n.times do |c| + mask = 0 + [[0, 0], [1, 0], [-1, 0], [0, 1], [0, -1]].each do |dr, dc| + nr = r + dr + nc = c + dc + if nr >= 0 && nr < m && nc >= 0 && nc < n + mask |= 1 << (nr * n + nc) + end + end + masks << mask + end + end + + start = 0 + m.times do |r| + n.times do |c| + start |= 1 << (r * n + c) if mat[r][c] == 1 + end + end + + dist = Array.new(1 << (m * n), -1) + q = [[start, 0]] + dist[start] = 0 + head = 0 + + while head < q.length + state, steps = q[head] + head += 1 + return steps if state == 0 + + masks.each do |mask| + nxt = state ^ mask + next unless dist[nxt] == -1 + dist[nxt] = steps + 1 + q << [nxt, steps + 1] + end + end + + -1 +end diff --git a/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.rs b/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.rs new file mode 100644 index 00000000..0591e119 --- /dev/null +++ b/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.rs @@ -0,0 +1,54 @@ +use std::collections::VecDeque; + +impl Solution { + pub fn min_flips(mat: Vec>) -> i32 { + let m = mat.len(); + let n = mat[0].len(); + let mut masks = Vec::with_capacity(m * n); + + for r in 0..m { + for c in 0..n { + let mut mask = 0usize; + for (dr, dc) in [(0isize, 0isize), (1, 0), (-1, 0), (0, 1), (0, -1)] { + let nr = r as isize + dr; + let nc = c as isize + dc; + if nr >= 0 && nr < m as isize && nc >= 0 && nc < n as isize { + mask |= 1usize << (nr as usize * n + nc as usize); + } + } + masks.push(mask); + } + } + + let mut start = 0usize; + for r in 0..m { + for c in 0..n { + if mat[r][c] == 1 { + start |= 1usize << (r * n + c); + } + } + } + + let size = 1usize << (m * n); + let mut dist = vec![-1i32; size]; + let mut q = VecDeque::new(); + dist[start] = 0; + q.push_back(start); + + while let Some(state) = q.pop_front() { + let steps = dist[state]; + if state == 0 { + return steps; + } + for &mask in &masks { + let next = state ^ mask; + if dist[next] == -1 { + dist[next] = steps + 1; + q.push_back(next); + } + } + } + + -1 + } +} diff --git a/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.swift b/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.swift new file mode 100644 index 00000000..d91b91de --- /dev/null +++ b/tests/1001-1500/1284. minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/sol.swift @@ -0,0 +1,56 @@ +class Solution { + func minFlips(_ mat: [[Int]]) -> Int { + let m = mat.count + let n = mat[0].count + var masks = [Int]() + masks.reserveCapacity(m * n) + let dirs = [(0, 0), (1, 0), (-1, 0), (0, 1), (0, -1)] + + for r in 0..= 0 && nr < m && nc >= 0 && nc < n { + mask |= 1 << (nr * n + nc) + } + } + masks.append(mask) + } + } + + var start = 0 + for r in 0..(size).fill(-1); + const q: number[] = [start]; + dist[start] = 0; + + for (let head = 0; head < q.length; head++) { + const state = q[head]; + const steps = dist[state]; + if (state === 0) { + return steps; + } + for (const mask of masks) { + const next = state ^ mask; + if (dist[next] === -1) { + dist[next] = steps + 1; + q.push(next); + } + } + } + + return -1; +} diff --git a/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/manifest.yaml b/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/manifest.yaml new file mode 100644 index 00000000..7516dcbd --- /dev/null +++ b/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/manifest.yaml @@ -0,0 +1,628 @@ +entry: + id: 1287 + title: "element-appearing-more-than-25-in-sorted-array" + params: + arr: + type: array + items: + type: int + call: + cpp: "Solution().findSpecialInteger({arr})" + rust: "Solution::find_special_integer({arr})" + python3: "Solution().findSpecialInteger({arr})" + python2: "Solution().findSpecialInteger({arr})" + ruby: "find_special_integer({arr})" + java: "new Solution().findSpecialInteger({arr})" + csharp: "new Solution().FindSpecialInteger({arr})" + kotlin: "Solution().findSpecialInteger({arr})" + go: "findSpecialInteger({arr})" + dart: "Solution().findSpecialInteger({arr})" + swift: "Solution().findSpecialInteger({arr})" + typescript: "findSpecialInteger({arr})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().findSpecialInteger(arr, {result})" + checker: | + class Checker: + def findSpecialInteger(self, arr, result): + if any(arr[i] > arr[i + 1] for i in range(len(arr) - 1)): + return False + counts = {} + for value in arr: + counts[value] = counts.get(value, 0) + 1 + winners = [value for value, count in counts.items() if count * 4 > len(arr)] + return len(winners) == 1 and result == winners[0] + +seed: 1287 + +tests: + - name: "example-one" + in: + arr: [1, 2, 2, 6, 6, 6, 6, 7, 10] + out: 6 + - name: "example-two" + in: + arr: [1, 1] + out: 1 + - name: "single-minimum" + in: + arr: [0] + out: 0 + - name: "single-maximum" + in: + arr: [100000] + out: 100000 + - name: "two-equal" + in: + arr: [42, 42] + out: 42 + - name: "three-equal" + in: + arr: [7, 7, 7] + out: 7 + - name: "four-middle-pair" + in: + arr: [0, 1, 1, 2] + out: 1 + - name: "four-leading-pair" + in: + arr: [3, 3, 4, 5] + out: 3 + - name: "five-quarter-plus-one" + in: + arr: [0, 0, 2, 3, 4] + out: 0 + - name: "six-trailing-pair" + in: + arr: [0, 1, 2, 3, 9, 9] + out: 9 + - name: "seven-interior-pair" + in: + arr: [0, 1, 4, 4, 5, 6, 7] + out: 4 + - name: "eight-leading-three" + in: + arr: [1, 1, 1, 3, 4, 5, 6, 7] + out: 1 + - name: "nine-middle-three" + in: + arr: [0, 1, 2, 4, 4, 4, 7, 8, 9] + out: 4 + - name: "ten-trailing-three" + in: + arr: [0, 1, 2, 3, 4, 5, 6, 8, 8, 8] + out: 8 + - name: "eleven-leading-three" + in: + arr: [2, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10] + out: 2 + - name: "twelve-exact-four" + in: + arr: [0, 1, 2, 5, 5, 5, 5, 6, 7, 8, 9, 10] + out: 5 + - name: "thirteen-four-at-end" + in: + arr: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 99, 99, 99, 99] + out: 99 + - name: "fifteen-four-at-start" + in: + arr: [1, 1, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] + out: 1 + - name: "sixteen-five-middle" + in: + arr: [0, 1, 2, 3, 12, 12, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19] + out: 12 + - name: "seventeen-five-at-end" + in: + arr: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 40, 40, 40, 40, 40] + out: 40 + - name: "twenty-leading-six" + in: + arr: [0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] + out: 0 + - name: "twenty-middle-six" + in: + arr: + [ + 0, + 1, + 2, + 3, + 4, + 5, + 17, + 17, + 17, + 17, + 17, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + ] + out: 17 + - name: "twenty-trailing-six" + in: + arr: + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 90, 90, 90, 90, 90, 90] + out: 90 + - name: "twenty-competing-non-special-runs" + in: + arr: [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3] + out: 2 + - name: "twenty-five-seven-at-start" + in: + arr: + [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + ] + out: 0 + - name: "twenty-six-seven-in-center" + in: + arr: + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59, + 60, + 61, + 62, + ] + out: 50 + - name: "ninety-nine-threshold-twenty-five" + 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, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 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, + ] + out: 50 + - name: "one-hundred-threshold-twenty-six" + 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, + 77, + 77, + 77, + 77, + 77, + 77, + 77, + 77, + 77, + 77, + 77, + 77, + 77, + 77, + 77, + 77, + 77, + 77, + 77, + 77, + 77, + 77, + 77, + 77, + 77, + 77, + 77, + 77, + 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, + ] + out: 77 + - name: "special-minimum-with-high-values" + in: + arr: + [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 99990, + 99991, + 99992, + 99993, + 99994, + 99995, + 99996, + 99997, + 99998, + 99999, + 100000, + ] + out: 0 + - name: "special-maximum" + in: + arr: [0, 1, 2, 3, 4, 5, 6, 7, 100000, 100000, 100000, 100000, 100000] + out: 100000 + - name: "all-maximum" + in: + arr: [100000, 100000, 100000, 100000, 100000, 100000, 100000, 100000] + out: 100000 + - name: "twenty-four-non-special-runs" + in: + arr: + [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3] + out: 2 + - name: "twenty-four-first-valid-position" + in: + arr: + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 8, + 8, + 8, + 8, + 8, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + ] + out: 8 + - name: "thirty-two-nine-at-quarter-boundary" + in: + arr: + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 45, + 46, + 47, + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + ] + out: 44 + - name: "large-generated-zero" + seed: 2001 + in: + arr: + gen: "array" + len: 1000 + of: + gen: "int" + min: 0 + max: 0 + distinct: false + sorted: true + elemType: "int" + - name: "large-generated-one" + seed: 2002 + in: + arr: + gen: "array" + len: 4096 + of: + gen: "int" + min: 1 + max: 1 + distinct: false + sorted: true + elemType: "int" + - name: "large-generated-midpoint" + seed: 2003 + in: + arr: + gen: "array" + len: 8191 + of: + gen: "int" + min: 50000 + max: 50000 + distinct: false + sorted: true + elemType: "int" + - name: "large-generated-near-maximum-one" + seed: 2004 + in: + arr: + gen: "array" + len: 9997 + of: + gen: "int" + min: 99997 + max: 99997 + distinct: false + sorted: true + elemType: "int" + - name: "large-generated-near-maximum-two" + seed: 2005 + in: + arr: + gen: "array" + len: 9999 + of: + gen: "int" + min: 99999 + max: 99999 + distinct: false + sorted: true + elemType: "int" + - name: "large-generated-maximum" + seed: 2006 + in: + arr: + gen: "array" + len: 10000 + of: + gen: "int" + min: 100000 + max: 100000 + distinct: false + sorted: true + elemType: "int" diff --git a/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.cpp b/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.cpp new file mode 100644 index 00000000..01b35b35 --- /dev/null +++ b/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int findSpecialInteger(vector& arr) { + int n = arr.size(); + int q = n / 4; + unordered_map m; + for (int num : arr) { + m[num]++; + if (m[num] > q) { + return num; + } + } + return -1; + } +}; diff --git a/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.cs b/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.cs new file mode 100644 index 00000000..b43bbf13 --- /dev/null +++ b/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.cs @@ -0,0 +1,18 @@ +public class Solution { + public int FindSpecialInteger(int[] arr) { + int n = arr.Length; + int q = n / 4; + Dictionary m = new Dictionary(); + foreach (int num in arr) { + if (m.ContainsKey(num)) { + m[num]++; + } else { + m[num] = 1; + } + if (m[num] > q) { + return num; + } + } + return -1; + } +} diff --git a/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.dart b/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.dart new file mode 100644 index 00000000..4034ead2 --- /dev/null +++ b/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.dart @@ -0,0 +1,14 @@ +class Solution { + int findSpecialInteger(List arr) { + int n = arr.length; + int q = n ~/ 4; + Map m = {}; + for (int num in arr) { + m[num] = (m[num] ?? 0) + 1; + if (m[num]! > q) { + return num; + } + } + return -1; + } +} diff --git a/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.go b/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.go new file mode 100644 index 00000000..4841aa81 --- /dev/null +++ b/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.go @@ -0,0 +1,12 @@ +func findSpecialInteger(arr []int) int { + n := len(arr) + q := n / 4 + m := make(map[int]int) + for _, num := range arr { + m[num]++ + if m[num] > q { + return num + } + } + return -1 +} diff --git a/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.java b/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.java new file mode 100644 index 00000000..008992e3 --- /dev/null +++ b/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.java @@ -0,0 +1,14 @@ +class Solution { + public int findSpecialInteger(int[] arr) { + int n = arr.length; + int q = n / 4; + Map m = new HashMap<>(); + for (int num : arr) { + m.put(num, m.getOrDefault(num, 0) + 1); + if (m.get(num) > q) { + return num; + } + } + return -1; + } +} diff --git a/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.kt b/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.kt new file mode 100644 index 00000000..9a107b73 --- /dev/null +++ b/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.kt @@ -0,0 +1,14 @@ +class Solution { + fun findSpecialInteger(arr: IntArray): Int { + val n = arr.size + val q = n / 4 + val m = mutableMapOf() + for (num in arr) { + m[num] = m.getOrDefault(num, 0) + 1 + if (m[num]!! > q) { + return num + } + } + return -1 + } +} diff --git a/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.py b/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.py new file mode 100644 index 00000000..644ba949 --- /dev/null +++ b/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.py @@ -0,0 +1,10 @@ +class Solution: + def findSpecialInteger(self, arr: List[int]) -> int: + n = len(arr) + q = n // 4 + m = {} + for num in arr: + m[num] = m.get(num, 0) + 1 + if m[num] > q: + return num + return None diff --git a/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.py2 b/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.py2 new file mode 100644 index 00000000..b89748ff --- /dev/null +++ b/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.py2 @@ -0,0 +1,14 @@ +class Solution(object): + def findSpecialInteger(self, arr): + """ + :type arr: List[int] + :rtype: int + """ + n = len(arr) + q = n // 4 + m = {} + for num in arr: + m[num] = m.get(num, 0) + 1 + if m[num] > q: + return num + return None diff --git a/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.rb b/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.rb new file mode 100644 index 00000000..a23b9737 --- /dev/null +++ b/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.rb @@ -0,0 +1,14 @@ +# @param {Integer[]} arr +# @return {Integer} +def find_special_integer(arr) + n = arr.length + q = n / 4 + m = {} + arr.each do |num| + m[num] = (m[num] || 0) + 1 + if m[num] > q + return num + end + end + nil +end diff --git a/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.rs b/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.rs new file mode 100644 index 00000000..82db9910 --- /dev/null +++ b/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn find_special_integer(arr: Vec) -> i32 { + let n = arr.len(); + let q = n / 4; + let mut m = std::collections::HashMap::new(); + for num in arr { + let count = m.entry(num).or_insert(0); + *count += 1; + if *count > q { + return num; + } + } + -1 + } +} diff --git a/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.swift b/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.swift new file mode 100644 index 00000000..0d11e52e --- /dev/null +++ b/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.swift @@ -0,0 +1,14 @@ +class Solution { + func findSpecialInteger(_ arr: [Int]) -> Int { + let n = arr.count + let q = n / 4 + var m = [Int: Int]() + for num in arr { + m[num, default: 0] += 1 + if m[num]! > q { + return num + } + } + return -1 + } +} diff --git a/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.ts b/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.ts new file mode 100644 index 00000000..3c85b981 --- /dev/null +++ b/tests/1001-1500/1287. element-appearing-more-than-25-in-sorted-array/sol.ts @@ -0,0 +1,12 @@ +function findSpecialInteger(arr: number[]): number { + const n: number = arr.length; + const q: number = Math.floor(n / 4); + const m: Map = new Map(); + for (const num of arr) { + m.set(num, (m.get(num) || 0) + 1); + if (m.get(num)! > q) { + return num; + } + } + return -1; +} diff --git a/tests/1001-1500/1288. remove-covered-intervals/manifest.yaml b/tests/1001-1500/1288. remove-covered-intervals/manifest.yaml new file mode 100644 index 00000000..8dbf377f --- /dev/null +++ b/tests/1001-1500/1288. remove-covered-intervals/manifest.yaml @@ -0,0 +1,440 @@ +entry: + id: 1288 + title: "remove-covered-intervals" + params: + intervals: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().removeCoveredIntervals({intervals})" + rust: "Solution::remove_covered_intervals({intervals})" + python3: "Solution().removeCoveredIntervals({intervals})" + python2: "Solution().removeCoveredIntervals({intervals})" + ruby: "remove_covered_intervals({intervals})" + java: "new Solution().removeCoveredIntervals({intervals})" + csharp: "new Solution().RemoveCoveredIntervals({intervals})" + kotlin: "Solution().removeCoveredIntervals({intervals})" + go: "removeCoveredIntervals({intervals})" + dart: "Solution().removeCoveredIntervals({intervals})" + swift: "Solution().removeCoveredIntervals({intervals})" + typescript: "removeCoveredIntervals({intervals})" +judge: + type: "exact" +limits: + time_ms: 300 + memory_mb: 300 +oracle: + python3: + call: "Checker().removeCoveredIntervals(intervals, {result})" + checker: | + class Checker: + def removeCoveredIntervals(self, intervals, result): + if not isinstance(result, int): + return False + kept = 0 + rightmost = -1 + for left, right in sorted(intervals, key=lambda interval: (interval[0], -interval[1])): + if right > rightmost: + kept += 1 + rightmost = right + return result == kept +seed: 1288 +tests: + - name: "example_1_crossing_and_covered" + in: + intervals: + - [1, 4] + - [3, 6] + - [2, 8] + out: 2 + - name: "example_2_nested_pair" + in: + intervals: + - [1, 4] + - [2, 3] + out: 1 + - name: "single_interval" + in: + intervals: + - [4, 9] + out: 1 + - name: "disjoint_intervals" + in: + intervals: + - [1, 2] + - [3, 4] + - [5, 6] + out: 3 + - name: "touching_intervals_are_not_covered" + in: + intervals: + - [1, 2] + - [2, 3] + - [3, 4] + out: 3 + - name: "strictly_nested_chain" + in: + intervals: + - [1, 10] + - [2, 9] + - [3, 8] + - [4, 7] + out: 1 + - name: "same_left_longest_first_required" + in: + intervals: + - [1, 8] + - [1, 10] + - [2, 9] + - [11, 12] + out: 2 + - name: "same_right_shortest_is_covered" + in: + intervals: + - [2, 5] + - [1, 5] + - [3, 5] + - [6, 7] + out: 2 + - name: "minimum_and_maximum_coordinates" + in: + intervals: + - [0, 100000] + - [0, 99999] + - [1, 100000] + out: 1 + - name: "increasing_right_endpoints" + in: + intervals: + - [0, 2] + - [1, 3] + - [2, 4] + - [3, 5] + out: 4 + - name: "decreasing_right_endpoints" + in: + intervals: + - [3, 10] + - [0, 20] + - [2, 15] + - [1, 18] + out: 1 + - name: "overlap_without_coverage" + in: + intervals: + - [1, 4] + - [2, 5] + - [3, 6] + out: 3 + - name: "unordered_multiple_coverers" + in: + intervals: + - [8, 12] + - [2, 9] + - [1, 10] + - [3, 4] + - [11, 13] + out: 3 + - name: "one_interval_covers_many" + in: + intervals: + - [20, 30] + - [0, 100] + - [40, 50] + - [1, 99] + - [60, 70] + out: 1 + - name: "two_separate_covering_groups" + in: + intervals: + - [11, 20] + - [1, 10] + - [2, 3] + - [12, 19] + - [4, 8] + out: 2 + - name: "shared_left_with_later_extension" + in: + intervals: + - [5, 9] + - [5, 7] + - [6, 10] + - [7, 8] + out: 2 + - name: "shared_right_with_earlier_extension" + in: + intervals: + - [3, 9] + - [2, 9] + - [1, 8] + - [0, 10] + out: 1 + - name: "small_unit_intervals" + in: + intervals: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + out: 5 + - name: "one_unit_interval_inside_large" + in: + intervals: + - [99999, 100000] + - [0, 100000] + out: 1 + - name: "covering_boundary_equal_left" + in: + intervals: + - [0, 10] + - [0, 9] + - [1, 10] + - [10, 11] + out: 2 + - name: "alternating_kept_and_covered" + in: + intervals: + - [2, 3] + - [0, 5] + - [6, 8] + - [7, 9] + - [10, 20] + - [12, 15] + out: 4 + - name: "later_interval_covers_prior_interval" + in: + intervals: + - [4, 8] + - [1, 5] + - [3, 10] + - [11, 12] + out: 3 + - name: "wide_then_narrow_then_extension" + in: + intervals: + - [0, 50] + - [10, 20] + - [20, 60] + - [30, 40] + - [50, 70] + out: 3 + - name: "all_lefts_distinct_all_rights_distinct" + in: + intervals: + - [9, 13] + - [1, 7] + - [4, 8] + - [2, 6] + - [8, 12] + out: 4 + - name: "large_coordinate_overlapping_frontier" + in: + intervals: + - [0, 50000] + - [49999, 75000] + - [74999, 99999] + - [99998, 100000] + - [25000, 26000] + out: 4 + - name: "covering_interval_not_first" + in: + intervals: + - [50, 60] + - [20, 80] + - [30, 40] + - [10, 90] + out: 1 + - name: "three_components_with_nested_members" + in: + intervals: + - [1, 9] + - [2, 8] + - [10, 15] + - [11, 14] + - [16, 20] + - [17, 19] + out: 3 + - name: "sorted_input_with_same_left" + in: + intervals: + - [0, 9] + - [0, 7] + - [1, 8] + - [2, 10] + - [3, 4] + out: 2 + - name: "reverse_sorted_input" + in: + intervals: + - [9, 10] + - [8, 12] + - [7, 11] + - [1, 20] + - [0, 21] + out: 1 + - name: "crossing_then_contained_tail" + in: + intervals: + - [1, 3] + - [2, 7] + - [4, 6] + - [5, 9] + - [6, 8] + out: 3 + - name: "near_coordinate_limit_disjoint" + in: + intervals: + - [0, 1] + - [99997, 99998] + - [99998, 99999] + - [99999, 100000] + out: 4 + - name: "nested_at_coordinate_limit" + in: + intervals: + - [99990, 100000] + - [99991, 99999] + - [99992, 99998] + - [99993, 99997] + out: 1 + - name: "two_frontiers_with_equal_right" + in: + intervals: + - [1, 6] + - [2, 6] + - [3, 8] + - [4, 8] + - [9, 10] + out: 3 + - name: "many_short_intervals_under_two_kept" + in: + intervals: + - [0, 30] + - [1, 2] + - [3, 4] + - [5, 20] + - [21, 29] + - [30, 40] + - [31, 32] + - [35, 39] + out: 2 + - name: "endpoint_equality_is_coverage" + in: + intervals: + - [1, 5] + - [1, 4] + - [2, 5] + - [2, 4] + out: 1 + - name: "touching_covering_groups" + in: + intervals: + - [0, 100] + - [0, 99] + - [100, 200] + - [100, 199] + out: 2 + - name: "long_crossing_frontier" + in: + intervals: + - [0, 4] + - [1, 8] + - [2, 7] + - [3, 12] + - [4, 11] + - [5, 16] + - [6, 15] + out: 4 + - name: "sparse_unsorted_mix" + in: + intervals: + - [700, 800] + - [100, 900] + - [200, 300] + - [850, 950] + - [0, 50] + - [400, 500] + out: 3 + - name: "large_static_nested_and_frontier_stress" + in: + intervals: + - [400, 900] + - [0, 1000] + - [10, 990] + - [20, 980] + - [30, 970] + - [40, 960] + - [50, 950] + - [60, 940] + - [70, 930] + - [80, 920] + - [90, 910] + - [1000, 1100] + - [1010, 1090] + - [1020, 1080] + - [1100, 1200] + - [1110, 1190] + - [1120, 1180] + - [1200, 1300] + - [1210, 1290] + - [1220, 1280] + - [1300, 1400] + - [1310, 1390] + - [1320, 1380] + - [1400, 1500] + - [1410, 1490] + - [1420, 1480] + - [1500, 1600] + - [1510, 1590] + - [1520, 1580] + - [1600, 1700] + - [1610, 1690] + - [1620, 1680] + out: 8 + - name: "large_static_crossing_staircase_stress" + in: + intervals: + - [490, 510] + - [0, 100] + - [10, 90] + - [50, 150] + - [60, 140] + - [100, 200] + - [110, 190] + - [150, 250] + - [160, 240] + - [200, 300] + - [210, 290] + - [250, 350] + - [260, 340] + - [300, 400] + - [310, 390] + - [350, 450] + - [360, 440] + - [400, 500] + - [410, 490] + - [450, 550] + - [460, 540] + - [500, 600] + - [510, 590] + - [550, 650] + - [560, 640] + - [600, 700] + - [610, 690] + - [650, 750] + - [660, 740] + - [700, 800] + - [710, 790] + - [750, 850] + - [760, 840] + - [800, 900] + - [810, 890] + - [850, 950] + - [860, 940] + - [900, 1000] + - [910, 990] + out: 19 diff --git a/tests/1001-1500/1288. remove-covered-intervals/sol.cpp b/tests/1001-1500/1288. remove-covered-intervals/sol.cpp new file mode 100644 index 00000000..5a29c779 --- /dev/null +++ b/tests/1001-1500/1288. remove-covered-intervals/sol.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int removeCoveredIntervals(vector>& intervals) { + sort(intervals.begin(), intervals.end(), [](const auto& a, const auto& b) { + return a[0] == b[0] ? a[1] > b[1] : a[0] < b[0]; + }); + int res = 0, r = 0; + for (const auto& interval : intervals) { + if (interval[1] > r) { + ++res; + } + r = max(r, interval[1]); + } + return res; + } +}; diff --git a/tests/1001-1500/1288. remove-covered-intervals/sol.cs b/tests/1001-1500/1288. remove-covered-intervals/sol.cs new file mode 100644 index 00000000..51006d73 --- /dev/null +++ b/tests/1001-1500/1288. remove-covered-intervals/sol.cs @@ -0,0 +1,13 @@ +public class Solution { + public int RemoveCoveredIntervals(int[][] intervals) { + Array.Sort(intervals, (a, b) => a[0] == b[0] ? b[1].CompareTo(a[1]) : a[0].CompareTo(b[0])); + int res = 0, r = 0; + foreach (var interval in intervals) { + if (interval[1] > r) { + res++; + } + r = Math.Max(r, interval[1]); + } + return res; + } +} diff --git a/tests/1001-1500/1288. remove-covered-intervals/sol.dart b/tests/1001-1500/1288. remove-covered-intervals/sol.dart new file mode 100644 index 00000000..3c3de26d --- /dev/null +++ b/tests/1001-1500/1288. remove-covered-intervals/sol.dart @@ -0,0 +1,13 @@ +class Solution { + int removeCoveredIntervals(List> intervals) { + intervals.sort((a, b) => a[0] == b[0] ? b[1].compareTo(a[1]) : a[0].compareTo(b[0])); + int res = 0, r = 0; + for (final interval in intervals) { + if (interval[1] > r) { + res++; + } + r = r > interval[1] ? r : interval[1]; + } + return res; + } +} diff --git a/tests/1001-1500/1288. remove-covered-intervals/sol.go b/tests/1001-1500/1288. remove-covered-intervals/sol.go new file mode 100644 index 00000000..7bd928b1 --- /dev/null +++ b/tests/1001-1500/1288. remove-covered-intervals/sol.go @@ -0,0 +1,18 @@ +func removeCoveredIntervals(intervals [][]int) int { + sort.Slice(intervals, func(i, j int) bool { + if intervals[i][0] == intervals[j][0] { + return intervals[i][1] > intervals[j][1] + } + return intervals[i][0] < intervals[j][0] + }) + res, r := 0, 0 + for _, interval := range intervals { + if interval[1] > r { + res++ + } + if interval[1] > r { + r = interval[1] + } + } + return res +} diff --git a/tests/1001-1500/1288. remove-covered-intervals/sol.java b/tests/1001-1500/1288. remove-covered-intervals/sol.java new file mode 100644 index 00000000..4a7a6749 --- /dev/null +++ b/tests/1001-1500/1288. remove-covered-intervals/sol.java @@ -0,0 +1,13 @@ +class Solution { + public int removeCoveredIntervals(int[][] intervals) { + Arrays.sort(intervals, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]); + int res = 0, r = 0; + for (int[] interval : intervals) { + if (interval[1] > r) { + res++; + } + r = Math.max(r, interval[1]); + } + return res; + } +} diff --git a/tests/1001-1500/1288. remove-covered-intervals/sol.kt b/tests/1001-1500/1288. remove-covered-intervals/sol.kt new file mode 100644 index 00000000..ce5f69dc --- /dev/null +++ b/tests/1001-1500/1288. remove-covered-intervals/sol.kt @@ -0,0 +1,12 @@ +class Solution { + fun removeCoveredIntervals(intervals: Array): Int { + intervals.sortWith(compareBy { it[0] }.thenByDescending { it[1] }) + var res = 0 + var r = 0 + for ((_, end) in intervals) { + if (end > r) res++ + r = maxOf(r, end) + } + return res + } +} diff --git a/tests/1001-1500/1288. remove-covered-intervals/sol.py b/tests/1001-1500/1288. remove-covered-intervals/sol.py new file mode 100644 index 00000000..db52c550 --- /dev/null +++ b/tests/1001-1500/1288. remove-covered-intervals/sol.py @@ -0,0 +1,10 @@ +class Solution: + def removeCoveredIntervals(self, A: List[List[int]]) -> int: + A.sort(key=lambda x: (x[0], -x[1])) + res = r = 0 + + for st, end in A: + res += end > r + r = max(r, end) + + return res diff --git a/tests/1001-1500/1288. remove-covered-intervals/sol.py2 b/tests/1001-1500/1288. remove-covered-intervals/sol.py2 new file mode 100644 index 00000000..51867274 --- /dev/null +++ b/tests/1001-1500/1288. remove-covered-intervals/sol.py2 @@ -0,0 +1,12 @@ +class Solution(object): + def removeCoveredIntervals(self, intervals): + """ + :type intervals: List[List[int]] + :rtype: int + """ + intervals.sort(key=lambda x: (x[0], -x[1])) + res = r = 0 + for st, end in intervals: + res += end > r + r = max(r, end) + return res diff --git a/tests/1001-1500/1288. remove-covered-intervals/sol.rb b/tests/1001-1500/1288. remove-covered-intervals/sol.rb new file mode 100644 index 00000000..51a89bf4 --- /dev/null +++ b/tests/1001-1500/1288. remove-covered-intervals/sol.rb @@ -0,0 +1,14 @@ +# @param {Integer[][]} intervals +# @return {Integer} +def remove_covered_intervals(intervals) + intervals.sort_by! { |a| [a[0], -a[1]] } + res = 0 + r = 0 + intervals.each do |st, en| + if en > r + res += 1 + end + r = [r, en].max + end + res +end diff --git a/tests/1001-1500/1288. remove-covered-intervals/sol.rs b/tests/1001-1500/1288. remove-covered-intervals/sol.rs new file mode 100644 index 00000000..42cc25ca --- /dev/null +++ b/tests/1001-1500/1288. remove-covered-intervals/sol.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn remove_covered_intervals(intervals: Vec>) -> i32 { + let mut intervals = intervals; + intervals.sort_by(|a, b| a[0].cmp(&b[0]).then(b[1].cmp(&a[1]))); + let mut res = 0; + let mut r = 0; + for interval in intervals { + if interval[1] > r { + res += 1; + } + r = r.max(interval[1]); + } + res + } +} diff --git a/tests/1001-1500/1288. remove-covered-intervals/sol.swift b/tests/1001-1500/1288. remove-covered-intervals/sol.swift new file mode 100644 index 00000000..79cee765 --- /dev/null +++ b/tests/1001-1500/1288. remove-covered-intervals/sol.swift @@ -0,0 +1,15 @@ +class Solution { + func removeCoveredIntervals(_ intervals: [[Int]]) -> Int { + let sorted = intervals.sorted { a, b in + a[0] == b[0] ? a[1] > b[1] : a[0] < b[0] + } + var res = 0, r = 0 + for interval in sorted { + if interval[1] > r { + res += 1 + } + r = max(r, interval[1]) + } + return res + } +} diff --git a/tests/1001-1500/1288. remove-covered-intervals/sol.ts b/tests/1001-1500/1288. remove-covered-intervals/sol.ts new file mode 100644 index 00000000..1beb5076 --- /dev/null +++ b/tests/1001-1500/1288. remove-covered-intervals/sol.ts @@ -0,0 +1,12 @@ +function removeCoveredIntervals(intervals: number[][]): number { + intervals.sort((a, b) => (a[0] === b[0] ? b[1] - a[1] : a[0] - b[0])); + let res = 0, + r = 0; + for (const [st, end] of intervals) { + if (end > r) { + res++; + } + r = Math.max(r, end); + } + return res; +} diff --git a/tests/1001-1500/1289. minimum-falling-path-sum-ii/manifest.yaml b/tests/1001-1500/1289. minimum-falling-path-sum-ii/manifest.yaml new file mode 100644 index 00000000..51479163 --- /dev/null +++ b/tests/1001-1500/1289. minimum-falling-path-sum-ii/manifest.yaml @@ -0,0 +1,514 @@ +entry: + id: 1289 + title: "minimum-falling-path-sum-ii" + params: + grid: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().minFallingPathSum({grid})" + rust: "Solution::min_falling_path_sum({grid})" + python3: "Solution().minFallingPathSum({grid})" + python2: "Solution().minFallingPathSum({grid})" + ruby: "min_falling_path_sum({grid})" + java: "new Solution().minFallingPathSum({grid})" + csharp: "new Solution().MinFallingPathSum({grid})" + kotlin: "Solution().minFallingPathSum({grid})" + go: "minFallingPathSum({grid})" + dart: "Solution().minFallingPathSum({grid})" + swift: "Solution().minFallingPathSum({grid})" + typescript: "minFallingPathSum({grid})" +judge: + type: "exact" +limits: + time_ms: 1000 + memory_mb: 300 +oracle: + python3: + call: "Checker().minFallingPathSum(grid, {result})" + checker: | + class Checker: + def minFallingPathSum(self, grid, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + previous = grid[0][:] + for row in grid[1:]: + current = [] + for col, value in enumerate(row): + best = min(previous[other] for other in range(len(row)) if other != col) + current.append(value + best) + previous = current + return result == min(previous) +seed: 1289 +tests: + - name: "example_three_by_three" + in: + grid: + elemType: "int" + value: + - [1, 2, 3] + - [4, 5, 6] + - [7, 8, 9] + out: 13 + - name: "example_single_cell" + in: + grid: + elemType: "int" + value: + - [7] + out: 7 + - name: "single_minimum" + in: + grid: + elemType: "int" + value: + - [-99] + out: -99 + - name: "two_by_two_negative_tie" + in: + grid: + elemType: "int" + value: + - [-1, -2] + - [-3, -4] + out: -5 + - name: "two_by_two_alternating_extremes" + in: + grid: + elemType: "int" + value: + - [99, -99] + - [-99, 99] + out: -198 + - name: "two_by_two_reverse_extremes" + in: + grid: + elemType: "int" + value: + - [-99, 99] + - [99, -99] + out: -198 + - name: "three_by_three_all_negative" + in: + grid: + elemType: "int" + value: + - [-99, -99, -99] + - [-99, -99, -99] + - [-99, -99, -99] + out: -297 + - name: "reuse_column_after_one_row" + in: + grid: + elemType: "int" + value: + - [1, 99, 99] + - [99, 1, 99] + - [1, 99, 99] + out: 3 + - name: "forced_expensive_shift" + in: + grid: + elemType: "int" + value: + - [0, 1, 2] + - [0, 99, 99] + - [0, 1, 2] + out: 2 + - name: "three_by_three_mixed_signs" + in: + grid: + elemType: "int" + value: + - [7, -3, 8] + - [6, 1, -5] + - [-2, 4, 9] + out: -10 + - name: "three_by_three_repeated_minimum" + in: + grid: + elemType: "int" + value: + - [5, 0, 0] + - [0, 5, 5] + - [5, 0, 0] + out: 0 + - name: "three_by_three_diagonal_trap" + in: + grid: + elemType: "int" + value: + - [-8, 5, 5] + - [5, -8, 5] + - [5, 5, -8] + out: -24 + - name: "four_by_four_example_like" + in: + grid: + elemType: "int" + value: + - [2, 9, 4, 5] + - [1, 0, 8, 3] + - [7, 6, 2, 4] + - [3, 5, 1, 9] + out: 7 + - name: "four_by_four_negative_corridor" + in: + grid: + elemType: "int" + value: + - [-9, 4, 4, 4] + - [4, -9, 4, 4] + - [4, 4, -9, 4] + - [4, 4, 4, -9] + out: -36 + - name: "four_by_four_column_zero_trap" + in: + grid: + elemType: "int" + value: + - [-10, 1, 2, 3] + - [-10, 20, 20, 20] + - [-10, 1, 2, 3] + - [-10, 20, 20, 20] + out: -18 + - name: "four_by_four_boundary_values" + in: + grid: + elemType: "int" + value: + - [99, -99, 99, -99] + - [-99, 99, -99, 99] + - [99, -99, 99, -99] + - [-99, 99, -99, 99] + out: -396 + - name: "four_by_four_multiple_equal_paths" + in: + grid: + elemType: "int" + value: + - [0, 0, 5, 5] + - [0, 0, 5, 5] + - [5, 5, 0, 0] + - [0, 0, 5, 5] + out: 0 + - name: "five_by_five_descending_rows" + in: + grid: + elemType: "int" + value: + - [9, 8, 7, 6, 5] + - [5, 6, 7, 8, 9] + - [9, 1, 9, 9, 9] + - [9, 9, 1, 9, 9] + - [9, 9, 9, 1, 9] + out: 13 + - name: "five_by_five_alternating_zero_columns" + in: + grid: + elemType: "int" + value: + - [0, 9, 9, 9, 9] + - [9, 0, 9, 9, 9] + - [0, 9, 9, 9, 9] + - [9, 0, 9, 9, 9] + - [0, 9, 9, 9, 9] + out: 0 + - name: "five_by_five_global_vs_greedy" + in: + grid: + elemType: "int" + value: + - [0, 4, 4, 4, 4] + - [0, 50, 50, 50, 50] + - [0, 1, 1, 1, 1] + - [0, 50, 50, 50, 50] + - [0, 1, 1, 1, 1] + out: 6 + - name: "five_by_five_dense_mixed" + in: + grid: + elemType: "int" + value: + - [3, -4, 2, 8, 1] + - [6, 5, -7, 4, 0] + - [-2, 9, 3, -5, 7] + - [8, -6, 1, 2, -3] + - [4, 0, -8, 6, 5] + out: -30 + - name: "six_by_six_shifted_diagonal" + in: + grid: + elemType: "int" + value: + - [-6, 8, 8, 8, 8, 8] + - [8, -6, 8, 8, 8, 8] + - [8, 8, -6, 8, 8, 8] + - [8, 8, 8, -6, 8, 8] + - [8, 8, 8, 8, -6, 8] + - [8, 8, 8, 8, 8, -6] + out: -36 + - name: "six_by_six_opposite_corners" + in: + grid: + elemType: "int" + value: + - [-9, 9, 9, 9, 9, 9] + - [9, 9, 9, 9, 9, -9] + - [-9, 9, 9, 9, 9, 9] + - [9, 9, 9, 9, 9, -9] + - [-9, 9, 9, 9, 9, 9] + - [9, 9, 9, 9, 9, -9] + out: -54 + - name: "six_by_six_sparse_negative" + in: + grid: + elemType: "int" + value: + - [4, 4, -5, 4, 4, 4] + - [4, -5, 4, 4, 4, 4] + - [4, 4, -5, 4, 4, 4] + - [4, -5, 4, 4, 4, 4] + - [4, 4, -5, 4, 4, 4] + - [4, -5, 4, 4, 4, 4] + out: -30 + - name: "six_by_six_tie_for_second_best" + in: + grid: + elemType: "int" + value: + - [0, 0, 4, 4, 4, 4] + - [0, 0, 4, 4, 4, 4] + - [4, 4, 0, 0, 4, 4] + - [4, 4, 0, 0, 4, 4] + - [0, 0, 4, 4, 4, 4] + - [0, 0, 4, 4, 4, 4] + out: 0 + - name: "seven_by_seven_alternating_extremes" + in: + grid: + elemType: "int" + value: + - [-99, 99, 99, 99, 99, 99, 99] + - [99, -99, 99, 99, 99, 99, 99] + - [-99, 99, 99, 99, 99, 99, 99] + - [99, -99, 99, 99, 99, 99, 99] + - [-99, 99, 99, 99, 99, 99, 99] + - [99, -99, 99, 99, 99, 99, 99] + - [-99, 99, 99, 99, 99, 99, 99] + out: -693 + - name: "seven_by_seven_center_avoidance" + in: + grid: + elemType: "int" + value: + - [7, 7, 7, -8, 7, 7, 7] + - [7, 7, 7, -8, 7, 7, 7] + - [7, 7, -8, 7, -8, 7, 7] + - [7, -8, 7, 7, 7, -8, 7] + - [-8, 7, 7, 7, 7, 7, -8] + - [7, -8, 7, 7, 7, -8, 7] + - [7, 7, -8, 7, -8, 7, 7] + out: -41 + - name: "seven_by_seven_row_minimum_collision" + in: + grid: + elemType: "int" + value: + - [-10, 2, 2, 2, 2, 2, 2] + - [-10, 2, 2, 2, 2, 2, 2] + - [2, -10, 2, 2, 2, 2, 2] + - [2, -10, 2, 2, 2, 2, 2] + - [2, 2, -10, 2, 2, 2, 2] + - [2, 2, -10, 2, 2, 2, 2] + - [-10, 2, 2, 2, 2, 2, 2] + out: -34 + - name: "eight_by_eight_checkerboard" + in: + grid: + elemType: "int" + value: + - [-3, 6, -3, 6, -3, 6, -3, 6] + - [6, -3, 6, -3, 6, -3, 6, -3] + - [-3, 6, -3, 6, -3, 6, -3, 6] + - [6, -3, 6, -3, 6, -3, 6, -3] + - [-3, 6, -3, 6, -3, 6, -3, 6] + - [6, -3, 6, -3, 6, -3, 6, -3] + - [-3, 6, -3, 6, -3, 6, -3, 6] + - [6, -3, 6, -3, 6, -3, 6, -3] + out: -24 + - name: "eight_by_eight_wide_choice" + in: + grid: + elemType: "int" + value: + - [8, 7, 6, 5, 4, 3, 2, 1] + - [1, 2, 3, 4, 5, 6, 7, 8] + - [8, 1, 8, 8, 8, 8, 8, 8] + - [8, 8, 1, 8, 8, 8, 8, 8] + - [8, 8, 8, 1, 8, 8, 8, 8] + - [8, 8, 8, 8, 1, 8, 8, 8] + - [8, 8, 8, 8, 8, 1, 8, 8] + - [8, 8, 8, 8, 8, 8, 1, 8] + out: 8 + - name: "nine_by_nine_negative_zigzag" + in: + grid: + elemType: "int" + value: + - [-4, 3, 3, 3, 3, 3, 3, 3, 3] + - [3, -4, 3, 3, 3, 3, 3, 3, 3] + - [-4, 3, 3, 3, 3, 3, 3, 3, 3] + - [3, -4, 3, 3, 3, 3, 3, 3, 3] + - [-4, 3, 3, 3, 3, 3, 3, 3, 3] + - [3, -4, 3, 3, 3, 3, 3, 3, 3] + - [-4, 3, 3, 3, 3, 3, 3, 3, 3] + - [3, -4, 3, 3, 3, 3, 3, 3, 3] + - [-4, 3, 3, 3, 3, 3, 3, 3, 3] + out: -36 + - name: "nine_by_nine_mixed_layers" + in: + grid: + elemType: "int" + value: + - [2, -1, 4, 0, 3, -2, 5, 1, 6] + - [3, 5, -4, 2, 1, 6, -1, 4, 0] + - [-3, 2, 1, 5, -5, 3, 4, 0, 2] + - [4, -6, 3, 1, 2, -2, 5, 0, 6] + - [1, 4, -7, 3, 0, 2, -1, 5, 6] + - [5, 0, 2, -8, 4, 1, 3, -2, 6] + - [-4, 3, 1, 2, -3, 5, 0, 4, 6] + - [2, -5, 4, 0, 3, 1, -6, 5, 7] + - [1, 3, -2, 4, 0, -4, 2, 5, 6] + out: -46 + - name: "ten_by_ten_alternating_columns" + in: + grid: + elemType: "int" + value: + - [-2, 5, 5, 5, 5, 5, 5, 5, 5, 5] + - [5, -2, 5, 5, 5, 5, 5, 5, 5, 5] + - [-2, 5, 5, 5, 5, 5, 5, 5, 5, 5] + - [5, -2, 5, 5, 5, 5, 5, 5, 5, 5] + - [-2, 5, 5, 5, 5, 5, 5, 5, 5, 5] + - [5, -2, 5, 5, 5, 5, 5, 5, 5, 5] + - [-2, 5, 5, 5, 5, 5, 5, 5, 5, 5] + - [5, -2, 5, 5, 5, 5, 5, 5, 5, 5] + - [-2, 5, 5, 5, 5, 5, 5, 5, 5, 5] + - [5, -2, 5, 5, 5, 5, 5, 5, 5, 5] + out: -20 + - name: "ten_by_ten_broad_negative_choices" + in: + grid: + elemType: "int" + value: + - [-1, -1, 9, 9, 9, 9, 9, 9, 9, 9] + - [-1, -1, 9, 9, 9, 9, 9, 9, 9, 9] + - [9, 9, -1, -1, 9, 9, 9, 9, 9, 9] + - [9, 9, -1, -1, 9, 9, 9, 9, 9, 9] + - [9, 9, 9, 9, -1, -1, 9, 9, 9, 9] + - [9, 9, 9, 9, -1, -1, 9, 9, 9, 9] + - [9, 9, 9, 9, 9, 9, -1, -1, 9, 9] + - [9, 9, 9, 9, 9, 9, -1, -1, 9, 9] + - [9, 9, 9, 9, 9, 9, 9, 9, -1, -1] + - [9, 9, 9, 9, 9, 9, 9, 9, -1, -1] + out: -10 + - name: "eleven_by_eleven_alternating_endpoints" + in: + grid: + elemType: "int" + value: + - [-3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4] + - [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, -3] + - [-3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4] + - [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, -3] + - [-3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4] + - [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, -3] + - [-3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4] + - [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, -3] + - [-3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4] + - [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, -3] + - [-3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4] + out: -33 + - name: "generated_max_square_uniform_range_a" + seed: 128901 + in: + grid: + gen: "array" + len: 200 + elemType: "int" + of: + gen: "array" + len: 200 + elemType: "int" + of: + gen: "int" + min: -99 + max: 99 + + - name: "generated_max_square_uniform_range_b" + seed: 128902 + in: + grid: + gen: "array" + len: 200 + elemType: "int" + of: + gen: "array" + len: 200 + elemType: "int" + of: + gen: "int" + min: -99 + max: 99 + + - name: "generated_max_square_nonnegative" + seed: 128903 + in: + grid: + gen: "array" + len: 200 + elemType: "int" + of: + gen: "array" + len: 200 + elemType: "int" + of: + gen: "int" + min: 0 + max: 99 + + - name: "generated_max_square_nonpositive" + seed: 128904 + in: + grid: + gen: "array" + len: 200 + elemType: "int" + of: + gen: "array" + len: 200 + elemType: "int" + of: + gen: "int" + min: -99 + max: 0 + + - name: "generated_max_square_boundary_values" + seed: 128905 + in: + grid: + gen: "array" + len: 200 + elemType: "int" + of: + gen: "array" + len: 200 + elemType: "int" + of: + gen: "int" + min: -99 + max: 99 diff --git a/tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.cpp b/tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.cpp new file mode 100644 index 00000000..cc5f3a55 --- /dev/null +++ b/tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int minFallingPathSum(vector>& grid) { + int n = grid.size(); + vector dp = grid[0]; + for (int i = 1; i < n; i++) { + int smallest = INT_MAX; + int second_smallest = INT_MAX; + int smallest_col = -1; + for (int col = 0; col < n; col++) { + if (dp[col] < smallest) { + second_smallest = smallest; + smallest = dp[col]; + smallest_col = col; + } else if (dp[col] < second_smallest) { + second_smallest = dp[col]; + } + } + vector new_dp(n); + for (int col = 0; col < n; col++) { + new_dp[col] = grid[i][col] + (col == smallest_col ? second_smallest : smallest); + } + dp = new_dp; + } + return *min_element(dp.begin(), dp.end()); + } +}; diff --git a/tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.cs b/tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.cs new file mode 100644 index 00000000..37dde147 --- /dev/null +++ b/tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.cs @@ -0,0 +1,26 @@ +public class Solution { + public int MinFallingPathSum(int[][] grid) { + int n = grid.Length; + int[] dp = (int[])grid[0].Clone(); + for (int i = 1; i < n; i++) { + int smallest = int.MaxValue; + int secondSmallest = int.MaxValue; + int smallestCol = -1; + for (int col = 0; col < n; col++) { + if (dp[col] < smallest) { + secondSmallest = smallest; + smallest = dp[col]; + smallestCol = col; + } else if (dp[col] < secondSmallest) { + secondSmallest = dp[col]; + } + } + int[] newDp = new int[n]; + for (int col = 0; col < n; col++) { + newDp[col] = grid[i][col] + (col == smallestCol ? secondSmallest : smallest); + } + dp = newDp; + } + return dp.Min(); + } +} diff --git a/tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.dart b/tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.dart new file mode 100644 index 00000000..1ff065ca --- /dev/null +++ b/tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.dart @@ -0,0 +1,25 @@ +class Solution { + int minFallingPathSum(List> grid) { + int n = grid.length; + List dp = List.from(grid[0]); + for (int i = 1; i < n; i++) { + int smallest = 1 << 62; + int secondSmallest = 1 << 62; + int smallestCol = -1; + for (int col = 0; col < n; col++) { + int value = dp[col]; + if (value < smallest) { + secondSmallest = smallest; + smallest = value; + smallestCol = col; + } else if (value < secondSmallest) { + secondSmallest = value; + } + } + dp = List.generate(n, (col) { + return grid[i][col] + (col == smallestCol ? secondSmallest : smallest); + }); + } + return dp.reduce((a, b) => a < b ? a : b); + } +} diff --git a/tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.go b/tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.go new file mode 100644 index 00000000..127a1eee --- /dev/null +++ b/tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.go @@ -0,0 +1,35 @@ +func minFallingPathSum(grid [][]int) int { + n := len(grid) + dp := make([]int, n) + copy(dp, grid[0]) + for i := 1; i < n; i++ { + smallest := int(^uint(0) >> 1) // max int + secondSmallest := int(^uint(0) >> 1) + smallestCol := -1 + for col, value := range dp { + if value < smallest { + secondSmallest = smallest + smallest = value + smallestCol = col + } else if value < secondSmallest { + secondSmallest = value + } + } + newDp := make([]int, n) + for col, value := range grid[i] { + if col == smallestCol { + newDp[col] = value + secondSmallest + } else { + newDp[col] = value + smallest + } + } + dp = newDp + } + min := dp[0] + for _, val := range dp { + if val < min { + min = val + } + } + return min +} diff --git a/tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.java b/tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.java new file mode 100644 index 00000000..a7f62799 --- /dev/null +++ b/tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.java @@ -0,0 +1,30 @@ +class Solution { + public int minFallingPathSum(int[][] grid) { + int n = grid.length; + int[] dp = grid[0].clone(); + for (int i = 1; i < n; i++) { + int smallest = Integer.MAX_VALUE; + int secondSmallest = Integer.MAX_VALUE; + int smallestCol = -1; + for (int col = 0; col < n; col++) { + if (dp[col] < smallest) { + secondSmallest = smallest; + smallest = dp[col]; + smallestCol = col; + } else if (dp[col] < secondSmallest) { + secondSmallest = dp[col]; + } + } + int[] newDp = new int[n]; + for (int col = 0; col < n; col++) { + newDp[col] = grid[i][col] + (col == smallestCol ? secondSmallest : smallest); + } + dp = newDp; + } + int min = dp[0]; + for (int val : dp) { + if (val < min) min = val; + } + return min; + } +} diff --git a/tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.kt b/tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.kt new file mode 100644 index 00000000..772ba896 --- /dev/null +++ b/tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.kt @@ -0,0 +1,25 @@ +class Solution { + fun minFallingPathSum(grid: Array): Int { + val n = grid.size + var dp = grid[0].copyOf() + for (i in 1 until n) { + var smallest = Int.MAX_VALUE + var secondSmallest = Int.MAX_VALUE + var smallestCol = -1 + for (col in dp.indices) { + val value = dp[col] + if (value < smallest) { + secondSmallest = smallest + smallest = value + smallestCol = col + } else if (value < secondSmallest) { + secondSmallest = value + } + } + dp = IntArray(n) { col -> + grid[i][col] + if (col == smallestCol) secondSmallest else smallest + } + } + return dp.min() + } +} diff --git a/tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.py b/tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.py new file mode 100644 index 00000000..94ac2fd3 --- /dev/null +++ b/tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.py @@ -0,0 +1,21 @@ +from typing import List + + +class Solution: + def minFallingPathSum(self, grid: List[List[int]]) -> int: + dp = grid[0][:] + for row in grid[1:]: + smallest = second_smallest = float("inf") + smallest_col = -1 + for col, value in enumerate(dp): + if value < smallest: + second_smallest = smallest + smallest = value + smallest_col = col + elif value < second_smallest: + second_smallest = value + dp = [ + value + (second_smallest if col == smallest_col else smallest) + for col, value in enumerate(row) + ] + return min(dp) diff --git a/tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.py2 b/tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.py2 new file mode 100644 index 00000000..e5a8e396 --- /dev/null +++ b/tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.py2 @@ -0,0 +1,20 @@ +class Solution(object): + def minFallingPathSum(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + dp = grid[0][:] + for row in grid[1:]: + smallest = second_smallest = float("inf") + smallest_col = -1 + for col, value in enumerate(dp): + if value < smallest: + second_smallest = smallest + smallest = value + smallest_col = col + elif value < second_smallest: + second_smallest = value + dp = [value + (second_smallest if col == smallest_col else smallest) + for col, value in enumerate(row)] + return min(dp) diff --git a/tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.rb b/tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.rb new file mode 100644 index 00000000..3fc6f200 --- /dev/null +++ b/tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.rb @@ -0,0 +1,23 @@ +# @param {Integer[][]} grid +# @return {Integer} +def min_falling_path_sum(grid) + dp = grid[0].dup + (1...grid.length).each do |i| + smallest = Float::INFINITY + second_smallest = Float::INFINITY + smallest_col = -1 + dp.each_with_index do |value, col| + if value < smallest + second_smallest = smallest + smallest = value + smallest_col = col + elsif value < second_smallest + second_smallest = value + end + end + dp = grid[i].each_with_index.map do |value, col| + value + (col == smallest_col ? second_smallest : smallest) + end + end + dp.min +end diff --git a/tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.rs b/tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.rs new file mode 100644 index 00000000..031ff80a --- /dev/null +++ b/tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.rs @@ -0,0 +1,32 @@ +impl Solution { + pub fn min_falling_path_sum(grid: Vec>) -> i32 { + let n = grid.len(); + let mut dp = grid[0].clone(); + for i in 1..n { + let mut smallest = i32::MAX; + let mut second_smallest = i32::MAX; + let mut smallest_col: i32 = -1; + for (col, &value) in dp.iter().enumerate() { + if value < smallest { + second_smallest = smallest; + smallest = value; + smallest_col = col as i32; + } else if value < second_smallest { + second_smallest = value; + } + } + dp = grid[i] + .iter() + .enumerate() + .map(|(col, &value)| { + value + if col as i32 == smallest_col { + second_smallest + } else { + smallest + } + }) + .collect(); + } + *dp.iter().min().unwrap() + } +} diff --git a/tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.swift b/tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.swift new file mode 100644 index 00000000..3b38f8d4 --- /dev/null +++ b/tests/1001-1500/1289. minimum-falling-path-sum-ii/sol.swift @@ -0,0 +1,24 @@ +class Solution { + func minFallingPathSum(_ grid: [[Int]]) -> Int { + let n = grid.count + var dp = grid[0] + for i in 1.. value + (col === smallestCol ? secondSmallest : smallest), + ); + } + return Math.min(...dp); +} diff --git a/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/manifest.yaml b/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/manifest.yaml new file mode 100644 index 00000000..526037c1 --- /dev/null +++ b/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/manifest.yaml @@ -0,0 +1,427 @@ +entry: + id: 1290 + title: "convert-binary-number-in-a-linked-list-to-integer" + params: + head: + type: list_node + call: + cpp: "Solution().getDecimalValue({head})" + rust: "Solution::get_decimal_value({head})" + python3: "Solution().getDecimalValue({head})" + python2: "Solution().getDecimalValue({head})" + ruby: "get_decimal_value({head})" + java: "new Solution().getDecimalValue({head})" + csharp: "new Solution().GetDecimalValue({head})" + kotlin: "Solution().getDecimalValue({head})" + go: "getDecimalValue({head})" + dart: "Solution().getDecimalValue({head})" + swift: "Solution().getDecimalValue({head})" + typescript: "getDecimalValue({head})" + +judge: + type: "exact" + +limits: + time_ms: 300 + memory_mb: 300 + +oracle: + python3: + call: "Checker().getDecimalValue(head, {result})" + checker: | + class Checker: + def getDecimalValue(self, head, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + value = 0 + for bit in head: + if bit not in (0, 1): + return False + value = (value << 1) | bit + return result == value + +seed: 1290 + +tests: + - name: "example_101" + in: + head: [1, 0, 1] + out: 5 + + - name: "example_zero" + in: + head: [0] + out: 0 + + - name: "single_one" + in: + head: [1] + out: 1 + + - name: "two_bits_01" + in: + head: [0, 1] + out: 1 + + - name: "two_bits_10" + in: + head: [1, 0] + out: 2 + + - name: "two_bits_11" + in: + head: [1, 1] + out: 3 + + - name: "all_zeros_eight_bits" + in: + head: [0, 0, 0, 0, 0, 0, 0, 0] + out: 0 + + - name: "all_ones_three_bits" + in: + head: [1, 1, 1] + out: 7 + + - name: "all_ones_eight_bits" + in: + head: [1, 1, 1, 1, 1, 1, 1, 1] + out: 255 + + - name: "power_of_two_after_leading_one" + in: + head: [1, 0, 0, 0, 0, 0] + out: 32 + + - name: "trailing_one" + in: + head: [1, 0, 0, 0, 0, 1] + out: 33 + + - name: "leading_zeros" + in: + head: [0, 0, 1, 0, 1] + out: 5 + + - name: "many_leading_zeros" + in: + head: [0, 0, 0, 0, 0, 0, 1] + out: 1 + + - name: "alternating_six_start_one" + in: + head: [1, 0, 1, 0, 1, 0] + out: 42 + + - name: "alternating_six_start_zero" + in: + head: [0, 1, 0, 1, 0, 1] + out: 21 + + - name: "eight_bit_mixed" + in: + head: [1, 0, 1, 0, 1, 1, 0, 0] + out: 172 + + - name: "nine_bit_endpoint_ones" + in: + head: [1, 0, 0, 0, 0, 0, 0, 0, 1] + out: 257 + + - name: "seven_bit_clustered" + in: + head: [1, 1, 0, 0, 1, 0, 1] + out: 101 + + - name: "seven_bit_leading_zero" + in: + head: [0, 1, 1, 0, 0, 1, 1] + out: 51 + + - name: "ten_bit_mixed" + in: + head: [1, 0, 1, 1, 0, 0, 1, 0, 1, 1] + out: 715 + + - name: "twelve_bit_mixed" + in: + head: [0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1] + out: 1869 + + - name: "fifteen_bit_mixed" + in: + head: [1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0] + out: 22166 + + - name: "sixteen_bit_msb_only" + in: + head: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + out: 32768 + + - name: "sixteen_bit_lsb_only" + in: + head: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1] + out: 1 + + - name: "sixteen_bit_all_ones" + in: + head: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + out: 65535 + + - name: "twenty_bit_sparse" + in: + head: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1] + out: 524801 + + - name: "twenty_bit_alternating" + in: + head: [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0] + out: 699050 + + - name: "twenty_bit_all_ones" + in: + head: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + out: 1048575 + + - name: "twenty_one_bit_middle_one" + in: + head: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + out: 1024 + + - name: "twenty_four_bit_boundary_pattern" + in: + head: + [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1] + out: 8388863 + + - name: "thirty_bit_min_value" + 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, + 0, + 0, + 0, + 0, + 0, + 1, + ] + out: 1 + + - name: "thirty_bit_high_bit" + in: + head: + [ + 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, + ] + out: 536870912 + + - name: "thirty_bit_all_ones" + in: + head: + [ + 1, + 1, + 1, + 1, + 1, + 1, + 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: 1073741823 + + - name: "thirty_bit_mixed_maximum_width" + in: + head: + [ + 1, + 0, + 0, + 1, + 1, + 0, + 1, + 0, + 1, + 1, + 0, + 0, + 1, + 0, + 1, + 0, + 0, + 1, + 1, + 1, + 0, + 1, + 0, + 1, + 1, + 0, + 0, + 1, + 0, + 1, + ] + out: 649239909 + + - name: "generated_max_width_seed_1" + seed: 1291 + in: + head: + gen: "array" + len: 30 + of: + gen: "int" + min: 0 + max: 1 + distinct: false + sorted: false + elemType: "int" + + - name: "generated_max_width_seed_2" + seed: 1292 + in: + head: + gen: "array" + len: 30 + of: + gen: "int" + min: 0 + max: 1 + distinct: false + sorted: false + elemType: "int" + + - name: "generated_max_width_seed_3" + seed: 1293 + in: + head: + gen: "array" + len: 30 + of: + gen: "int" + min: 0 + max: 1 + distinct: false + sorted: false + elemType: "int" + + - name: "generated_max_width_seed_4" + seed: 1294 + in: + head: + gen: "array" + len: 30 + of: + gen: "int" + min: 0 + max: 1 + distinct: false + sorted: false + elemType: "int" + + - name: "generated_max_width_seed_5" + seed: 1295 + in: + head: + gen: "array" + len: 30 + of: + gen: "int" + min: 0 + max: 1 + distinct: false + sorted: false + elemType: "int" + + - name: "generated_max_width_seed_6" + seed: 1296 + in: + head: + gen: "array" + len: 30 + of: + gen: "int" + min: 0 + max: 1 + distinct: false + sorted: false + elemType: "int" diff --git a/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.cpp b/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.cpp new file mode 100644 index 00000000..903094b0 --- /dev/null +++ b/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.cpp @@ -0,0 +1,21 @@ +/** + * 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: + int getDecimalValue(ListNode* head) { + int num = 0; + while (head != nullptr) { + num = (num << 1) | head->val; + head = head->next; + } + return num; + } +}; diff --git a/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.cs b/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.cs new file mode 100644 index 00000000..aeca180d --- /dev/null +++ b/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.cs @@ -0,0 +1,21 @@ +/** + * 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 int GetDecimalValue(ListNode head) { + int num = 0; + while (head != null) { + num = (num << 1) | head.val; + head = head.next; + } + return num; + } +} diff --git a/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.dart b/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.dart new file mode 100644 index 00000000..5cc0a3bb --- /dev/null +++ b/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.dart @@ -0,0 +1,18 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * int val; + * ListNode? next; + * ListNode([this.val = 0, this.next]); + * } + */ +class Solution { + int getDecimalValue(ListNode? head) { + int num = 0; + while (head != null) { + num = (num << 1) | head.val; + head = head.next; + } + return num; + } +} diff --git a/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.go b/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.go new file mode 100644 index 00000000..a02c3fd6 --- /dev/null +++ b/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.go @@ -0,0 +1,15 @@ +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func getDecimalValue(head *ListNode) int { + num := 0 + for head != nil { + num = (num << 1) | head.Val + head = head.Next + } + return num +} diff --git a/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.java b/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.java new file mode 100644 index 00000000..b57f3cd7 --- /dev/null +++ b/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.java @@ -0,0 +1,20 @@ +/** + * 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 int getDecimalValue(ListNode head) { + int num = 0; + while (head != null) { + num = (num << 1) | head.val; + head = head.next; + } + return num; + } +} diff --git a/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.kt b/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.kt new file mode 100644 index 00000000..26933d3b --- /dev/null +++ b/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.kt @@ -0,0 +1,20 @@ +/** + * 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 getDecimalValue(head: ListNode?): Int { + var num = 0 + var curr = head + while (curr != null) { + num = (num shl 1) or curr.`val` + curr = curr.next + } + return num + } +} diff --git a/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.py b/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.py new file mode 100644 index 00000000..ff0ea403 --- /dev/null +++ b/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.py @@ -0,0 +1,7 @@ +class Solution: + def getDecimalValue(self, head: Optional[ListNode]) -> int: + num = 0 + while head: + num = (num << 1) | head.val + head = head.next + return num diff --git a/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.py2 b/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.py2 new file mode 100644 index 00000000..7c8d0dee --- /dev/null +++ b/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.py2 @@ -0,0 +1,16 @@ +# 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 getDecimalValue(self, head): + """ + :type head: Optional[ListNode] + :rtype: int + """ + num = 0 + while head: + num = (num << 1) | head.val + head = head.next + return num diff --git a/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.rb b/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.rb new file mode 100644 index 00000000..9046abb1 --- /dev/null +++ b/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.rb @@ -0,0 +1,18 @@ +# 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 +# @return {Integer} +def get_decimal_value(head) + num = 0 + while head + num = (num << 1) | head.val + head = head.next + end + num +end diff --git a/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.rs b/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.rs new file mode 100644 index 00000000..b2438509 --- /dev/null +++ b/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.rs @@ -0,0 +1,27 @@ +// 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 get_decimal_value(head: Option>) -> i32 { + let mut num = 0; + let mut curr = head; + while let Some(node) = curr { + num = (num << 1) | node.val; + curr = node.next; + } + num + } +} diff --git a/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.swift b/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.swift new file mode 100644 index 00000000..fbb89294 --- /dev/null +++ b/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.swift @@ -0,0 +1,21 @@ +/** + * 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 getDecimalValue(_ head: ListNode?) -> Int { + var num = 0 + var curr = head + while let node = curr { + num = (num << 1) | node.val + curr = node.next + } + return num + } +} diff --git a/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.ts b/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.ts new file mode 100644 index 00000000..a5b0db2c --- /dev/null +++ b/tests/1001-1500/1290. convert-binary-number-in-a-linked-list-to-integer/sol.ts @@ -0,0 +1,20 @@ +/** + * 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 getDecimalValue(head: ListNode | null): number { + let num = 0; + while (head !== null) { + num = (num << 1) | head.val; + head = head.next; + } + return num; +} diff --git a/tests/1001-1500/1291. sequential-digits/manifest.yaml b/tests/1001-1500/1291. sequential-digits/manifest.yaml new file mode 100644 index 00000000..441a0290 --- /dev/null +++ b/tests/1001-1500/1291. sequential-digits/manifest.yaml @@ -0,0 +1,343 @@ +entry: + id: 1291 + title: "sequential-digits" + params: + low: + type: int + high: + type: int + call: + cpp: "Solution().sequentialDigits({low}, {high})" + rust: "Solution::sequential_digits({low}, {high})" + python3: "Solution().sequentialDigits({low}, {high})" + python2: "Solution().sequentialDigits({low}, {high})" + ruby: "sequential_digits({low}, {high})" + java: "new Solution().sequentialDigits({low}, {high})" + csharp: "new Solution().SequentialDigits({low}, {high})" + kotlin: "Solution().sequentialDigits({low}, {high})" + go: "sequentialDigits({low}, {high})" + dart: "Solution().sequentialDigits({low}, {high})" + swift: "Solution().sequentialDigits({low}, {high})" + typescript: "sequentialDigits({low}, {high})" + +judge: + type: "exact" + +limits: + time_ms: 300 + memory_mb: 300 + +oracle: + python3: + call: "Checker().sequentialDigits(low, high, {result})" + checker: | + class Checker: + def sequentialDigits(self, low, high, result): + if not isinstance(result, list) or result != sorted(result): + return False + for value in result: + if not isinstance(value, int) or not low <= value <= high: + return False + digits = str(value) + if any(int(digits[i + 1]) != int(digits[i]) + 1 for i in range(len(digits) - 1)): + return False + expected_count = 0 + for length in range(2, 10): + for start in range(1, 11 - length): + value = int("".join(str(digit) for digit in range(start, start + length))) + if low <= value <= high: + expected_count += 1 + return len(result) == expected_count + +seed: 1291 + +tests: + - name: "example_100_to_300" + in: + low: 100 + high: 300 + out: [123, 234] + - name: "example_1000_to_13000" + in: + low: 1000 + high: 13000 + out: [1234, 2345, 3456, 4567, 5678, 6789, 12345] + - name: "minimum_single_value_no_match" + in: + low: 10 + high: 10 + out: [] + - name: "first_two_digit_value" + in: + low: 12 + high: 12 + out: [12] + - name: "between_first_two_digit_values" + in: + low: 13 + high: 22 + out: [] + - name: "all_two_digit_values" + in: + low: 10 + high: 99 + out: [12, 23, 34, 45, 56, 67, 78, 89] + - name: "last_two_digit_value" + in: + low: 89 + high: 89 + out: [89] + - name: "two_to_three_digit_transition" + in: + low: 90 + high: 123 + out: [123] + - name: "three_digit_lower_boundary" + in: + low: 100 + high: 123 + out: [123] + - name: "all_three_digit_values" + in: + low: 100 + high: 999 + out: [123, 234, 345, 456, 567, 678, 789] + - name: "three_digit_internal_gap" + in: + low: 124 + high: 233 + out: [] + - name: "three_digit_middle_window" + in: + low: 300 + high: 700 + out: [345, 456, 567, 678] + - name: "last_three_digit_to_four_digit_transition" + in: + low: 790 + high: 1234 + out: [1234] + - name: "generated_low_small_high_nine_digit" + seed: 129101 + in: + low: + gen: "int" + min: 10 + max: 99999999 + high: + gen: "int" + min: 100000000 + max: 1000000000 + - name: "all_four_digit_values" + in: + low: 1000 + high: 9999 + out: [1234, 2345, 3456, 4567, 5678, 6789] + - name: "four_digit_partial_window" + in: + low: 2000 + high: 6000 + out: [2345, 3456, 4567, 5678] + - name: "four_to_five_digit_transition" + in: + low: 6790 + high: 12345 + out: [12345] + - name: "generated_midrange_low_high_max_tail" + seed: 129102 + in: + low: + gen: "int" + min: 100000000 + max: 500000000 + high: + gen: "int" + min: 900000000 + max: 1000000000 + - name: "all_five_digit_values" + in: + low: 10000 + high: 99999 + out: [12345, 23456, 34567, 45678, 56789] + - name: "five_digit_upper_window" + in: + low: 45000 + high: 60000 + out: [45678, 56789] + - name: "five_to_six_digit_transition" + in: + low: 56790 + high: 123456 + out: [123456] + - name: "all_six_digit_values" + in: + low: 100000 + high: 999999 + out: [123456, 234567, 345678, 456789] + - name: "six_digit_internal_window" + in: + low: 200000 + high: 400000 + out: [234567, 345678] + - name: "six_to_seven_digit_transition" + in: + low: 456790 + high: 1234567 + out: [1234567] + - name: "all_seven_digit_values" + in: + low: 1000000 + high: 9999999 + out: [1234567, 2345678, 3456789] + - name: "generated_near_nine_digit_boundary" + seed: 129103 + in: + low: + gen: "int" + min: 123456000 + max: 123456789 + high: + gen: "int" + min: 123456790 + max: 1000000000 + - name: "seven_to_eight_digit_transition" + in: + low: 3456790 + high: 12345678 + out: [12345678] + - name: "all_eight_digit_values" + in: + low: 10000000 + high: 99999999 + out: [12345678, 23456789] + - name: "eight_digit_internal_gap" + in: + low: 12345679 + high: 23456788 + out: [] + - name: "eight_to_nine_digit_transition" + in: + low: 23456790 + high: 123456789 + out: [123456789] + - name: "only_nine_digit_value" + in: + low: 100000000 + high: 999999999 + out: [123456789] + - name: "generated_above_all_sequential_values" + seed: 129104 + in: + low: + gen: "int" + min: 900000000 + max: 999999999 + high: + gen: "int" + min: 1000000000 + max: 1000000000 + - name: "above_largest_sequential_value" + in: + low: 123456790 + high: 1000000000 + out: [] + - name: "maximum_single_value_no_match" + in: + low: 1000000000 + high: 1000000000 + out: [] + - name: "crosses_multiple_digit_lengths" + in: + low: 500 + high: 50000 + out: + [ + 567, + 678, + 789, + 1234, + 2345, + 3456, + 4567, + 5678, + 6789, + 12345, + 23456, + 34567, + 45678, + ] + - name: "lower_cutoff_inclusive" + in: + low: 2345 + high: 6789 + out: [2345, 3456, 4567, 5678, 6789] + - name: "upper_cutoff_inclusive" + in: + low: 123 + high: 456 + out: [123, 234, 345, 456] + - name: "wide_stress_full_constraint_range" + in: + low: 10 + high: 1000000000 + out: + [ + 12, + 23, + 34, + 45, + 56, + 67, + 78, + 89, + 123, + 234, + 345, + 456, + 567, + 678, + 789, + 1234, + 2345, + 3456, + 4567, + 5678, + 6789, + 12345, + 23456, + 34567, + 45678, + 56789, + 123456, + 234567, + 345678, + 456789, + 1234567, + 2345678, + 3456789, + 12345678, + 23456789, + 123456789, + ] + - name: "generated_wide_lower_bound" + seed: 129105 + in: + low: + gen: "int" + min: 10 + max: 1000 + high: + gen: "int" + min: 999999999 + max: 1000000000 + - name: "generated_eight_digit_low_maximum_high" + seed: 129106 + in: + low: + gen: "int" + min: 12345678 + max: 23456789 + high: + gen: "int" + min: 900000000 + max: 1000000000 diff --git a/tests/1001-1500/1291. sequential-digits/sol.cpp b/tests/1001-1500/1291. sequential-digits/sol.cpp new file mode 100644 index 00000000..89c96d81 --- /dev/null +++ b/tests/1001-1500/1291. sequential-digits/sol.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + vector sequentialDigits(int low, int high) { + vector q; + for (int i = 1; i <= 9; i++) { + q.push_back(i); + } + for (int i = 0; i < q.size(); i++) { + int x = q[i]; + int d = x % 10; + if (d < 9) { + q.push_back(x * 10 + d + 1); + } + } + vector result; + for (int x : q) { + if (low <= x && x <= high) { + result.push_back(x); + } + } + return result; + } +}; diff --git a/tests/1001-1500/1291. sequential-digits/sol.cs b/tests/1001-1500/1291. sequential-digits/sol.cs new file mode 100644 index 00000000..4942c683 --- /dev/null +++ b/tests/1001-1500/1291. sequential-digits/sol.cs @@ -0,0 +1,22 @@ +public class Solution { + public IList SequentialDigits(int low, int high) { + List q = new List(); + for (int i = 1; i <= 9; i++) { + q.Add(i); + } + for (int i = 0; i < q.Count; i++) { + int x = q[i]; + int d = x % 10; + if (d < 9) { + q.Add(x * 10 + d + 1); + } + } + List result = new List(); + foreach (int x in q) { + if (low <= x && x <= high) { + result.Add(x); + } + } + return result; + } +} diff --git a/tests/1001-1500/1291. sequential-digits/sol.dart b/tests/1001-1500/1291. sequential-digits/sol.dart new file mode 100644 index 00000000..e184b602 --- /dev/null +++ b/tests/1001-1500/1291. sequential-digits/sol.dart @@ -0,0 +1,16 @@ +class Solution { + List sequentialDigits(int low, int high) { + List q = []; + for (int i = 1; i <= 9; i++) { + q.add(i); + } + for (int i = 0; i < q.length; i++) { + int x = q[i]; + int d = x % 10; + if (d < 9) { + q.add(x * 10 + d + 1); + } + } + return q.where((x) => low <= x && x <= high).toList(); + } +} diff --git a/tests/1001-1500/1291. sequential-digits/sol.go b/tests/1001-1500/1291. sequential-digits/sol.go new file mode 100644 index 00000000..0b82f017 --- /dev/null +++ b/tests/1001-1500/1291. sequential-digits/sol.go @@ -0,0 +1,20 @@ +func sequentialDigits(low int, high int) []int { + q := make([]int, 0) + for i := 1; i <= 9; i++ { + q = append(q, i) + } + for i := 0; i < len(q); i++ { + x := q[i] + d := x % 10 + if d < 9 { + q = append(q, x*10+d+1) + } + } + result := make([]int, 0) + for _, x := range q { + if low <= x && x <= high { + result = append(result, x) + } + } + return result +} diff --git a/tests/1001-1500/1291. sequential-digits/sol.java b/tests/1001-1500/1291. sequential-digits/sol.java new file mode 100644 index 00000000..7c2bb33c --- /dev/null +++ b/tests/1001-1500/1291. sequential-digits/sol.java @@ -0,0 +1,24 @@ +class Solution { + public List sequentialDigits(int low, int high) { + List q = new ArrayList<>(); + for (int i = 1; i <= 9; i++) { + q.add(i); + } + int i = 0; + while (i < q.size()) { + int x = q.get(i); + int d = x % 10; + if (d < 9) { + q.add(x * 10 + d + 1); + } + i++; + } + List result = new ArrayList<>(); + for (int num : q) { + if (low <= num && num <= high) { + result.add(num); + } + } + return result; + } +} diff --git a/tests/1001-1500/1291. sequential-digits/sol.kt b/tests/1001-1500/1291. sequential-digits/sol.kt new file mode 100644 index 00000000..21789563 --- /dev/null +++ b/tests/1001-1500/1291. sequential-digits/sol.kt @@ -0,0 +1,18 @@ +class Solution { + fun sequentialDigits(low: Int, high: Int): List { + val q = mutableListOf() + for (i in 1..9) { + q.add(i) + } + var i = 0 + while (i < q.size) { + val x = q[i] + val d = x % 10 + if (d < 9) { + q.add(x * 10 + d + 1) + } + i++ + } + return q.filter { low <= it && it <= high } + } +} diff --git a/tests/1001-1500/1291. sequential-digits/sol.py b/tests/1001-1500/1291. sequential-digits/sol.py new file mode 100644 index 00000000..2e561826 --- /dev/null +++ b/tests/1001-1500/1291. sequential-digits/sol.py @@ -0,0 +1,10 @@ +class Solution: + q = [*range(1, 10)] + + for x in q: + d = x % 10 + if d < 9: + q.append(x * 10 + d + 1) + + def sequentialDigits(self, l: int, h: int) -> list[int]: + return [x for x in self.q if l <= x <= h] diff --git a/tests/1001-1500/1291. sequential-digits/sol.py2 b/tests/1001-1500/1291. sequential-digits/sol.py2 new file mode 100644 index 00000000..1d0b6a76 --- /dev/null +++ b/tests/1001-1500/1291. sequential-digits/sol.py2 @@ -0,0 +1,13 @@ +class Solution(object): + def sequentialDigits(self, low, high): + """ + :type low: int + :type high: int + :rtype: List[int] + """ + q = list(range(1, 10)) + for x in q: + d = x % 10 + if d < 9: + q.append(x * 10 + d + 1) + return [x for x in q if low <= x <= high] diff --git a/tests/1001-1500/1291. sequential-digits/sol.rb b/tests/1001-1500/1291. sequential-digits/sol.rb new file mode 100644 index 00000000..f204f5ce --- /dev/null +++ b/tests/1001-1500/1291. sequential-digits/sol.rb @@ -0,0 +1,13 @@ +# @param {Integer} low +# @param {Integer} high +# @return {Integer[]} +def sequential_digits(low, high) + q = (1..9).to_a + q.each do |x| + d = x % 10 + if d < 9 + q << x * 10 + d + 1 + end + end + q.select { |x| low <= x && x <= high } +end diff --git a/tests/1001-1500/1291. sequential-digits/sol.rs b/tests/1001-1500/1291. sequential-digits/sol.rs new file mode 100644 index 00000000..cef690b4 --- /dev/null +++ b/tests/1001-1500/1291. sequential-digits/sol.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn sequential_digits(low: i32, high: i32) -> Vec { + let mut q: Vec = (1..=9).collect(); + let mut i = 0; + while i < q.len() { + let x = q[i]; + let d = x % 10; + if d < 9 { + q.push(x * 10 + d + 1); + } + i += 1; + } + q.into_iter().filter(|&x| low <= x && x <= high).collect() + } +} diff --git a/tests/1001-1500/1291. sequential-digits/sol.swift b/tests/1001-1500/1291. sequential-digits/sol.swift new file mode 100644 index 00000000..18569c1c --- /dev/null +++ b/tests/1001-1500/1291. sequential-digits/sol.swift @@ -0,0 +1,18 @@ +class Solution { + func sequentialDigits(_ low: Int, _ high: Int) -> [Int] { + var q: [Int] = [] + for i in 1...9 { + q.append(i) + } + var i = 0 + while i < q.count { + let x = q[i] + let d = x % 10 + if d < 9 { + q.append(x * 10 + d + 1) + } + i += 1 + } + return q.filter { low <= $0 && $0 <= high } + } +} diff --git a/tests/1001-1500/1291. sequential-digits/sol.ts b/tests/1001-1500/1291. sequential-digits/sol.ts new file mode 100644 index 00000000..de95cc00 --- /dev/null +++ b/tests/1001-1500/1291. sequential-digits/sol.ts @@ -0,0 +1,14 @@ +function sequentialDigits(low: number, high: number): number[] { + const q: number[] = []; + for (let i = 1; i <= 9; i++) { + q.push(i); + } + for (let i = 0; i < q.length; i++) { + const x = q[i]; + const d = x % 10; + if (d < 9) { + q.push(x * 10 + d + 1); + } + } + return q.filter((x) => low <= x && x <= high); +} diff --git a/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/manifest.yaml b/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/manifest.yaml new file mode 100644 index 00000000..c892b3be --- /dev/null +++ b/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/manifest.yaml @@ -0,0 +1,651 @@ +entry: + id: 1292 + title: "maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold" + params: + mat: + type: array + items: + type: array + items: + type: int + threshold: + type: int + call: + cpp: "Solution().maxSideLength({mat}, {threshold})" + rust: "Solution::max_side_length({mat}, {threshold})" + python3: "Solution().maxSideLength({mat}, {threshold})" + python2: "Solution().maxSideLength({mat}, {threshold})" + ruby: "max_side_length({mat}, {threshold})" + java: "new Solution().maxSideLength({mat}, {threshold})" + csharp: "new Solution().MaxSideLength({mat}, {threshold})" + kotlin: "Solution().maxSideLength({mat}, {threshold})" + go: "maxSideLength({mat}, {threshold})" + dart: "Solution().maxSideLength({mat}, {threshold})" + swift: "Solution().maxSideLength({mat}, {threshold})" + typescript: "maxSideLength({mat}, {threshold})" +judge: + type: "exact" +limits: + time_ms: 500 + memory_mb: 300 +oracle: + python3: + call: "Checker().maxSideLength(mat, threshold, {result})" + checker: | + class Checker: + def maxSideLength(self, mat, threshold, result): + if type(result) is not int: + return False + rows, cols = len(mat), len(mat[0]) + prefix = [[0] * (cols + 1) for _ in range(rows + 1)] + best = 0 + for row in range(rows): + for col in range(cols): + prefix[row + 1][col + 1] = ( + mat[row][col] + prefix[row][col + 1] + + prefix[row + 1][col] - prefix[row][col] + ) + for side in range(1, min(rows, cols) + 1): + for row in range(side, rows + 1): + for col in range(side, cols + 1): + total = ( + prefix[row][col] - prefix[row - side][col] + - prefix[row][col - side] + prefix[row - side][col - side] + ) + if total <= threshold: + best = side + break + if best == side: + break + return result == best +seed: 1292 +tests: + - name: "example_one" + in: + mat: + elemType: "int" + value: + - [1, 1, 3, 2, 4, 3, 2] + - [1, 1, 3, 2, 4, 3, 2] + - [1, 1, 3, 2, 4, 3, 2] + threshold: 4 + out: 2 + - name: "example_two" + in: + mat: + elemType: "int" + value: + - [2, 2, 2, 2, 2] + - [2, 2, 2, 2, 2] + - [2, 2, 2, 2, 2] + - [2, 2, 2, 2, 2] + - [2, 2, 2, 2, 2] + threshold: 1 + out: 0 + - name: "single_zero_at_zero_threshold" + in: + mat: + elemType: "int" + value: + - [0] + threshold: 0 + out: 1 + - name: "single_value_over_threshold" + in: + mat: + elemType: "int" + value: + - [10000] + threshold: 9999 + out: 0 + - name: "single_row_contains_zero" + in: + mat: + elemType: "int" + value: + - [7, 0, 8, 9, 10, 11] + threshold: 0 + out: 1 + - name: "single_column_contains_zero" + in: + mat: + elemType: "int" + value: + - [7] + - [8] + - [0] + - [9] + - [10] + - [11] + threshold: 0 + out: 1 + - name: "two_by_two_exact_total" + in: + mat: + elemType: "int" + value: + - [1, 1] + - [1, 1] + threshold: 4 + out: 2 + - name: "two_by_two_one_short" + in: + mat: + elemType: "int" + value: + - [1, 1] + - [1, 1] + threshold: 3 + out: 1 + - name: "wide_all_twos" + in: + mat: + elemType: "int" + value: + - [2, 2, 2, 2, 2] + - [2, 2, 2, 2, 2] + threshold: 8 + out: 2 + - name: "tall_all_twos" + in: + mat: + elemType: "int" + value: + - [2, 2] + - [2, 2] + - [2, 2] + - [2, 2] + - [2, 2] + threshold: 7 + out: 1 + - name: "interior_zero_square" + in: + mat: + elemType: "int" + value: + - [5, 5, 5, 5, 5] + - [5, 0, 0, 5, 5] + - [5, 0, 0, 5, 5] + threshold: 0 + out: 2 + - name: "maximum_values_three_by_three" + in: + mat: + elemType: "int" + value: + - [10000, 10000, 10000] + - [10000, 10000, 10000] + - [10000, 10000, 10000] + threshold: 100000 + out: 3 + - name: "maximum_values_four_by_four" + in: + mat: + elemType: "int" + value: + - [10000, 10000, 10000, 10000] + - [10000, 10000, 10000, 10000] + - [10000, 10000, 10000, 10000] + - [10000, 10000, 10000, 10000] + threshold: 100000 + out: 3 + - name: "increasing_values_exact_two" + in: + mat: + elemType: "int" + value: + - [1, 2, 3] + - [4, 5, 6] + - [7, 8, 9] + threshold: 12 + out: 2 + - name: "increasing_values_below_two" + in: + mat: + elemType: "int" + value: + - [1, 2, 3] + - [4, 5, 6] + - [7, 8, 9] + threshold: 11 + out: 1 + - name: "checkerboard_two_by_two_exact" + in: + mat: + elemType: "int" + value: + - [1, 3, 1] + - [3, 1, 3] + - [1, 3, 1] + threshold: 8 + out: 2 + - name: "checkerboard_below_two" + in: + mat: + elemType: "int" + value: + - [1, 3, 1] + - [3, 1, 3] + - [1, 3, 1] + threshold: 7 + out: 1 + - name: "central_zero_but_no_two_square" + in: + mat: + elemType: "int" + value: + - [9, 9, 9] + - [9, 0, 9] + - [9, 9, 9] + threshold: 26 + out: 1 + - name: "bottom_right_affordable_square" + in: + mat: + elemType: "int" + value: + - [100, 100, 100] + - [100, 1, 1] + - [100, 1, 1] + threshold: 4 + out: 2 + - name: "bottom_right_square_one_short" + in: + mat: + elemType: "int" + value: + - [100, 100, 100] + - [100, 1, 1] + - [100, 1, 1] + threshold: 3 + out: 1 + - name: "four_by_five_side_three" + 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] + threshold: 9 + out: 3 + - name: "four_by_five_side_two" + 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] + threshold: 8 + out: 2 + - name: "five_by_four_exact_maximum" + 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] + threshold: 16 + out: 4 + - name: "five_by_four_one_short" + 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] + threshold: 15 + out: 3 + - name: "ten_by_ten_large_values" + in: + mat: + elemType: "int" + value: + - [ + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + ] + - [ + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + ] + - [ + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + ] + - [ + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + ] + - [ + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + ] + - [ + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + ] + - [ + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + ] + - [ + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + ] + - [ + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + ] + - [ + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + ] + threshold: 100000 + out: 3 + - name: "ten_by_ten_all_zeros" + 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] + threshold: 0 + out: 10 + - name: "eight_by_twelve_exact_side_eight" + 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] + threshold: 64 + out: 8 + - name: "twelve_by_eight_exact_side_eight" + 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] + threshold: 64 + out: 8 + - name: "zero_corner_two_by_two" + in: + mat: + elemType: "int" + value: + - [0, 2, 2, 2] + - [2, 2, 2, 2] + - [2, 2, 2, 2] + - [2, 2, 2, 2] + threshold: 6 + out: 2 + - name: "zero_corner_below_two" + in: + mat: + elemType: "int" + value: + - [0, 2, 2, 2] + - [2, 2, 2, 2] + - [2, 2, 2, 2] + - [2, 2, 2, 2] + threshold: 5 + out: 1 + - name: "all_twos_exact_three" + in: + mat: + elemType: "int" + value: + - [2, 2, 2] + - [2, 2, 2] + - [2, 2, 2] + threshold: 18 + out: 3 + - name: "all_twos_below_three" + in: + mat: + elemType: "int" + value: + - [2, 2, 2] + - [2, 2, 2] + - [2, 2, 2] + threshold: 17 + out: 2 + - name: "alternating_five_by_five" + in: + mat: + elemType: "int" + value: + - [1, 2, 1, 2, 1] + - [2, 1, 2, 1, 2] + - [1, 2, 1, 2, 1] + - [2, 1, 2, 1, 2] + - [1, 2, 1, 2, 1] + threshold: 6 + out: 2 + - name: "generated_max_dimension_high_values" + seed: 129201 + in: + mat: + gen: "array" + len: 300 + distinct: false + sorted: false + elemType: "int" + of: + gen: "array" + len: 300 + distinct: false + sorted: false + elemType: "int" + of: + gen: "int" + min: 0 + max: 10000 + threshold: + gen: "int" + min: 0 + max: 100000 + - name: "generated_max_dimension_zero_threshold" + seed: 129202 + in: + mat: + gen: "array" + len: 300 + distinct: false + sorted: false + elemType: "int" + of: + gen: "array" + len: 300 + distinct: false + sorted: false + elemType: "int" + of: + gen: "int" + min: 0 + max: 10000 + threshold: 0 + - name: "generated_max_dimension_low_values" + seed: 129203 + in: + mat: + gen: "array" + len: 300 + distinct: false + sorted: false + elemType: "int" + of: + gen: "array" + len: 300 + distinct: false + sorted: false + elemType: "int" + of: + gen: "int" + min: 0 + max: 20 + threshold: + gen: "int" + min: 0 + max: 100000 + - name: "generated_max_dimension_small_threshold" + seed: 129204 + in: + mat: + gen: "array" + len: 300 + distinct: false + sorted: false + elemType: "int" + of: + gen: "array" + len: 300 + distinct: false + sorted: false + elemType: "int" + of: + gen: "int" + min: 0 + max: 10000 + threshold: + gen: "int" + min: 1 + max: 1000 + - name: "generated_max_dimension_threshold_boundary" + seed: 129205 + in: + mat: + gen: "array" + len: 300 + distinct: false + sorted: false + elemType: "int" + of: + gen: "array" + len: 300 + distinct: false + sorted: false + elemType: "int" + of: + gen: "int" + min: 0 + max: 10000 + threshold: + gen: "int" + min: 99900 + max: 100000 diff --git a/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.cpp b/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.cpp new file mode 100644 index 00000000..93f1c4a1 --- /dev/null +++ b/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.cpp @@ -0,0 +1,44 @@ +class Solution { +public: + int maxSideLength(vector>& mat, int threshold) { + int n = mat.size(); + int m = mat[0].size(); + vector> pref = mat; + for (int i = 0; i < n; i++) { + for (int j = 1; j < m; j++) { + pref[i][j] += pref[i][j - 1]; + } + } + for (int j = 0; j < m; j++) { + for (int i = 1; i < n; i++) { + pref[i][j] += pref[i - 1][j]; + } + } + auto isValid = [&](int k) { + for (int i = k - 1; i < n; i++) { + for (int j = k - 1; j < m; j++) { + int x1 = i - k + 1; + int y1 = j - k + 1; + int total = pref[i][j]; + if (x1 > 0) total -= pref[x1 - 1][j]; + if (y1 > 0) total -= pref[i][y1 - 1]; + if (x1 > 0 && y1 > 0) total += pref[x1 - 1][y1 - 1]; + if (total <= threshold) return true; + } + } + return false; + }; + int low = 1, high = min(n, m); + int ans = 0; + while (low <= high) { + int mid = (low + high) / 2; + if (isValid(mid)) { + ans = mid; + low = mid + 1; + } else { + high = mid - 1; + } + } + return ans; + } +}; diff --git a/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.cs b/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.cs new file mode 100644 index 00000000..18980097 --- /dev/null +++ b/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.cs @@ -0,0 +1,47 @@ +public class Solution { + public int MaxSideLength(int[][] mat, int threshold) { + int n = mat.Length; + int m = mat[0].Length; + int[][] pref = new int[n][]; + for (int i = 0; i < n; i++) { + pref[i] = new int[m]; + Array.Copy(mat[i], pref[i], m); + } + for (int i = 0; i < n; i++) { + for (int j = 1; j < m; j++) { + pref[i][j] += pref[i][j - 1]; + } + } + for (int j = 0; j < m; j++) { + for (int i = 1; i < n; i++) { + pref[i][j] += pref[i - 1][j]; + } + } + bool IsValid(int k) { + for (int i = k - 1; i < n; i++) { + for (int j = k - 1; j < m; j++) { + int x1 = i - k + 1; + int y1 = j - k + 1; + int total = pref[i][j]; + if (x1 > 0) total -= pref[x1 - 1][j]; + if (y1 > 0) total -= pref[i][y1 - 1]; + if (x1 > 0 && y1 > 0) total += pref[x1 - 1][y1 - 1]; + if (total <= threshold) return true; + } + } + return false; + } + int low = 1, high = Math.Min(n, m); + int ans = 0; + while (low <= high) { + int mid = (low + high) / 2; + if (IsValid(mid)) { + ans = mid; + low = mid + 1; + } else { + high = mid - 1; + } + } + return ans; + } +} diff --git a/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.dart b/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.dart new file mode 100644 index 00000000..f39bfeff --- /dev/null +++ b/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.dart @@ -0,0 +1,43 @@ +class Solution { + int maxSideLength(List> mat, int threshold) { + int n = mat.length; + int m = mat[0].length; + List> pref = List.generate(n, (i) => List.from(mat[i])); + for (int i = 0; i < n; i++) { + for (int j = 1; j < m; j++) { + pref[i][j] += pref[i][j - 1]; + } + } + for (int j = 0; j < m; j++) { + for (int i = 1; i < n; i++) { + pref[i][j] += pref[i - 1][j]; + } + } + bool isValid(int k) { + for (int i = k - 1; i < n; i++) { + for (int j = k - 1; j < m; j++) { + int x1 = i - k + 1; + int y1 = j - k + 1; + int total = pref[i][j]; + if (x1 > 0) total -= pref[x1 - 1][j]; + if (y1 > 0) total -= pref[i][y1 - 1]; + if (x1 > 0 && y1 > 0) total += pref[x1 - 1][y1 - 1]; + if (total <= threshold) return true; + } + } + return false; + } + int low = 1, high = n < m ? n : m; + int ans = 0; + while (low <= high) { + int mid = (low + high) ~/ 2; + if (isValid(mid)) { + ans = mid; + low = mid + 1; + } else { + high = mid - 1; + } + } + return ans; + } +} diff --git a/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.go b/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.go new file mode 100644 index 00000000..0e6d92d4 --- /dev/null +++ b/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.go @@ -0,0 +1,53 @@ +func maxSideLength(mat [][]int, threshold int) int { + n := len(mat) + m := len(mat[0]) + pref := make([][]int, n) + for i := 0; i < n; i++ { + pref[i] = make([]int, m) + copy(pref[i], mat[i]) + } + for i := 0; i < n; i++ { + for j := 1; j < m; j++ { + pref[i][j] += pref[i][j-1] + } + } + for j := 0; j < m; j++ { + for i := 1; i < n; i++ { + pref[i][j] += pref[i-1][j] + } + } + isValid := func(k int) bool { + for i := k - 1; i < n; i++ { + for j := k - 1; j < m; j++ { + x1 := i - k + 1 + y1 := j - k + 1 + total := pref[i][j] + if x1 > 0 { + total -= pref[x1-1][j] + } + if y1 > 0 { + total -= pref[i][y1-1] + } + if x1 > 0 && y1 > 0 { + total += pref[x1-1][y1-1] + } + if total <= threshold { + return true + } + } + } + return false + } + low, high := 1, min(n, m) + ans := 0 + for low <= high { + mid := (low + high) / 2 + if isValid(mid) { + ans = mid + low = mid + 1 + } else { + high = mid - 1 + } + } + return ans +} diff --git a/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.java b/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.java new file mode 100644 index 00000000..8dabf04a --- /dev/null +++ b/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.java @@ -0,0 +1,51 @@ +class Solution { + public int maxSideLength(int[][] mat, int threshold) { + int n = mat.length; + int m = mat[0].length; + int[][] pref = new int[n][m]; + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + pref[i][j] = mat[i][j]; + } + } + for (int i = 0; i < n; i++) { + for (int j = 1; j < m; j++) { + pref[i][j] += pref[i][j - 1]; + } + } + for (int j = 0; j < m; j++) { + for (int i = 1; i < n; i++) { + pref[i][j] += pref[i - 1][j]; + } + } + int low = 1, high = Math.min(n, m); + int ans = 0; + while (low <= high) { + int mid = (low + high) / 2; + if (isValid(pref, mid, threshold)) { + ans = mid; + low = mid + 1; + } else { + high = mid - 1; + } + } + return ans; + } + + private boolean isValid(int[][] pref, int k, int limit) { + int n = pref.length; + int m = pref[0].length; + for (int i = k - 1; i < n; i++) { + for (int j = k - 1; j < m; j++) { + int x1 = i - k + 1; + int y1 = j - k + 1; + int total = pref[i][j]; + if (x1 > 0) total -= pref[x1 - 1][j]; + if (y1 > 0) total -= pref[i][y1 - 1]; + if (x1 > 0 && y1 > 0) total += pref[x1 - 1][y1 - 1]; + if (total <= limit) return true; + } + } + return false; + } +} diff --git a/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.kt b/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.kt new file mode 100644 index 00000000..f592470f --- /dev/null +++ b/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.kt @@ -0,0 +1,44 @@ +class Solution { + fun maxSideLength(mat: Array, threshold: Int): Int { + val n = mat.size + val m = mat[0].size + val pref = Array(n) { mat[it].copyOf() } + for (i in 0 until n) { + for (j in 1 until m) { + pref[i][j] += pref[i][j - 1] + } + } + for (j in 0 until m) { + for (i in 1 until n) { + pref[i][j] += pref[i - 1][j] + } + } + fun isValid(k: Int): Boolean { + for (i in k - 1 until n) { + for (j in k - 1 until m) { + val x1 = i - k + 1 + val y1 = j - k + 1 + var total = pref[i][j] + if (x1 > 0) total -= pref[x1 - 1][j] + if (y1 > 0) total -= pref[i][y1 - 1] + if (x1 > 0 && y1 > 0) total += pref[x1 - 1][y1 - 1] + if (total <= threshold) return true + } + } + return false + } + var low = 1 + var high = minOf(n, m) + var ans = 0 + while (low <= high) { + val mid = (low + high) / 2 + if (isValid(mid)) { + ans = mid + low = mid + 1 + } else { + high = mid - 1 + } + } + return ans + } +} diff --git a/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.py b/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.py new file mode 100644 index 00000000..07ad87fb --- /dev/null +++ b/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.py @@ -0,0 +1,51 @@ +class Solution: + def isValid(self, pref, k, limit): + n = len(pref) + m = len(pref[0]) + + for i in range(k - 1, n): + for j in range(k - 1, m): + x1 = i - k + 1 + y1 = j - k + 1 + + total = pref[i][j] + if x1 > 0: + total -= pref[x1 - 1][j] + if y1 > 0: + total -= pref[i][y1 - 1] + if x1 > 0 and y1 > 0: + total += pref[x1 - 1][y1 - 1] + + if total <= limit: + return True + + return False + + def maxSideLength(self, mat, threshold): + n = len(mat) + m = len(mat[0]) + + pref = [row[:] for row in mat] + + # Row-wise prefix sum + for i in range(n): + for j in range(1, m): + pref[i][j] += pref[i][j - 1] + + # Column-wise prefix sum + for j in range(m): + for i in range(1, n): + pref[i][j] += pref[i - 1][j] + + low, high = 1, min(n, m) + ans = 0 + + while low <= high: + mid = (low + high) // 2 + if self.isValid(pref, mid, threshold): + ans = mid + low = mid + 1 + else: + high = mid - 1 + + return ans diff --git a/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.py2 b/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.py2 new file mode 100644 index 00000000..0596324b --- /dev/null +++ b/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.py2 @@ -0,0 +1,44 @@ +class Solution(object): + def maxSideLength(self, mat, threshold): + """ + :type mat: List[List[int]] + :type threshold: int + :rtype: int + """ + def isValid(pref, k, limit): + n = len(pref) + m = len(pref[0]) + for i in range(k - 1, n): + for j in range(k - 1, m): + x1 = i - k + 1 + y1 = j - k + 1 + total = pref[i][j] + if x1 > 0: + total -= pref[x1 - 1][j] + if y1 > 0: + total -= pref[i][y1 - 1] + if x1 > 0 and y1 > 0: + total += pref[x1 - 1][y1 - 1] + if total <= limit: + return True + return False + + n = len(mat) + m = len(mat[0]) + pref = [row[:] for row in mat] + for i in range(n): + for j in range(1, m): + pref[i][j] += pref[i][j - 1] + for j in range(m): + for i in range(1, n): + pref[i][j] += pref[i - 1][j] + low, high = 1, min(n, m) + ans = 0 + while low <= high: + mid = (low + high) // 2 + if isValid(pref, mid, threshold): + ans = mid + low = mid + 1 + else: + high = mid - 1 + return ans diff --git a/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.rb b/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.rb new file mode 100644 index 00000000..05bf695e --- /dev/null +++ b/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.rb @@ -0,0 +1,47 @@ +# @param {Integer[][]} mat +# @param {Integer} threshold +# @return {Integer} +def max_side_length(mat, threshold) + is_valid = ->(pref, k, limit) { + n = pref.length + m = pref[0].length + (k - 1...n).each do |i| + (k - 1...m).each do |j| + x1 = i - k + 1 + y1 = j - k + 1 + total = pref[i][j] + total -= pref[x1 - 1][j] if x1 > 0 + total -= pref[i][y1 - 1] if y1 > 0 + total += pref[x1 - 1][y1 - 1] if x1 > 0 && y1 > 0 + return true if total <= limit + end + end + false + } + + n = mat.length + m = mat[0].length + pref = mat.map(&:dup) + (0...n).each do |i| + (1...m).each do |j| + pref[i][j] += pref[i][j - 1] + end + end + (0...m).each do |j| + (1...n).each do |i| + pref[i][j] += pref[i - 1][j] + end + end + low, high = 1, [n, m].min + ans = 0 + while low <= high + mid = (low + high) / 2 + if is_valid.call(pref, mid, threshold) + ans = mid + low = mid + 1 + else + high = mid - 1 + end + end + ans +end diff --git a/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.rs b/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.rs new file mode 100644 index 00000000..5d9a801c --- /dev/null +++ b/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.rs @@ -0,0 +1,52 @@ +impl Solution { + pub fn max_side_length(mat: Vec>, threshold: i32) -> i32 { + let n = mat.len(); + let m = mat[0].len(); + let mut pref = mat.clone(); + for i in 0..n { + for j in 1..m { + pref[i][j] += pref[i][j - 1]; + } + } + for j in 0..m { + for i in 1..n { + pref[i][j] += pref[i - 1][j]; + } + } + let is_valid = |k: usize| -> bool { + for i in (k - 1)..n { + for j in (k - 1)..m { + let x1 = i - k + 1; + let y1 = j - k + 1; + let mut total = pref[i][j]; + if x1 > 0 { + total -= pref[x1 - 1][j]; + } + if y1 > 0 { + total -= pref[i][y1 - 1]; + } + if x1 > 0 && y1 > 0 { + total += pref[x1 - 1][y1 - 1]; + } + if total <= threshold { + return true; + } + } + } + false + }; + let mut low = 1; + let mut high = n.min(m); + let mut ans = 0; + while low <= high { + let mid = (low + high) / 2; + if is_valid(mid) { + ans = mid; + low = mid + 1; + } else { + high = mid - 1; + } + } + ans as i32 + } +} diff --git a/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.swift b/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.swift new file mode 100644 index 00000000..7bfc6b4e --- /dev/null +++ b/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.swift @@ -0,0 +1,43 @@ +class Solution { + func maxSideLength(_ mat: [[Int]], _ threshold: Int) -> Int { + let n = mat.count + let m = mat[0].count + var pref = mat + for i in 0.. Bool { + for i in (k - 1).. 0 { total -= pref[x1 - 1][j] } + if y1 > 0 { total -= pref[i][y1 - 1] } + if x1 > 0 && y1 > 0 { total += pref[x1 - 1][y1 - 1] } + if total <= threshold { return true } + } + } + return false + } + var low = 1, high = min(n, m) + var ans = 0 + while low <= high { + let mid = (low + high) / 2 + if isValid(mid) { + ans = mid + low = mid + 1 + } else { + high = mid - 1 + } + } + return ans + } +} diff --git a/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.ts b/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.ts new file mode 100644 index 00000000..6d629709 --- /dev/null +++ b/tests/1001-1500/1292. maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/sol.ts @@ -0,0 +1,42 @@ +function maxSideLength(mat: number[][], threshold: number): number { + const n = mat.length; + const m = mat[0].length; + const pref: number[][] = mat.map((row) => [...row]); + for (let i = 0; i < n; i++) { + for (let j = 1; j < m; j++) { + pref[i][j] += pref[i][j - 1]; + } + } + for (let j = 0; j < m; j++) { + for (let i = 1; i < n; i++) { + pref[i][j] += pref[i - 1][j]; + } + } + const isValid = (k: number): boolean => { + for (let i = k - 1; i < n; i++) { + for (let j = k - 1; j < m; j++) { + const x1 = i - k + 1; + const y1 = j - k + 1; + let total = pref[i][j]; + if (x1 > 0) total -= pref[x1 - 1][j]; + if (y1 > 0) total -= pref[i][y1 - 1]; + if (x1 > 0 && y1 > 0) total += pref[x1 - 1][y1 - 1]; + if (total <= threshold) return true; + } + } + return false; + }; + let low = 1, + high = Math.min(n, m); + let ans = 0; + while (low <= high) { + const mid = Math.floor((low + high) / 2); + if (isValid(mid)) { + ans = mid; + low = mid + 1; + } else { + high = mid - 1; + } + } + return ans; +} diff --git a/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/manifest.yaml b/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/manifest.yaml new file mode 100644 index 00000000..3de1fcd5 --- /dev/null +++ b/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/manifest.yaml @@ -0,0 +1,1104 @@ +entry: + id: 1293 + title: shortest-path-in-a-grid-with-obstacles-elimination + params: + grid: + type: array + items: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().shortestPath({grid}, {k})" + rust: "Solution::shortest_path({grid}, {k})" + python3: "Solution().shortestPath({grid}, {k})" + python2: "Solution().shortestPath({grid}, {k})" + ruby: "shortest_path({grid}, {k})" + java: "new Solution().shortestPath({grid}, {k})" + csharp: "new Solution().ShortestPath({grid}, {k})" + kotlin: "Solution().shortestPath({grid}, {k})" + go: "shortestPath({grid}, {k})" + dart: "Solution().shortestPath({grid}, {k})" + swift: "Solution().shortestPath({grid}, {k})" + typescript: "shortestPath({grid}, {k})" +judge: + type: exact +limits: + time_ms: 1500 + memory_mb: 256 +oracle: + python3: + call: "Checker().shortestPath(grid, k, {result})" + checker: | + class Checker: + def shortestPath(self, grid, k, result): + if not isinstance(grid, list) or not grid or not isinstance(k, int) or isinstance(k, bool) or k < 1: + return False + rows, cols = len(grid), len(grid[0]) + if rows > 40 or cols < 1 or cols > 40 or k > rows * cols or any(not isinstance(row, list) or len(row) != cols for row in grid): + return False + if any(cell not in (0, 1) for row in grid for cell in row) or grid[0][0] != 0 or grid[-1][-1] != 0: + return False + if not isinstance(result, int) or isinstance(result, bool): + return False + queue = [(0, 0, k, 0)] + seen = {(0, 0, k)} + head = 0 + while head < len(queue): + r, c, remaining, distance = queue[head] + head += 1 + if r == rows - 1 and c == cols - 1: + return result == distance + 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: + next_remaining = remaining - grid[nr][nc] + state = (nr, nc, next_remaining) + if next_remaining >= 0 and state not in seen: + seen.add(state) + queue.append((nr, nc, next_remaining, distance + 1)) + return result == -1 +seed: 1293 +tests: + - name: single_cell + in: + grid: + - [0] + k: 1 + out: 0 + - name: single_row_clear + in: + grid: + - [0, 0, 0, 0, 0] + k: 1 + out: 4 + - name: single_row_obstacles + in: + grid: + - [0, 1, 1, 1, 0] + k: 3 + out: 4 + - name: single_column_clear + in: + grid: + - [0] + - [0] + - [0] + - [0] + k: 1 + out: 3 + - name: single_column_blocked + in: + grid: + - [0] + - [1] + - [1] + - [0] + k: 1 + out: -1 + - name: example_one + in: + grid: + - [0, 0, 0] + - [1, 1, 0] + - [0, 0, 0] + - [0, 1, 1] + - [0, 0, 0] + k: 1 + out: 6 + - name: example_two + in: + grid: + - [0, 1, 1] + - [1, 1, 1] + - [1, 0, 0] + k: 1 + out: -1 + - name: clear_two_by_two + in: + grid: + - [0, 0] + - [0, 0] + k: 1 + out: 2 + - name: one_block_two_by_two + in: + grid: + - [0, 1] + - [0, 0] + k: 1 + out: 2 + - name: no_route_without_elimination + in: + grid: + - [0, 1, 0] + - [1, 1, 1] + - [0, 1, 0] + k: 1 + out: -1 + - name: route_with_elimination + in: + grid: + - [0, 1, 0] + - [1, 1, 1] + - [0, 1, 0] + k: 4 + out: 4 + - name: open_border + in: + grid: + - [0, 0, 0, 0] + - [1, 1, 1, 0] + - [0, 0, 0, 0] + k: 1 + out: 5 + - name: central_wall + in: + grid: + - [0, 0, 0] + - [0, 1, 0] + - [0, 0, 0] + k: 1 + out: 4 + - name: three_by_three_all_interior_obstacles + in: + grid: + - [0, 0, 0] + - [1, 1, 1] + - [0, 0, 0] + k: 3 + out: 4 + - name: zigzag_obstacles + in: + grid: + - [0, 1, 0, 1, 0] + - [0, 1, 0, 1, 0] + - [0, 0, 0, 1, 0] + k: 1 + out: 6 + - name: dense_four_by_four + in: + grid: + - [0, 1, 1, 0] + - [0, 1, 1, 0] + - [0, 0, 0, 1] + - [1, 1, 0, 0] + k: 2 + out: 6 + - name: dense_requires_three + in: + grid: + - [0, 1, 1, 1] + - [0, 1, 0, 1] + - [0, 1, 0, 1] + - [0, 0, 0, 0] + k: 2 + out: 6 + - name: detour_beats_wall + in: + grid: + - [0, 1, 1, 1, 0] + - [0, 0, 0, 1, 0] + - [1, 1, 0, 0, 0] + k: 1 + out: 6 + - name: checkerboard_small + in: + grid: + - [0, 1, 0, 1] + - [1, 0, 1, 0] + - [0, 1, 0, 1] + - [1, 0, 1, 0] + k: 2 + out: -1 + - name: checkerboard_budget_zero + in: + grid: + - [0, 1, 0] + - [1, 0, 1] + - [0, 1, 0] + k: 1 + out: -1 + - name: all_obstacles_interior + in: + grid: + - [0, 1, 1, 1, 0] + - [1, 1, 1, 1, 1] + - [0, 1, 1, 1, 0] + k: 5 + out: 6 + - name: long_clear_corridor + in: + grid: + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + k: 1 + out: 9 + - name: long_wall + in: + grid: + - [0, 1, 1, 1, 1, 1, 1, 1, 1, 0] + k: 8 + out: 9 + - name: five_by_five_clear + in: + grid: + - [0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0] + k: 1 + out: 8 + - name: five_by_five_diagonal + in: + grid: + - [0, 1, 1, 1, 1] + - [0, 0, 1, 1, 1] + - [1, 0, 0, 1, 1] + - [1, 1, 0, 0, 1] + - [1, 1, 1, 0, 0] + k: 2 + out: 8 + - name: five_by_five_barriers + in: + grid: + - [0, 1, 0, 1, 0] + - [0, 1, 0, 1, 0] + - [0, 1, 0, 1, 0] + - [0, 1, 0, 1, 0] + - [0, 0, 0, 0, 0] + k: 1 + out: 8 + - name: six_by_six_sparse + in: + grid: + - [0, 0, 1, 0, 0, 0] + - [1, 0, 1, 0, 1, 0] + - [0, 0, 0, 0, 1, 0] + - [0, 1, 1, 1, 1, 0] + - [0, 0, 0, 0, 1, 0] + - [0, 1, 0, 0, 0, 0] + k: 2 + out: 10 + - name: six_by_six_dense + in: + grid: + - [0, 1, 1, 1, 1, 1] + - [0, 1, 0, 0, 0, 1] + - [0, 1, 0, 1, 0, 1] + - [0, 1, 0, 1, 0, 1] + - [0, 0, 0, 1, 0, 0] + - [1, 1, 0, 1, 1, 0] + k: 3 + out: 10 + - name: seven_by_three + in: + grid: + - [0, 1, 0] + - [0, 1, 0] + - [0, 1, 0] + - [0, 1, 0] + - [0, 1, 0] + - [0, 1, 0] + - [0, 0, 0] + k: 1 + out: 8 + - name: three_by_seven + in: + grid: + - [0, 1, 1, 1, 1, 1, 0] + - [0, 0, 0, 0, 0, 1, 0] + - [1, 1, 1, 1, 0, 0, 0] + k: 2 + out: 8 + - name: eight_by_eight_open + in: + grid: + - [0, 0, 0, 0, 0, 0, 0, 0] + - [0, 1, 1, 1, 1, 1, 1, 0] + - [0, 0, 0, 0, 0, 0, 0, 0] + - [0, 1, 1, 1, 1, 1, 1, 0] + - [0, 0, 0, 0, 0, 0, 0, 0] + - [0, 1, 1, 1, 1, 1, 1, 0] + - [0, 0, 0, 0, 0, 0, 0, 0] + - [0, 1, 1, 1, 1, 1, 1, 0] + k: 1 + out: 14 + - name: eight_by_eight_budget + in: + grid: + - [0, 1, 1, 1, 1, 1, 1, 0] + - [1, 1, 1, 1, 1, 1, 1, 1] + - [0, 1, 0, 0, 0, 0, 1, 0] + - [0, 1, 0, 1, 1, 0, 1, 0] + - [0, 1, 0, 0, 0, 0, 1, 0] + - [0, 1, 1, 1, 1, 1, 1, 0] + - [0, 0, 0, 0, 0, 0, 0, 0] + - [1, 1, 1, 1, 1, 1, 1, 0] + k: 5 + out: 14 + - name: narrow_turns + in: + grid: + - [0, 1, 0, 0] + - [0, 1, 0, 1] + - [0, 0, 0, 1] + - [1, 1, 0, 0] + k: 1 + out: 6 + - name: two_routes_different_cost + in: + grid: + - [0, 1, 0, 0, 0] + - [0, 1, 0, 1, 0] + - [0, 0, 0, 1, 0] + - [1, 1, 1, 1, 0] + k: 2 + out: 7 + - name: nine_by_two_column + in: + grid: + - [0, 1] + - [0, 1] + - [0, 1] + - [0, 1] + - [0, 1] + - [0, 1] + - [0, 1] + - [0, 1] + - [0, 0] + k: 1 + out: 9 + - name: max_height_clear_column + in: + grid: + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + k: 1 + out: 39 + - name: near_max_height_obstacle_column_exact_budget + in: + grid: + - [0] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [0] + k: 37 + out: 38 + - name: near_max_height_obstacle_column_insufficient_budget + in: + grid: + - [0] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [0] + k: 36 + out: -1 + - name: large_width_open_grid + in: + grid: + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + k: 1 + out: 42 + - name: large_ten_by_forty_open_grid + in: + grid: + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + k: 1 + out: 48 diff --git a/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.cpp b/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.cpp new file mode 100644 index 00000000..2ebaef04 --- /dev/null +++ b/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int shortestPath(vector>& grid, int k) { + int n = grid.size(), m = grid[0].size(); + queue> q; + q.push({0, 0, k, 0}); + set> visi; + visi.insert({0, 0, k}); + vector> dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; + while (!q.empty()) { + auto cur = q.front(); q.pop(); + int r = cur[0], c = cur[1], k_rem = cur[2], d = cur[3]; + if (r == n - 1 && c == m - 1) return d; + if (grid[r][c] == 1) k_rem--; + for (auto [dr, dc] : dirs) { + int nr = r + dr, nc = c + dc; + if (nr >= 0 && nr < n && nc >= 0 && nc < m) { + if (visi.find({nr, nc, k_rem}) == visi.end() && k_rem >= 0) { + visi.insert({nr, nc, k_rem}); + q.push({nr, nc, k_rem, d + 1}); + } + } + } + } + return -1; + } +}; diff --git a/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.cs b/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.cs new file mode 100644 index 00000000..e63bdd40 --- /dev/null +++ b/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.cs @@ -0,0 +1,27 @@ +public class Solution { + public int ShortestPath(int[][] grid, int k) { + int n = grid.Length, m = grid[0].Length; + var q = new Queue(); + q.Enqueue(new int[]{0, 0, k, 0}); + var visi = new HashSet(); + visi.Add("0,0," + k); + int[][] dirs = new int[][]{new int[]{-1, 0}, new int[]{0, 1}, new int[]{1, 0}, new int[]{0, -1}}; + while (q.Count > 0) { + var cur = q.Dequeue(); + int r = cur[0], c = cur[1], kRem = cur[2], d = cur[3]; + if (r == n - 1 && c == m - 1) return d; + if (grid[r][c] == 1) kRem--; + foreach (var dir in dirs) { + int nr = r + dir[0], nc = c + dir[1]; + if (nr >= 0 && nr < n && nc >= 0 && nc < m) { + var key = nr + "," + nc + "," + kRem; + if (!visi.Contains(key) && kRem >= 0) { + visi.Add(key); + q.Enqueue(new int[]{nr, nc, kRem, d + 1}); + } + } + } + } + return -1; + } +} diff --git a/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.dart b/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.dart new file mode 100644 index 00000000..50c5c852 --- /dev/null +++ b/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.dart @@ -0,0 +1,34 @@ +class Solution { + int shortestPath(List> grid, int k) { + int n = grid.length, m = grid[0].length; + var q = Queue(); + q.add([0, 0, k, 0]); + var visi = {}; + visi.add("0,0,$k"); + var dirs = [[-1, 0], [0, 1], [1, 0], [0, -1]]; + while (q.isNotEmpty) { + var cur = q.removeFirst(); + int r = cur[0], c = cur[1], kRem = cur[2], d = cur[3]; + if (r == n - 1 && c == m - 1) return d; + if (grid[r][c] == 1) kRem--; + for (var dir in dirs) { + int nr = r + dir[0], nc = c + dir[1]; + if (nr >= 0 && nr < n && nc >= 0 && nc < m) { + var key = "$nr,$nc,$kRem"; + if (!visi.contains(key) && kRem >= 0) { + visi.add(key); + q.add([nr, nc, kRem, d + 1]); + } + } + } + } + return -1; + } +} + +class Queue { + final List> _list = []; + void add(List val) => _list.add(val); + bool get isNotEmpty => _list.isNotEmpty; + List removeFirst() => _list.removeAt(0); +} diff --git a/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.go b/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.go new file mode 100644 index 00000000..039df4f2 --- /dev/null +++ b/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.go @@ -0,0 +1,29 @@ +func shortestPath(grid [][]int, k int) int { + n, m := len(grid), len(grid[0]) + type state struct{ r, c, k_rem, d int } + q := []state{{0, 0, k, 0}} + visi := make(map[[3]int]bool) + visi[[3]int{0, 0, k}] = true + dirs := [][2]int{{-1, 0}, {0, 1}, {1, 0}, {0, -1}} + for len(q) > 0 { + cur := q[0] + q = q[1:] + r, c, k_rem, d := cur.r, cur.c, cur.k_rem, cur.d + if r == n-1 && c == m-1 { + return d + } + if grid[r][c] == 1 { + k_rem-- + } + for _, dir := range dirs { + nr, nc := r+dir[0], c+dir[1] + if nr >= 0 && nr < n && nc >= 0 && nc < m { + if !visi[[3]int{nr, nc, k_rem}] && k_rem >= 0 { + visi[[3]int{nr, nc, k_rem}] = true + q = append(q, state{nr, nc, k_rem, d + 1}) + } + } + } + } + return -1 +} diff --git a/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.java b/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.java new file mode 100644 index 00000000..618f5825 --- /dev/null +++ b/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.java @@ -0,0 +1,27 @@ +class Solution { + public int shortestPath(int[][] grid, int k) { + int n = grid.length, m = grid[0].length; + var q = new java.util.ArrayDeque(); + q.add(new int[]{0, 0, k, 0}); + var visi = new java.util.HashSet(); + visi.add(0 + "," + 0 + "," + k); + int[][] dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; + while (!q.isEmpty()) { + int[] cur = q.poll(); + int r = cur[0], c = cur[1], k_rem = cur[2], d = cur[3]; + if (r == n - 1 && c == m - 1) return d; + if (grid[r][c] == 1) k_rem--; + for (int[] dir : dirs) { + int nr = r + dir[0], nc = c + dir[1]; + if (nr >= 0 && nr < n && nc >= 0 && nc < m) { + String key = nr + "," + nc + "," + k_rem; + if (!visi.contains(key) && k_rem >= 0) { + visi.add(key); + q.add(new int[]{nr, nc, k_rem, d + 1}); + } + } + } + } + return -1; + } +} diff --git a/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.kt b/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.kt new file mode 100644 index 00000000..241a6cd9 --- /dev/null +++ b/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.kt @@ -0,0 +1,29 @@ +class Solution { + fun shortestPath(grid: Array, k: Int): Int { + val n = grid.size + val m = grid[0].size + val q = ArrayDeque() + q.add(intArrayOf(0, 0, k, 0)) + val visi = HashSet() + visi.add("0,0,$k") + val dirs = arrayOf(intArrayOf(-1, 0), intArrayOf(0, 1), intArrayOf(1, 0), intArrayOf(0, -1)) + while (q.isNotEmpty()) { + val (r, c, kRem, d) = q.removeFirst() + if (r == n - 1 && c == m - 1) return d + var kRem2 = kRem + if (grid[r][c] == 1) kRem2-- + for ((dr, dc) in dirs) { + val nr = r + dr + val nc = c + dc + if (nr in 0 until n && nc in 0 until m) { + val key = "$nr,$nc,$kRem2" + if (key !in visi && kRem2 >= 0) { + visi.add(key) + q.add(intArrayOf(nr, nc, kRem2, d + 1)) + } + } + } + } + return -1 + } +} diff --git a/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.py b/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.py new file mode 100644 index 00000000..57d91db4 --- /dev/null +++ b/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.py @@ -0,0 +1,43 @@ +from collections import deque + + +class Solution: + def shortestPath(self, grid: List[List[int]], k: int) -> int: + n, m = len(grid), len(grid[0]) + + # ============================================================================================================================ + # q = deque() + # q.append((0, 0,k,0)) #r,c,k,d #ALWAYS Prefer(d,r,c) rather than (r,c,d) + q = deque([(0, 0, k, 0)]) + + visi = set() + visi.add((0, 0, k)) # ALWAYS prefer to mark visited while pushing | + # ⭐️✅ Don'tput (d) in(set tuple) + # -------------------------------------------------------------------------- + while q: + r, c, k, d = q.popleft() + + # ----------------------------------------------- + if (r, c) == (n - 1, m - 1): # REACHED ALREADY ANSWRRR + return d + + if grid[r][c] == 1: # IF ITS AN OBSTACLE + k -= 1 # going through obstacle spend one k + + # ----------------------------------------------- + for dr, dc in [[-1, 0], [0, 1], [1, 0], [0, -1]]: + nr, nc = r + dr, c + dc + + if 0 <= nr < n and 0 <= nc < m: # inbounds check + if ( + (nr, nc, k) not in visi + ) and k >= 0: # ONLY FOR Positive remaingin k + visi.add( + (nr, nc, k) + ) # ⭐️✅ Don't put (d+1) also in the (set tuple) + q.append((nr, nc, k, d + 1)) + # ----------------------------------------------- + + return -1 # last option noting found + + # ============================================================================================================================ diff --git a/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.py2 b/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.py2 new file mode 100644 index 00000000..4f45cf8b --- /dev/null +++ b/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.py2 @@ -0,0 +1,25 @@ +class Solution(object): + def shortestPath(self, grid, k): + """ + :type grid: List[List[int]] + :type k: int + :rtype: int + """ + from collections import deque + n, m = len(grid), len(grid[0]) + q = deque([(0, 0, k, 0)]) + visi = set() + visi.add((0, 0, k)) + while q: + r, c, k_rem, d = q.popleft() + if (r, c) == (n - 1, m - 1): + return d + if grid[r][c] == 1: + k_rem -= 1 + for dr, dc in [(-1, 0), (0, 1), (1, 0), (0, -1)]: + nr, nc = r + dr, c + dc + if 0 <= nr < n and 0 <= nc < m: + if (nr, nc, k_rem) not in visi and k_rem >= 0: + visi.add((nr, nc, k_rem)) + q.append((nr, nc, k_rem, d + 1)) + return -1 diff --git a/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.rb b/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.rb new file mode 100644 index 00000000..1b4980d3 --- /dev/null +++ b/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.rb @@ -0,0 +1,25 @@ +# @param {Integer[][]} grid +# @param {Integer} k +# @return {Integer} +def shortest_path(grid, k) + n, m = grid.length, grid[0].length + q = [[0, 0, k, 0]] + visi = Set.new + visi.add([0, 0, k]) + dirs = [[-1, 0], [0, 1], [1, 0], [0, -1]] + while !q.empty? + r, c, k_rem, d = q.shift + return d if r == n - 1 && c == m - 1 + k_rem -= 1 if grid[r][c] == 1 + dirs.each do |dr, dc| + nr, nc = r + dr, c + dc + if nr >= 0 && nr < n && nc >= 0 && nc < m + if !visi.include?([nr, nc, k_rem]) && k_rem >= 0 + visi.add([nr, nc, k_rem]) + q.push([nr, nc, k_rem, d + 1]) + end + end + end + end + -1 +end diff --git a/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.rs b/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.rs new file mode 100644 index 00000000..93f39621 --- /dev/null +++ b/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.rs @@ -0,0 +1,33 @@ +impl Solution { + pub fn shortest_path(grid: Vec>, k: i32) -> i32 { + let n = grid.len(); + let m = grid[0].len(); + let mut q = std::collections::VecDeque::new(); + q.push_back((0, 0, k, 0)); + let mut visi = std::collections::HashSet::new(); + visi.insert((0, 0, k)); + let dirs = [(-1, 0), (0, 1), (1, 0), (0, -1)]; + while let Some((r, c, k_rem, d)) = q.pop_front() { + if r == n - 1 && c == m - 1 { + return d; + } + let mut new_k = k_rem; + if grid[r][c] == 1 { + new_k -= 1; + } + for (dr, dc) in dirs { + let nr = r as i32 + dr; + let nc = c as i32 + dc; + if nr >= 0 && nr < n as i32 && nc >= 0 && nc < m as i32 { + let nr = nr as usize; + let nc = nc as usize; + if !visi.contains(&(nr, nc, new_k)) && new_k >= 0 { + visi.insert((nr, nc, new_k)); + q.push_back((nr, nc, new_k, d + 1)); + } + } + } + } + -1 + } +} diff --git a/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.swift b/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.swift new file mode 100644 index 00000000..a99f5cb2 --- /dev/null +++ b/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.swift @@ -0,0 +1,29 @@ +class Solution { + func shortestPath(_ grid: [[Int]], _ k: Int) -> Int { + let n = grid.count, m = grid[0].count + var q = [[0, 0, k, 0]] + var visi = Set() + visi.insert("0,0,\(k)") + let dirs = [(-1, 0), (0, 1), (1, 0), (0, -1)] + while !q.isEmpty { + let cur = q.removeFirst() + let r = cur[0] + let c = cur[1] + var kRem = cur[2] + let d = cur[3] + if r == n - 1 && c == m - 1 { return d } + if grid[r][c] == 1 { kRem -= 1 } + for (dr, dc) in dirs { + let nr = r + dr, nc = c + dc + if nr >= 0 && nr < n && nc >= 0 && nc < m { + let key = "\(nr),\(nc),\(kRem)" + if !visi.contains(key) && kRem >= 0 { + visi.insert(key) + q.append([nr, nc, kRem, d + 1]) + } + } + } + } + return -1 + } +} diff --git a/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.ts b/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.ts new file mode 100644 index 00000000..1a5590f4 --- /dev/null +++ b/tests/1001-1500/1293. shortest-path-in-a-grid-with-obstacles-elimination/sol.ts @@ -0,0 +1,30 @@ +function shortestPath(grid: number[][], k: number): number { + const n = grid.length, + m = grid[0].length; + const q: [number, number, number, number][] = [[0, 0, k, 0]]; + const visi = new Set(); + visi.add("0,0," + k); + const dirs = [ + [-1, 0], + [0, 1], + [1, 0], + [0, -1], + ]; + while (q.length > 0) { + const [r, c, kRem, d] = q.shift()!; + if (r === n - 1 && c === m - 1) return d; + let newK = grid[r][c] === 1 ? kRem - 1 : kRem; + for (const [dr, dc] of dirs) { + const nr = r + dr, + nc = c + dc; + if (nr >= 0 && nr < n && nc >= 0 && nc < m) { + const key = nr + "," + nc + "," + newK; + if (!visi.has(key) && newK >= 0) { + visi.add(key); + q.push([nr, nc, newK, d + 1]); + } + } + } + } + return -1; +} diff --git a/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/manifest.yaml b/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/manifest.yaml new file mode 100644 index 00000000..dae464b9 --- /dev/null +++ b/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/manifest.yaml @@ -0,0 +1,282 @@ +entry: + id: 1295 + title: "find-numbers-with-even-number-of-digits" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().findNumbers({nums})" + rust: "Solution::find_numbers({nums})" + python3: "Solution().findNumbers({nums})" + python2: "Solution().findNumbers({nums})" + ruby: "find_numbers({nums})" + java: "new Solution().findNumbers({nums})" + csharp: "new Solution().FindNumbers({nums})" + kotlin: "Solution().findNumbers({nums})" + go: "findNumbers({nums})" + dart: "Solution().findNumbers({nums})" + swift: "Solution().findNumbers({nums})" + typescript: "findNumbers({nums})" + +judge: + type: "exact" + +limits: + time_ms: 500 + memory_mb: 256 + +oracle: + python3: + call: "Checker().findNumbers(nums, {result})" + checker: | + class Checker: + def findNumbers(self, nums, result): + if not isinstance(nums, list) or not 1 <= len(nums) <= 500: + return False + if any(not isinstance(value, int) or isinstance(value, bool) or not 1 <= value <= 100000 for value in nums): + return False + if not isinstance(result, int) or isinstance(result, bool): + return False + expected = sum(10 <= value <= 99 or 1000 <= value <= 9999 or value == 100000 for value in nums) + return result == expected + +seed: 1295 + +tests: + - name: "example_one" + in: + nums: [12, 345, 2, 6, 7896] + out: 2 + - name: "example_two" + in: + nums: [555, 901, 482, 1771] + out: 1 + - name: "single_one_digit" + in: + nums: [7] + out: 0 + - name: "single_two_digit" + in: + nums: [10] + out: 1 + - name: "single_three_digit" + in: + nums: [999] + out: 0 + - name: "single_four_digit" + in: + nums: [1000] + out: 1 + - name: "single_five_digit" + in: + nums: [10000] + out: 0 + - name: "single_maximum" + in: + nums: [100000] + out: 1 + - name: "all_one_digit" + in: + nums: [1, 2, 3, 8, 9] + out: 0 + - name: "all_two_digit" + in: + nums: [10, 11, 42, 98] + out: 4 + - name: "all_three_digit" + in: + nums: [100, 101, 555, 999] + out: 0 + - name: "all_four_digit" + in: + nums: [1000, 1234, 9999] + out: 3 + - name: "all_five_digit" + in: + nums: [10000, 54321, 99999] + out: 0 + - name: "lower_boundaries" + in: + nums: [1, 9, 10, 99, 100] + out: 2 + - name: "upper_boundaries" + in: + nums: [999, 1000, 9999, 10000, 99999, 100000] + out: 3 + - name: "alternating_lengths" + in: + nums: [1, 10, 100, 1000, 10000] + out: 2 + - name: "repeated_even_values" + in: + nums: [12, 12, 1000, 1000, 100000] + out: 5 + - name: "repeated_odd_values" + in: + nums: [7, 7, 555, 555, 99999] + out: 0 + - name: "mixed_small" + in: + nums: [3, 14, 205, 4096, 87654] + out: 2 + - name: "mixed_large" + in: + nums: [99999, 100000, 1, 100, 10000] + out: 1 + - name: "powers_of_ten" + in: + nums: [1, 10, 100, 1000, 10000, 100000] + out: 3 + - name: "near_powers" + in: + nums: [9, 11, 99, 101, 999, 1001, 9999, 10001] + out: 4 + - name: "palindromic_values" + in: + nums: [11, 121, 1221, 12321, 99999] + out: 2 + - name: "sparse_even_count" + in: + nums: [1, 2, 3, 1000, 5, 6] + out: 1 + - name: "all_same_length_mixed" + in: + nums: [100, 250, 500, 750, 999] + out: 0 + - name: "two_element_even" + in: + nums: [10, 1000] + out: 2 + - name: "two_element_odd" + in: + nums: [1, 999] + out: 0 + - name: "boundary_pairs" + in: + nums: [98, 99, 100, 101, 998, 999, 1000, 1001] + out: 4 + - name: "exact_digit_transitions" + in: + nums: [9998, 9999, 10000, 10001, 99998, 99999, 100000] + out: 3 + - name: "mixed_extreme_repetitions" + in: + nums: [1, 10, 1, 1000, 100000, 99999, 100, 9] + out: 3 + - name: "all_transitions" + in: + nums: + [ + 8, + 9, + 10, + 11, + 98, + 99, + 100, + 101, + 998, + 999, + 1000, + 1001, + 9998, + 9999, + 10000, + 10001, + 99998, + 99999, + 100000, + ] + out: 9 + - name: "repeated_two_digit_values" + in: + nums: [10, 99, 10, 99, 10, 99] + out: 6 + - name: "highest_odd_ranges_and_maximum" + in: + nums: [100, 999, 10000, 99999, 100000] + out: 1 + - name: "descending_length_mix" + in: + nums: [12345, 1234, 123, 12, 1, 98765, 9876, 987, 98, 9] + out: 4 + - name: "stress_mixed_full_range" + seed: 101 + in: + nums: + gen: "array" + len: 500 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + - name: "stress_two_digit_only" + seed: 202 + in: + nums: + gen: "array" + len: 500 + of: + gen: "int" + min: 10 + max: 99 + distinct: false + sorted: false + elemType: "int" + - name: "stress_four_digit_only" + seed: 303 + in: + nums: + gen: "array" + len: 500 + of: + gen: "int" + min: 1000 + max: 9999 + distinct: false + sorted: false + elemType: "int" + - name: "stress_one_digit_only" + seed: 404 + in: + nums: + gen: "array" + len: 500 + of: + gen: "int" + min: 1 + max: 9 + distinct: false + sorted: false + elemType: "int" + - name: "stress_three_digit_only" + seed: 505 + in: + nums: + gen: "array" + len: 500 + of: + gen: "int" + min: 100 + max: 999 + distinct: false + sorted: false + elemType: "int" + - name: "stress_five_and_six_digit_ranges" + seed: 606 + in: + nums: + gen: "array" + len: 500 + of: + gen: "int" + min: 10000 + max: 100000 + distinct: false + sorted: false + elemType: "int" diff --git a/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.cpp b/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.cpp new file mode 100644 index 00000000..8b0134ce --- /dev/null +++ b/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int findNumbers(vector& nums) { + int count = 0; + for (int i : nums) { + int msb = 31 - __builtin_clz(i); + int digits = (int)(msb * 0.30103) + 1; + if (i >= pow(10, digits)) { + digits++; + } + if (digits % 2 == 0) { + count++; + } + } + return count; + } +}; diff --git a/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.cs b/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.cs new file mode 100644 index 00000000..357887b5 --- /dev/null +++ b/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.cs @@ -0,0 +1,11 @@ +public class Solution { + public int FindNumbers(int[] nums) { + int count = 0; + foreach (int i in nums) { + if (i.ToString().Length % 2 == 0) { + count++; + } + } + return count; + } +} diff --git a/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.dart b/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.dart new file mode 100644 index 00000000..938bcc84 --- /dev/null +++ b/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.dart @@ -0,0 +1,11 @@ +class Solution { + int findNumbers(List nums) { + int count = 0; + for (int i in nums) { + if (i.toString().length % 2 == 0) { + count++; + } + } + return count; + } +} diff --git a/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.go b/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.go new file mode 100644 index 00000000..6ede9c45 --- /dev/null +++ b/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.go @@ -0,0 +1,17 @@ +func findNumbers(nums []int) int { + count := 0 + for _, i := range nums { + msb := 0 + if i > 0 { + msb = 31 - bits.LeadingZeros32(uint32(i)) + } + digits := int(float64(msb)*0.30103) + 1 + if float64(i) >= math.Pow(10, float64(digits)) { + digits++ + } + if digits%2 == 0 { + count++ + } + } + return count +} diff --git a/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.java b/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.java new file mode 100644 index 00000000..43d9c8f0 --- /dev/null +++ b/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.java @@ -0,0 +1,16 @@ +class Solution { + public int findNumbers(int[] nums) { + int count = 0; + for (int i : nums) { + int msb = Integer.SIZE - Integer.numberOfLeadingZeros(i) - 1; + int digits = (int)(msb * 0.30103) + 1; + if (i >= Math.pow(10, digits)) { + digits++; + } + if (digits % 2 == 0) { + count++; + } + } + return count; + } +} diff --git a/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.kt b/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.kt new file mode 100644 index 00000000..3a19a468 --- /dev/null +++ b/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun findNumbers(nums: IntArray): Int { + var count = 0 + for (i in nums) { + val msb = i.countLeadingZeroBits().let { 32 - it - 1 } + var digits = (msb * 0.30103).toInt() + 1 + if (i >= Math.pow(10.0, digits.toDouble())) { + digits++ + } + if (digits % 2 == 0) { + count++ + } + } + return count + } +} diff --git a/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.py b/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.py new file mode 100644 index 00000000..bf0f28ae --- /dev/null +++ b/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.py @@ -0,0 +1,11 @@ +class Solution(object): + def findNumbers(self, nums): + count = 0 + for i in nums: + msb = i.bit_length() - 1 + digits = int(msb * 0.30103) + 1 + if i >= 10**digits: + digits += 1 + if digits % 2 == 0: + count += 1 + return count diff --git a/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.py2 b/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.py2 new file mode 100644 index 00000000..bf0f28ae --- /dev/null +++ b/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.py2 @@ -0,0 +1,11 @@ +class Solution(object): + def findNumbers(self, nums): + count = 0 + for i in nums: + msb = i.bit_length() - 1 + digits = int(msb * 0.30103) + 1 + if i >= 10**digits: + digits += 1 + if digits % 2 == 0: + count += 1 + return count diff --git a/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.rb b/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.rb new file mode 100644 index 00000000..63ac49b0 --- /dev/null +++ b/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.rb @@ -0,0 +1,16 @@ +# @param {Integer[]} nums +# @return {Integer} +def find_numbers(nums) + count = 0 + nums.each do |i| + msb = i.bit_length - 1 + digits = (msb * 0.30103).to_i + 1 + if i >= 10 ** digits + digits += 1 + end + if digits % 2 == 0 + count += 1 + end + end + count +end diff --git a/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.rs b/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.rs new file mode 100644 index 00000000..798e5d70 --- /dev/null +++ b/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn find_numbers(nums: Vec) -> i32 { + let mut count = 0; + for &i in &nums { + let msb = 31 - i.leading_zeros() as i32; + let mut digits = (msb as f64 * 0.30103) as i32 + 1; + if i as f64 >= 10_f64.powi(digits) { + digits += 1; + } + if digits % 2 == 0 { + count += 1; + } + } + count + } +} diff --git a/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.swift b/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.swift new file mode 100644 index 00000000..4f377c6e --- /dev/null +++ b/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.swift @@ -0,0 +1,16 @@ +class Solution { + func findNumbers(_ nums: [Int]) -> Int { + var count = 0 + for i in nums { + let msb = i.bitWidth - i.leadingZeroBitCount - 1 + var digits = Int(Double(msb) * 0.30103) + 1 + if Double(i) >= pow(10.0, Double(digits)) { + digits += 1 + } + if digits % 2 == 0 { + count += 1 + } + } + return count + } +} diff --git a/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.ts b/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.ts new file mode 100644 index 00000000..655c5ddb --- /dev/null +++ b/tests/1001-1500/1295. find-numbers-with-even-number-of-digits/sol.ts @@ -0,0 +1,14 @@ +function findNumbers(nums: number[]): number { + let count = 0; + for (const i of nums) { + const msb = Math.floor(Math.log2(i)); + let digits = Math.floor(msb * 0.30103) + 1; + if (i >= Math.pow(10, digits)) { + digits++; + } + if (digits % 2 === 0) { + count++; + } + } + return count; +} diff --git a/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/manifest.yaml b/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/manifest.yaml new file mode 100644 index 00000000..2deb9227 --- /dev/null +++ b/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/manifest.yaml @@ -0,0 +1,312 @@ +entry: + id: 1296 + title: divide-array-in-sets-of-k-consecutive-numbers + params: + nums: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().isPossibleDivide({nums}, {k})" + rust: "Solution::is_possible_divide({nums}, {k})" + python3: "Solution().isPossibleDivide({nums}, {k})" + python2: "Solution().isPossibleDivide({nums}, {k})" + ruby: "is_possible_divide({nums}, {k})" + java: "new Solution().isPossibleDivide({nums}, {k})" + csharp: "new Solution().IsPossibleDivide({nums}, {k})" + kotlin: "Solution().isPossibleDivide({nums}, {k})" + go: "isPossibleDivide({nums}, {k})" + dart: "Solution().isPossibleDivide({nums}, {k})" + swift: "Solution().isPossibleDivide({nums}, {k})" + typescript: "isPossibleDivide({nums}, {k})" +judge: + type: "exact" +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().isPossibleDivide(nums, k, {result})" + checker: | + class Checker: + def isPossibleDivide(self, nums, k, result): + if type(result) is not bool: + return False + if not isinstance(nums, list) or not 1 <= len(nums) <= 100000: + return False + if not isinstance(k, int) or isinstance(k, bool) or not 1 <= k <= len(nums): + return False + if any(not isinstance(value, int) or isinstance(value, bool) or not 1 <= value <= 1000000000 for value in nums): + return False + if len(nums) % k != 0: + return result is False + counts = {} + for value in nums: + counts[value] = counts.get(value, 0) + 1 + for start in sorted(counts): + needed = counts[start] + if needed == 0: + continue + for value in range(start, start + k): + if counts.get(value, 0) < needed: + return result is False + counts[value] -= needed + return result is True +seed: 1296 +tests: + - name: example_one_overlapping_groups + in: + nums: [1, 2, 3, 3, 4, 4, 5, 6] + k: 4 + out: true + - name: example_two_multiple_starts + in: + nums: [3, 2, 1, 2, 3, 4, 3, 4, 5, 9, 10, 11] + k: 3 + out: true + - name: example_three_nondivisible_length + in: + nums: [1, 2, 3, 4] + k: 3 + out: false + - name: single_value_k_one + in: + nums: [1] + k: 1 + out: true + - name: mixed_values_k_one + in: + nums: [1000000000, 1, 17, 17, 500000000] + k: 1 + out: true + - name: adjacent_pair + in: + nums: [1, 2] + k: 2 + out: true + - name: gapped_pair + in: + nums: [1, 3] + k: 2 + out: false + - name: full_array_one_group + in: + nums: [5, 2, 4, 1, 3] + k: 5 + out: true + - name: full_array_missing_middle + in: + nums: [1, 2, 4, 5] + k: 4 + out: false + - name: equal_duplicate_layers + in: + nums: [1, 1, 2, 2, 3, 3] + k: 3 + out: true + - name: excess_lowest_value + in: + nums: [1, 1, 1, 2, 2, 3] + k: 3 + out: false + - name: excess_highest_value + in: + nums: [1, 2, 2, 3, 3, 3] + k: 3 + out: false + - name: all_equal_divisible_but_not_consecutive + in: + nums: [7, 7, 7, 7] + k: 2 + out: false + - name: two_disjoint_runs + in: + nums: [10, 11, 12, 1, 2, 3] + k: 3 + out: true + - name: disjoint_run_with_gap + in: + nums: [1, 2, 4, 10, 11, 12] + k: 3 + out: false + - name: descending_input + in: + nums: [9, 8, 7, 6, 5, 4, 3, 2, 1] + k: 3 + out: true + - name: shuffled_duplicate_starts + in: + nums: [4, 2, 3, 1, 3, 2, 4, 1] + k: 4 + out: true + - name: overlapping_three_chains + in: + nums: [1, 2, 2, 3, 3, 3, 4, 4, 5] + k: 3 + out: true + - name: overlapping_chain_shortage + in: + nums: [1, 2, 2, 3, 3, 4] + k: 3 + out: true + - name: staggered_four_chains + in: + nums: [1, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 6] + k: 4 + out: true + - name: staggered_four_chains_shortage + in: + nums: [1, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6, 6] + k: 4 + out: false + - name: length_divisible_but_terminal_gap + in: + nums: [1, 2, 3, 5, 6, 7] + k: 3 + out: true + - name: terminal_gap_breaks_group + in: + nums: [1, 2, 3, 5, 6, 8] + k: 3 + out: false + - name: consecutive_ten_split_by_two + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + k: 2 + out: true + - name: consecutive_ten_split_by_five + in: + nums: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + k: 5 + out: true + - name: two_gapped_length_five_groups + in: + nums: [1, 2, 3, 4, 5, 7, 8, 9, 10, 11] + k: 5 + out: true + - name: repeated_four_value_runs + in: + nums: [1, 1, 2, 2, 3, 3, 4, 4] + k: 4 + out: true + - name: repeated_four_value_runs_unbalanced + in: + nums: [1, 1, 2, 2, 3, 4, 4, 5] + k: 4 + out: false + - name: starts_after_existing_run + in: + nums: [1, 2, 3, 3, 4, 5, 6, 7, 8] + k: 3 + out: true + - name: starts_after_existing_run_missing_tail + in: + nums: [1, 2, 3, 3, 4, 5, 6, 7, 9] + k: 3 + out: false + - name: near_upper_bound_single_group + in: + nums: [999999997, 999999998, 999999999, 1000000000] + k: 4 + out: true + - name: near_upper_bound_gap + in: + nums: [999999997, 999999998, 1000000000, 1000000000] + k: 4 + out: false + - name: widely_separated_high_value_groups + in: + nums: [1000000000, 999999999, 999999998, 100, 101, 102] + k: 3 + out: true + - name: many_parallel_pairs + in: + nums: [2, 1, 2, 1, 2, 1, 4, 3, 4, 3, 4, 3] + k: 2 + out: true + - name: generated_max_length_k_one + seed: 129601 + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + sorted: false + elemType: "int" + k: 1 + - name: generated_max_length_pairs + seed: 129602 + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + sorted: false + elemType: "int" + k: 2 + - name: generated_max_length_small_groups + seed: 129603 + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + sorted: false + elemType: "int" + k: 4 + - name: generated_max_length_moderate_groups + seed: 129604 + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + sorted: false + elemType: "int" + k: 100 + - name: generated_max_length_half_groups + seed: 129605 + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + sorted: false + elemType: "int" + k: 50000 + - name: generated_max_length_single_group + seed: 129606 + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + sorted: false + elemType: "int" + k: 100000 diff --git a/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.cpp b/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.cpp new file mode 100644 index 00000000..f401cd7a --- /dev/null +++ b/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + bool isPossibleDivide(vector& nums, int k) { + if (nums.size() % k != 0) return false; + map count; + for (int num : nums) { + count[num]++; + } + sort(nums.begin(), nums.end()); + for (int num : nums) { + if (count[num] == 0) continue; + for (int i = 0; i < k; i++) { + int cur = num + i; + if (count[cur] == 0) return false; + count[cur]--; + } + } + return true; + } +}; diff --git a/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.cs b/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.cs new file mode 100644 index 00000000..84bf1acf --- /dev/null +++ b/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.cs @@ -0,0 +1,20 @@ +public class Solution { + public bool IsPossibleDivide(int[] nums, int k) { + if (nums.Length % k != 0) return false; + var count = new Dictionary(); + foreach (int num in nums) { + if (count.ContainsKey(num)) count[num]++; + else count[num] = 1; + } + Array.Sort(nums); + foreach (int num in nums) { + if (count[num] == 0) continue; + for (int i = 0; i < k; i++) { + int cur = num + i; + if (!count.ContainsKey(cur) || count[cur] == 0) return false; + count[cur]--; + } + } + return true; + } +} diff --git a/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.dart b/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.dart new file mode 100644 index 00000000..9ffae5fb --- /dev/null +++ b/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.dart @@ -0,0 +1,19 @@ +class Solution { + bool isPossibleDivide(List nums, int k) { + if (nums.length % k != 0) return false; + final count = {}; + for (final num in nums) { + count[num] = (count[num] ?? 0) + 1; + } + nums.sort(); + for (final num in nums) { + if (count[num] == 0) continue; + for (int i = 0; i < k; i++) { + final cur = num + i; + if ((count[cur] ?? 0) == 0) return false; + count[cur] = count[cur]! - 1; + } + } + return true; + } +} diff --git a/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.go b/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.go new file mode 100644 index 00000000..abddfbb3 --- /dev/null +++ b/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.go @@ -0,0 +1,23 @@ +func isPossibleDivide(nums []int, k int) bool { + if len(nums)%k != 0 { + return false + } + count := make(map[int]int) + for _, num := range nums { + count[num]++ + } + sort.Ints(nums) + for _, num := range nums { + if count[num] == 0 { + continue + } + for i := 0; i < k; i++ { + cur := num + i + if count[cur] == 0 { + return false + } + count[cur]-- + } + } + return true +} diff --git a/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.java b/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.java new file mode 100644 index 00000000..e1a997dc --- /dev/null +++ b/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.java @@ -0,0 +1,19 @@ +class Solution { + public boolean isPossibleDivide(int[] nums, int k) { + if (nums.length % k != 0) return false; + java.util.Map count = new java.util.HashMap<>(); + for (int num : nums) { + count.put(num, count.getOrDefault(num, 0) + 1); + } + java.util.Arrays.sort(nums); + for (int num : nums) { + if (count.get(num) == 0) continue; + for (int i = 0; i < k; i++) { + int cur = num + i; + if (count.getOrDefault(cur, 0) == 0) return false; + count.put(cur, count.get(cur) - 1); + } + } + return true; + } +} diff --git a/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.kt b/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.kt new file mode 100644 index 00000000..f575b179 --- /dev/null +++ b/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.kt @@ -0,0 +1,19 @@ +class Solution { + fun isPossibleDivide(nums: IntArray, k: Int): Boolean { + if (nums.size % k != 0) return false + val count = mutableMapOf() + for (num in nums) { + count[num] = count.getOrDefault(num, 0) + 1 + } + nums.sort() + for (num in nums) { + if (count[num] == 0) continue + for (i in 0 until k) { + val cur = num + i + if (count.getOrDefault(cur, 0) == 0) return false + count[cur] = count[cur]!! - 1 + } + } + return true + } +} diff --git a/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.py b/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.py new file mode 100644 index 00000000..8434bfce --- /dev/null +++ b/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.py @@ -0,0 +1,18 @@ +from collections import Counter +from typing import List + + +class Solution: + def isPossibleDivide(self, nums: List[int], k: int) -> bool: + if len(nums) % k != 0: + return False + count = Counter(nums) + nums.sort() + for num in nums: + if count[num] == 0: + continue + for i in range(k): + if count[num + i] == 0: + return False + count[num + i] -= 1 + return True diff --git a/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.py2 b/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.py2 new file mode 100644 index 00000000..b87e98d9 --- /dev/null +++ b/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.py2 @@ -0,0 +1,20 @@ +class Solution(object): + def isPossibleDivide(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: bool + """ + if len(nums) % k != 0: + return False + from collections import Counter + count = Counter(nums) + nums.sort() + for num in nums: + if count[num] == 0: + continue + for i in range(k): + if count[num + i] == 0: + return False + count[num + i] -= 1 + return True diff --git a/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.rb b/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.rb new file mode 100644 index 00000000..a0b5521e --- /dev/null +++ b/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.rb @@ -0,0 +1,17 @@ +# @param {Integer[]} nums +# @param {Integer} k +# @return {Boolean} +def is_possible_divide(nums, k) + return false if nums.length % k != 0 + count = Hash.new(0) + nums.each { |num| count[num] += 1 } + nums.sort! + nums.each do |num| + next if count[num] == 0 + (0...k).each do |i| + return false if count[num + i] == 0 + count[num + i] -= 1 + end + end + true +end diff --git a/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.rs b/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.rs new file mode 100644 index 00000000..b524684e --- /dev/null +++ b/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.rs @@ -0,0 +1,26 @@ +impl Solution { + pub fn is_possible_divide(nums: Vec, k: i32) -> bool { + if nums.len() % k as usize != 0 { + return false; + } + let mut count = std::collections::HashMap::new(); + for &num in &nums { + *count.entry(num).or_insert(0) += 1; + } + let mut nums = nums; + nums.sort(); + for &num in &nums { + if count.get(&num) == Some(&0) { + continue; + } + for i in 0..k { + let cur = num + i; + if count.get(&cur).unwrap_or(&0) == &0 { + return false; + } + *count.get_mut(&cur).unwrap() -= 1; + } + } + true + } +} diff --git a/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.swift b/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.swift new file mode 100644 index 00000000..d5aa2407 --- /dev/null +++ b/tests/1001-1500/1296. divide-array-in-sets-of-k-consecutive-numbers/sol.swift @@ -0,0 +1,19 @@ +class Solution { + func isPossibleDivide(_ nums: [Int], _ k: Int) -> Bool { + if nums.count % k != 0 { return false } + var count = [Int: Int]() + for num in nums { + count[num, default: 0] += 1 + } + let sortedNums = nums.sorted() + for num in sortedNums { + if count[num] == 0 { continue } + for i in 0..(); + for (const num of nums) { + count.set(num, (count.get(num) || 0) + 1); + } + nums.sort((a, b) => a - b); + for (const num of nums) { + if (count.get(num) === 0) continue; + for (let i = 0; i < k; i++) { + const cur = num + i; + if ((count.get(cur) || 0) === 0) return false; + count.set(cur, count.get(cur)! - 1); + } + } + return true; +} diff --git a/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/manifest.yaml b/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/manifest.yaml new file mode 100644 index 00000000..44a878d4 --- /dev/null +++ b/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/manifest.yaml @@ -0,0 +1,355 @@ +entry: + id: 1297 + title: maximum-number-of-occurrences-of-a-substring + params: + s: + type: string + maxLetters: + type: int + minSize: + type: int + maxSize: + type: int + call: + cpp: "Solution().maxFreq({s}, {maxLetters}, {minSize}, {maxSize})" + rust: "Solution::max_freq({s}, {maxLetters}, {minSize}, {maxSize})" + python3: "Solution().maxFreq({s}, {maxLetters}, {minSize}, {maxSize})" + python2: "Solution().maxFreq({s}, {maxLetters}, {minSize}, {maxSize})" + ruby: "max_freq({s}, {maxLetters}, {minSize}, {maxSize})" + java: "new Solution().maxFreq({s}, {maxLetters}, {minSize}, {maxSize})" + csharp: "new Solution().MaxFreq({s}, {maxLetters}, {minSize}, {maxSize})" + kotlin: "Solution().maxFreq({s}, {maxLetters}, {minSize}, {maxSize})" + go: "maxFreq({s}, {maxLetters}, {minSize}, {maxSize})" + dart: "Solution().maxFreq({s}, {maxLetters}, {minSize}, {maxSize})" + swift: "Solution().maxFreq({s}, {maxLetters}, {minSize}, {maxSize})" + typescript: "maxFreq({s}, {maxLetters}, {minSize}, {maxSize})" + +judge: + type: "exact" + +limits: + time_ms: 1500 + memory_mb: 256 + +oracle: + python3: + call: "Checker().maxFreq(s, maxLetters, minSize, maxSize, {result})" + checker: | + class Checker: + def maxFreq(self, s, maxLetters, minSize, maxSize, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if not (1 <= len(s) <= 100000 and 1 <= maxLetters <= 26): + return False + if not (1 <= minSize <= maxSize <= min(26, len(s))): + return False + if any(char < 'a' or char > 'z' for char in s): + return False + counts = {} + for start in range(len(s) - minSize + 1): + piece = s[start:start + minSize] + if len(set(piece)) <= maxLetters: + counts[piece] = counts.get(piece, 0) + 1 + return result == max(counts.values(), default=0) + +seed: 1297 + +tests: + - name: example_one + in: + s: aababcaab + maxLetters: 2 + minSize: 3 + maxSize: 4 + out: 2 + - name: example_two + in: + s: aaaa + maxLetters: 1 + minSize: 3 + maxSize: 3 + out: 2 + - name: single_character + in: + s: z + maxLetters: 1 + minSize: 1 + maxSize: 1 + out: 1 + - name: uniform_run + in: + s: aaaaaaaa + maxLetters: 1 + minSize: 3 + maxSize: 8 + out: 6 + - name: pair_filter_rejects_all + in: + s: abcdef + maxLetters: 1 + minSize: 2 + maxSize: 4 + out: 0 + - name: triple_filter_rejects_all + in: + s: abcdef + maxLetters: 1 + minSize: 3 + maxSize: 3 + out: 0 + - name: alternating_pair + in: + s: abababab + maxLetters: 2 + minSize: 2 + maxSize: 5 + out: 4 + - name: periodic_triple + in: + s: abcabcabc + maxLetters: 3 + minSize: 3 + maxSize: 6 + out: 3 + - name: overlapping_uniform_windows + in: + s: aaaaaab + maxLetters: 1 + minSize: 2 + maxSize: 3 + out: 5 + - name: separated_uniform_pairs + in: + s: aabbaaacaa + maxLetters: 1 + minSize: 2 + maxSize: 4 + out: 4 + - name: all_distinct_but_allowed + in: + s: abcdefgh + maxLetters: 8 + minSize: 2 + maxSize: 8 + out: 1 + - name: single_size_character_frequency + in: + s: zyxxyzz + maxLetters: 1 + minSize: 1 + maxSize: 5 + out: 3 + - name: repeated_four_character_windows + in: + s: abacabadabacaba + maxLetters: 3 + minSize: 4 + maxSize: 4 + out: 2 + - name: repeated_aab + in: + s: aabcaabdaabca + maxLetters: 3 + minSize: 3 + maxSize: 7 + out: 3 + - name: three_cycle_under_two_letter_bound + in: + s: abcabcabcabc + maxLetters: 2 + minSize: 2 + maxSize: 5 + out: 4 + - name: repeated_unique_pairs + in: + s: qwertyqwerty + maxLetters: 2 + minSize: 2 + maxSize: 6 + out: 2 + - name: repeated_xyz + in: + s: xyzxyzxyza + maxLetters: 3 + minSize: 3 + maxSize: 5 + out: 3 + - name: suffix_uniform_run + in: + s: abczzzzzz + maxLetters: 1 + minSize: 2 + maxSize: 6 + out: 5 + - name: repeated_abcd + in: + s: abcdabceabcd + maxLetters: 4 + minSize: 4 + maxSize: 8 + out: 2 + - name: constrained_two_letter_windows + in: + s: aabacabaabbac + maxLetters: 2 + minSize: 3 + maxSize: 5 + out: 2 + - name: repeated_six_character_pattern + in: + s: abcdefabcdefabcdef + maxLetters: 6 + minSize: 6 + maxSize: 10 + out: 3 + - name: leading_uniform_run + in: + s: aaaaaabcde + maxLetters: 1 + minSize: 4 + maxSize: 6 + out: 3 + - name: whole_string_window + in: + s: abcde + maxLetters: 5 + minSize: 5 + maxSize: 5 + out: 1 + - name: min_size_one + in: + s: ababababa + maxLetters: 2 + minSize: 1 + maxSize: 2 + out: 5 + - name: repeating_four_window + in: + s: aabacaaabacaa + maxLetters: 3 + minSize: 4 + maxSize: 9 + out: 2 + - name: long_three_cycle + in: + s: abcabcabcabcabcabcabcabc + maxLetters: 3 + minSize: 3 + maxSize: 12 + out: 8 + - name: strict_two_letter_filter + in: + s: abcadeabcab + maxLetters: 2 + minSize: 3 + maxSize: 6 + out: 0 + - name: largest_uniform_block_wins + in: + s: aaaaaabaaaaac + maxLetters: 1 + minSize: 3 + maxSize: 7 + out: 7 + - name: repeated_five_letter_prefix + in: + s: abcdefabcdeffedcba + maxLetters: 5 + minSize: 5 + maxSize: 10 + out: 2 + - name: three_separated_abcd_windows + in: + s: abcdxabcdyabcd + maxLetters: 4 + minSize: 4 + maxSize: 8 + out: 3 + - name: alphabet_boundary_window + in: + s: abcdefghijklmnopqrstuvwxyz + maxLetters: 26 + minSize: 26 + maxSize: 26 + out: 1 + - name: banana_overlaps + in: + s: banana + maxLetters: 2 + minSize: 3 + maxSize: 3 + out: 2 + - name: repeating_four_characters + in: + s: zzxyzzxyzz + maxLetters: 3 + minSize: 4 + maxSize: 6 + out: 2 + - name: internal_uniform_run + in: + s: abbbbbba + maxLetters: 1 + minSize: 5 + maxSize: 7 + out: 2 + - name: generated_binary_20000 + seed: 201 + in: + s: + gen: "str" + len: 20000 + alphabet: ab + maxLetters: 1 + minSize: 10 + maxSize: 26 + - name: generated_ternary_35000 + seed: 202 + in: + s: + gen: "str" + len: 35000 + alphabet: abc + maxLetters: 3 + minSize: 26 + maxSize: 26 + - name: generated_full_alphabet_50000 + seed: 203 + in: + s: + gen: "str" + len: 50000 + alphabet: abcdefghijklmnopqrstuvwxyz + maxLetters: 26 + minSize: 26 + maxSize: 26 + - name: generated_four_letter_75000 + seed: 204 + in: + s: + gen: "str" + len: 75000 + alphabet: abcd + maxLetters: 2 + minSize: 20 + maxSize: 26 + - name: generated_ten_letter_filter_99999 + seed: 205 + in: + s: + gen: "str" + len: 99999 + alphabet: abcdefghijklmnopqrstuvwxyz + maxLetters: 10 + minSize: 5 + maxSize: 26 + - name: generated_binary_maximum_100000 + seed: 206 + in: + s: + gen: "str" + len: 100000 + alphabet: ab + maxLetters: 2 + minSize: 26 + maxSize: 26 diff --git a/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.cpp b/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.cpp new file mode 100644 index 00000000..8e07a470 --- /dev/null +++ b/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int maxFreq(string s, int maxLetters, int minSize, int maxSize) { + unordered_map count; + unordered_map unique; + int left = 0; + int res = 0; + for (int right = 0; right < s.size(); right++) { + unique[s[right]]++; + + while (unique.size() > maxLetters || right - left + 1 > minSize) { + unique[s[left]]--; + if (unique[s[left]] == 0) { + unique.erase(s[left]); + } + left++; + } + + if (right - left + 1 == minSize && unique.size() <= maxLetters) { + string curr = s.substr(left, right - left + 1); + int val = ++count[curr]; + res = max(res, val); + } + } + return res; + } +}; diff --git a/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.cs b/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.cs new file mode 100644 index 00000000..bb140488 --- /dev/null +++ b/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.cs @@ -0,0 +1,30 @@ +public class Solution { + public int MaxFreq(string s, int maxLetters, int minSize, int maxSize) { + var count = new Dictionary(); + var unique = new Dictionary(); + int left = 0; + int res = 0; + for (int right = 0; right < s.Length; right++) { + char rc = s[right]; + if (unique.ContainsKey(rc)) unique[rc]++; + else unique[rc] = 1; + + while (unique.Count > maxLetters || right - left + 1 > minSize) { + char lc = s[left]; + unique[lc]--; + if (unique[lc] == 0) { + unique.Remove(lc); + } + left++; + } + + if (right - left + 1 == minSize && unique.Count <= maxLetters) { + string curr = s.Substring(left, right - left + 1); + if (count.ContainsKey(curr)) count[curr]++; + else count[curr] = 1; + res = Math.Max(res, count[curr]); + } + } + return res; + } +} diff --git a/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.dart b/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.dart new file mode 100644 index 00000000..2e7b072e --- /dev/null +++ b/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.dart @@ -0,0 +1,28 @@ +class Solution { + int maxFreq(String s, int maxLetters, int minSize, int maxSize) { + Map count = {}; + Map unique = {}; + int left = 0; + int res = 0; + for (int right = 0; right < s.length; right++) { + String rc = s[right]; + unique[rc] = (unique[rc] ?? 0) + 1; + + while (unique.length > maxLetters || right - left + 1 > minSize) { + String lc = s[left]; + unique[lc] = unique[lc]! - 1; + if (unique[lc] == 0) { + unique.remove(lc); + } + left++; + } + + if (right - left + 1 == minSize && unique.length <= maxLetters) { + String curr = s.substring(left, right + 1); + count[curr] = (count[curr] ?? 0) + 1; + res = res > count[curr]! ? res : count[curr]!; + } + } + return res; + } +} diff --git a/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.go b/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.go new file mode 100644 index 00000000..5afedbbf --- /dev/null +++ b/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.go @@ -0,0 +1,26 @@ +func maxFreq(s string, maxLetters int, minSize int, maxSize int) int { + count := make(map[string]int) + unique := make(map[byte]int) + left := 0 + res := 0 + for right := 0; right < len(s); right++ { + unique[s[right]]++ + + for len(unique) > maxLetters || right-left+1 > minSize { + unique[s[left]]-- + if unique[s[left]] == 0 { + delete(unique, s[left]) + } + left++ + } + + if right-left+1 == minSize && len(unique) <= maxLetters { + curr := s[left : right+1] + count[curr]++ + if count[curr] > res { + res = count[curr] + } + } + } + return res +} diff --git a/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.java b/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.java new file mode 100644 index 00000000..b9c19ed6 --- /dev/null +++ b/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.java @@ -0,0 +1,29 @@ +class Solution { + public int maxFreq(String s, int maxLetters, int minSize, int maxSize) { + Map count = new HashMap<>(); + Map unique = new HashMap<>(); + int left = 0; + int res = 0; + for (int right = 0; right < s.length(); right++) { + char rc = s.charAt(right); + unique.put(rc, unique.getOrDefault(rc, 0) + 1); + + while (unique.size() > maxLetters || right - left + 1 > minSize) { + char lc = s.charAt(left); + unique.put(lc, unique.get(lc) - 1); + if (unique.get(lc) == 0) { + unique.remove(lc); + } + left++; + } + + if (right - left + 1 == minSize && unique.size() <= maxLetters) { + String curr = s.substring(left, right + 1); + int val = count.getOrDefault(curr, 0) + 1; + count.put(curr, val); + res = Math.max(res, val); + } + } + return res; + } +} diff --git a/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.kt b/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.kt new file mode 100644 index 00000000..f8ee0b88 --- /dev/null +++ b/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.kt @@ -0,0 +1,29 @@ +class Solution { + fun maxFreq(s: String, maxLetters: Int, minSize: Int, maxSize: Int): Int { + val count = mutableMapOf() + val unique = mutableMapOf() + var left = 0 + var res = 0 + for (right in s.indices) { + val rc = s[right] + unique[rc] = unique.getOrDefault(rc, 0) + 1 + + while (unique.size > maxLetters || right - left + 1 > minSize) { + val lc = s[left] + unique[lc] = unique[lc]!! - 1 + if (unique[lc] == 0) { + unique.remove(lc) + } + left++ + } + + if (right - left + 1 == minSize && unique.size <= maxLetters) { + val curr = s.substring(left, right + 1) + val value = count.getOrDefault(curr, 0) + 1 + count[curr] = value + res = maxOf(res, value) + } + } + return res + } +} diff --git a/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.py b/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.py new file mode 100644 index 00000000..44025e05 --- /dev/null +++ b/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.py @@ -0,0 +1,22 @@ +class Solution: + def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int: + count = {} + left = 0 + res = 0 + unique = {} + for right in range(len(s)): + unique[s[right]] = unique.get(s[right], 0) + 1 + + while len(unique) > maxLetters or right - left + 1 > minSize: + unique[s[left]] -= 1 + if unique[s[left]] == 0: + del unique[s[left]] + left += 1 + + curr = s[left : right + 1] + if right - left + 1 == minSize and len(unique) <= maxLetters: + count[curr] = count.get(curr, 0) + 1 + + res = max(res, count[curr]) + + return res diff --git a/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.py2 b/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.py2 new file mode 100644 index 00000000..5765092c --- /dev/null +++ b/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.py2 @@ -0,0 +1,28 @@ +class Solution(object): + def maxFreq(self, s, maxLetters, minSize, maxSize): + """ + :type s: str + :type maxLetters: int + :type minSize: int + :type maxSize: int + :rtype: int + """ + count = {} + left = 0 + res = 0 + unique = {} + for right in range(len(s)): + unique[s[right]] = unique.get(s[right], 0) + 1 + + while len(unique) > maxLetters or right - left + 1 > minSize: + unique[s[left]] -= 1 + if unique[s[left]] == 0: + del unique[s[left]] + left += 1 + + if right - left + 1 == minSize and len(unique) <= maxLetters: + curr = s[left:right + 1] + count[curr] = count.get(curr, 0) + 1 + res = max(res, count[curr]) + + return res diff --git a/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.rb b/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.rb new file mode 100644 index 00000000..9bccc803 --- /dev/null +++ b/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.rb @@ -0,0 +1,27 @@ +# @param {String} s +# @param {Integer} max_letters +# @param {Integer} min_size +# @param {Integer} max_size +# @return {Integer} +def max_freq(s, max_letters, min_size, max_size) + count = Hash.new(0) + left = 0 + res = 0 + unique = Hash.new(0) + (0...s.length).each do |right| + unique[s[right]] += 1 + + while unique.size > max_letters || right - left + 1 > min_size + unique[s[left]] -= 1 + unique.delete(s[left]) if unique[s[left]] == 0 + left += 1 + end + + if right - left + 1 == min_size && unique.size <= max_letters + curr = s[left..right] + count[curr] += 1 + res = [res, count[curr]].max + end + end + res +end diff --git a/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.rs b/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.rs new file mode 100644 index 00000000..e76aa0fa --- /dev/null +++ b/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.rs @@ -0,0 +1,34 @@ +impl Solution { + pub fn max_freq(s: String, max_letters: i32, min_size: i32, max_size: i32) -> i32 { + use std::collections::HashMap; + let mut count: HashMap = HashMap::new(); + let mut unique: HashMap = HashMap::new(); + let mut left = 0; + let mut res = 0; + let chars: Vec = s.chars().collect(); + let min_size = min_size as usize; + let max_letters = max_letters as usize; + for right in 0..chars.len() { + *unique.entry(chars[right]).or_insert(0) += 1; + + while unique.len() > max_letters || right - left + 1 > min_size { + let lc = chars[left]; + if let Some(cnt) = unique.get_mut(&lc) { + *cnt -= 1; + if *cnt == 0 { + unique.remove(&lc); + } + } + left += 1; + } + + if right - left + 1 == min_size && unique.len() <= max_letters { + let curr: String = chars[left..=right].iter().collect(); + let val = count.entry(curr).or_insert(0); + *val += 1; + res = res.max(*val); + } + } + res + } +} diff --git a/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.swift b/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.swift new file mode 100644 index 00000000..4cfff43c --- /dev/null +++ b/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.swift @@ -0,0 +1,29 @@ +class Solution { + func maxFreq(_ s: String, _ maxLetters: Int, _ minSize: Int, _ maxSize: Int) -> Int { + var count = [String: Int]() + var unique = [Character: Int]() + var left = 0 + var res = 0 + let chars = Array(s) + for right in 0.. maxLetters || right - left + 1 > minSize { + let lc = chars[left] + unique[lc, default: 0] -= 1 + if unique[lc] == 0 { + unique.removeValue(forKey: lc) + } + left += 1 + } + + if right - left + 1 == minSize && unique.count <= maxLetters { + let curr = String(chars[left...right]) + count[curr, default: 0] += 1 + res = max(res, count[curr]!) + } + } + return res + } +} diff --git a/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.ts b/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.ts new file mode 100644 index 00000000..ab506d66 --- /dev/null +++ b/tests/1001-1500/1297. maximum-number-of-occurrences-of-a-substring/sol.ts @@ -0,0 +1,32 @@ +function maxFreq( + s: string, + maxLetters: number, + minSize: number, + maxSize: number, +): number { + const count: Map = new Map(); + const unique: Map = new Map(); + let left = 0; + let res = 0; + for (let right = 0; right < s.length; right++) { + const rc = s[right]; + unique.set(rc, (unique.get(rc) ?? 0) + 1); + + while (unique.size > maxLetters || right - left + 1 > minSize) { + const lc = s[left]; + unique.set(lc, unique.get(lc)! - 1); + if (unique.get(lc) === 0) { + unique.delete(lc); + } + left++; + } + + if (right - left + 1 === minSize && unique.size <= maxLetters) { + const curr = s.substring(left, right + 1); + const val = (count.get(curr) ?? 0) + 1; + count.set(curr, val); + res = Math.max(res, val); + } + } + return res; +} diff --git a/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/manifest.yaml b/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/manifest.yaml new file mode 100644 index 00000000..a8aaa685 --- /dev/null +++ b/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/manifest.yaml @@ -0,0 +1,1013 @@ +entry: + id: 1298 + title: "maximum-candies-you-can-get-from-boxes" + params: + status: + type: array + items: + type: int + candies: + type: array + items: + type: int + keys: + type: array + items: + type: array + items: + type: int + containedBoxes: + type: array + items: + type: array + items: + type: int + initialBoxes: + type: array + items: + type: int + call: + cpp: "Solution().maxCandies({status}, {candies}, {keys}, {containedBoxes}, {initialBoxes})" + rust: "Solution::max_candies({status}, {candies}, {keys}, {containedBoxes}, {initialBoxes})" + python3: "Solution().maxCandies({status}, {candies}, {keys}, {containedBoxes}, {initialBoxes})" + python2: "Solution().maxCandies({status}, {candies}, {keys}, {containedBoxes}, {initialBoxes})" + ruby: "max_candies({status}, {candies}, {keys}, {containedBoxes}, {initialBoxes})" + java: "new Solution().maxCandies({status}, {candies}, {keys}, {containedBoxes}, {initialBoxes})" + csharp: "new Solution().MaxCandies({status}, {candies}, {keys}, {containedBoxes}, {initialBoxes})" + kotlin: "Solution().maxCandies({status}, {candies}, {keys}, {containedBoxes}, {initialBoxes})" + go: "maxCandies({status}, {candies}, {keys}, {containedBoxes}, {initialBoxes})" + dart: "Solution().maxCandies({status}, {candies}, {keys}, {containedBoxes}, {initialBoxes})" + swift: "Solution().maxCandies({status}, {candies}, {keys}, {containedBoxes}, {initialBoxes})" + typescript: "maxCandies({status}, {candies}, {keys}, {containedBoxes}, {initialBoxes})" +judge: + type: exact +limits: + time_ms: 500 + memory_mb: 300 +oracle: + python3: + call: "Checker().maxCandies(status, candies, keys, containedBoxes, initialBoxes, {result})" + checker: | + from collections import deque + class Checker: + def maxCandies(self, status, candies, keys, containedBoxes, initialBoxes, result): + owned = set(initialBoxes) + open_boxes = set(i for i, value in enumerate(status) if value) + opened = set() + queue = deque(initialBoxes) + total = 0 + while queue: + box = queue.popleft() + if box in opened or box not in open_boxes: + continue + opened.add(box) + total += candies[box] + for key in keys[box]: + open_boxes.add(key) + if key in owned: + queue.append(key) + for child in containedBoxes[box]: + owned.add(child) + if child in open_boxes: + queue.append(child) + return result == total +seed: 1298 +tests: + - name: official_one + in: + status: [1, 0, 1, 0] + candies: [7, 5, 4, 100] + keys: + - [] + - [] + - [1] + - [] + containedBoxes: + - [1, 2] + - [3] + - [] + - [] + initialBoxes: [0] + out: 16 + - name: official_two + in: + status: [1, 0, 0, 0, 0, 0] + candies: [1, 1, 1, 1, 1, 1] + keys: + - [1, 2, 3, 4, 5] + - [] + - [] + - [] + - [] + - [] + containedBoxes: + - [1, 2, 3, 4, 5] + - [] + - [] + - [] + - [] + - [] + initialBoxes: [0] + out: 6 + - name: one_open + in: + status: [1] + candies: [9] + keys: [[]] + containedBoxes: [[]] + initialBoxes: [0] + out: 9 + - name: one_closed + in: + status: [0] + candies: [9] + keys: [[]] + containedBoxes: [[]] + initialBoxes: [0] + out: 0 + - name: key_unlocks + in: + status: [1, 0] + candies: [3, 8] + keys: [[1], []] + containedBoxes: [[1], []] + initialBoxes: [0] + out: 11 + - name: key_without_box + in: + status: [1, 0] + candies: [3, 8] + keys: [[1], []] + containedBoxes: [[], []] + initialBoxes: [0] + out: 3 + - name: closed_chain + in: + status: [1, 0, 0] + candies: [1, 2, 4] + keys: [[1], [2], []] + containedBoxes: [[1], [2], []] + initialBoxes: [0] + out: 7 + - name: contained_closed + in: + status: [1, 0, 1] + candies: [5, 6, 7] + keys: [[], [2], []] + containedBoxes: [[1], [], []] + initialBoxes: [0] + out: 5 + - name: initial_multiple + in: + status: [1, 1, 0] + candies: [2, 3, 9] + keys: [[], [2], []] + containedBoxes: [[], [2], []] + initialBoxes: [0, 1] + out: 14 + - name: all_open + in: + status: [1, 1, 1] + candies: [4, 5, 6] + keys: [[], [], []] + containedBoxes: [[1], [2], []] + initialBoxes: [0] + out: 15 + - name: disconnected + in: + status: [1, 1, 1] + candies: [4, 5, 6] + keys: [[], [], []] + containedBoxes: [[], [], []] + initialBoxes: [1] + out: 5 + - name: unlock_late + in: + status: [0, 1, 0] + candies: [10, 2, 30] + keys: [[], [0], [2]] + containedBoxes: [[2], [], []] + initialBoxes: [1] + out: 2 + - name: nested_keys + in: + status: [1, 0, 0, 0] + candies: [1, 2, 3, 4] + keys: [[2], [3], [1], []] + containedBoxes: [[1], [2], [3], []] + initialBoxes: [0] + out: 1 + - name: no_initial + in: + status: [1, 1] + candies: [7, 8] + keys: [[], []] + containedBoxes: [[], []] + initialBoxes: [] + out: 0 + - name: six_boxes + in: + status: [1, 0, 1, 0, 0, 1] + candies: [1, 2, 3, 4, 5, 6] + keys: [[1], [], [3], [4], [5], []] + containedBoxes: [[1], [], [3], [], [], []] + initialBoxes: [0, 2] + out: 10 + - name: case22 + in: + status: [1, 0, 0, 0, 0] + candies: [5, 4, 3, 2, 1] + keys: [[1, 2], [], [3], [4], []] + containedBoxes: [[1, 2], [], [3], [4], []] + initialBoxes: [0] + out: 15 + - name: case23 + in: + status: [0, 0, 0] + candies: [1, 2, 3] + keys: [[], [], []] + containedBoxes: [[], [], []] + initialBoxes: [0, 1] + out: 0 + - name: case24 + in: + status: [1, 0, 1, 0, 1] + candies: [1, 10, 100, 1000, 10000] + keys: [[1], [], [3], [], []] + containedBoxes: [[1], [], [3], [], []] + initialBoxes: [0, 2, 4] + out: 11111 + - name: case25 + in: + status: [1, 0] + candies: [100, 1] + keys: [[], []] + containedBoxes: [[1], []] + initialBoxes: [0] + out: 100 + - name: case26 + in: + status: [0, 1] + candies: [100, 1] + keys: [[1], []] + containedBoxes: [[0], []] + initialBoxes: [1] + out: 1 + - name: case28 + in: + status: [1, 1, 0, 0] + candies: [9, 8, 7, 6] + keys: [[], [2], [3], []] + containedBoxes: [[], [2], [3], []] + initialBoxes: [1] + out: 21 + - name: case29 + in: + status: [1, 0, 0] + candies: [11, 22, 33] + keys: [[1], [2], []] + containedBoxes: [[1], [2], []] + initialBoxes: [0] + out: 66 + - name: case30 + in: + status: [0, 1, 0, 1] + candies: [2, 4, 6, 8] + keys: [[], [0], [], []] + containedBoxes: [[2], [], [], []] + initialBoxes: [1, 3] + out: 12 + - name: case31 + in: + status: [1, 0, 1, 0, 0, 0] + candies: [1, 1, 1, 1, 1, 1] + keys: [[1], [], [3], [], [5], []] + containedBoxes: [[1], [], [3], [4], [5], []] + initialBoxes: [0, 2] + out: 4 + - name: case32 + in: + status: [1, 0, 0, 1, 0] + candies: [3, 6, 9, 12, 15] + keys: [[1], [], [], [4], []] + containedBoxes: [[1], [2], [], [4], []] + initialBoxes: [0, 3] + out: 36 + - name: case33 + in: + status: [0, 0, 1, 0] + candies: [4, 8, 12, 16] + keys: [[0], [1], [3], []] + containedBoxes: [[], [], [3], []] + initialBoxes: [2] + out: 28 + - name: case34 + in: + status: [1, 1, 1, 1] + candies: [10, 20, 30, 40] + keys: [[], [], [], []] + containedBoxes: [[1, 2], [3], [], []] + initialBoxes: [0] + out: 100 + - name: case35 + in: + status: [1, 0, 1, 0, 1, 0] + candies: [5, 10, 15, 20, 25, 30] + keys: [[1], [], [3], [], [5], []] + containedBoxes: [[1], [], [3], [], [5], []] + initialBoxes: [0, 2, 4] + out: 105 + - name: chained_unlock_rounds + in: + status: [1, 1, 0, 0] + candies: [4, 5, 6, 7] + keys: [[], [2], [3], []] + containedBoxes: [[1], [], [3], []] + initialBoxes: [0] + out: 9 + - name: duplicate_initial_box + in: + status: [1] + candies: [13] + keys: [[]] + containedBoxes: [[]] + initialBoxes: [0, 0] + out: 13 + - name: initially_owned_child + in: + status: [1, 1] + candies: [8, 11] + keys: [[], []] + containedBoxes: [[1], []] + initialBoxes: [0, 1] + out: 19 + - name: key_and_box_from_separate_initial_boxes + in: + status: [1, 1, 0] + candies: [4, 9, 16] + keys: [[2], [], []] + containedBoxes: [[], [2], []] + initialBoxes: [0, 1] + out: 29 + - name: initially_held_closed_box_unlocked_later + in: + status: [0, 1, 0] + candies: [17, 6, 23] + keys: [[2], [0], []] + containedBoxes: [[2], [], []] + initialBoxes: [0, 1] + out: 46 + - name: static_long_unlock_chain + in: + status: + [ + 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, + ] + candies: + [ + 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, + ] + keys: + - [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] + - [] + containedBoxes: + - [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] + - [] + initialBoxes: [0] + out: 820 + - name: static_wide_open_frontier + in: + status: + [ + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + ] + candies: + [ + 1000, + 999, + 998, + 997, + 996, + 995, + 994, + 993, + 992, + 991, + 990, + 989, + 988, + 987, + 986, + 985, + 984, + 983, + 982, + 981, + 980, + 979, + 978, + 977, + 976, + 975, + 974, + 973, + 972, + 971, + 970, + 969, + 968, + 967, + 966, + 965, + 964, + 963, + 962, + 961, + ] + keys: + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + containedBoxes: + - [ + 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, + ] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + - [] + initialBoxes: [0] + out: 39220 + - name: generated_max_n_random_status_and_candies + seed: 129801 + in: + status: + gen: "array" + len: 1000 + of: + gen: "int" + min: 0 + max: 1 + elemType: "int" + candies: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 1000 + elemType: "int" + keys: + gen: "array" + len: 1000 + of: + gen: "array" + len: + gen: "int" + min: 0 + max: 8 + of: + gen: "int" + min: 0 + max: 999 + distinct: true + elemType: "int" + elemType: "int" + containedBoxes: + gen: "array" + len: 1000 + of: + gen: "array" + len: 0 + of: + gen: "int" + min: 0 + max: 999 + elemType: "int" + elemType: "int" + initialBoxes: + gen: "array" + len: 1000 + of: + gen: "int" + min: 0 + max: 999 + distinct: true + elemType: "int" + - name: generated_max_n_all_closed_with_keys + seed: 129802 + in: + status: + gen: "array" + len: 1000 + of: + gen: "int" + min: 0 + max: 0 + elemType: "int" + candies: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 1000 + elemType: "int" + keys: + gen: "array" + len: 1000 + of: + gen: "array" + len: 8 + of: + gen: "int" + min: 0 + max: 999 + distinct: true + elemType: "int" + elemType: "int" + containedBoxes: + gen: "array" + len: 1000 + of: + gen: "array" + len: 0 + of: + gen: "int" + min: 0 + max: 999 + elemType: "int" + elemType: "int" + initialBoxes: + gen: "array" + len: 1000 + of: + gen: "int" + min: 0 + max: 999 + distinct: true + elemType: "int" + - name: generated_max_n_all_open_empty_keys + seed: 129803 + in: + status: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 1 + elemType: "int" + candies: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 1000 + elemType: "int" + keys: + gen: "array" + len: 1000 + of: + gen: "array" + len: 0 + of: + gen: "int" + min: 0 + max: 999 + elemType: "int" + elemType: "int" + containedBoxes: + gen: "array" + len: 1000 + of: + gen: "array" + len: 0 + of: + gen: "int" + min: 0 + max: 999 + elemType: "int" + elemType: "int" + initialBoxes: + gen: "array" + len: 1000 + of: + gen: "int" + min: 0 + max: 999 + distinct: true + elemType: "int" + - name: generated_max_n_sparse_keys + seed: 129804 + in: + status: + gen: "array" + len: 1000 + of: + gen: "int" + min: 0 + max: 1 + elemType: "int" + candies: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 1000 + elemType: "int" + keys: + gen: "array" + len: 1000 + of: + gen: "array" + len: + gen: "int" + min: 0 + max: 1 + of: + gen: "int" + min: 0 + max: 999 + distinct: true + elemType: "int" + elemType: "int" + containedBoxes: + gen: "array" + len: 1000 + of: + gen: "array" + len: 0 + of: + gen: "int" + min: 0 + max: 999 + elemType: "int" + elemType: "int" + initialBoxes: + gen: "array" + len: 1000 + of: + gen: "int" + min: 0 + max: 999 + distinct: true + elemType: "int" + - name: generated_max_n_dense_keys + seed: 129805 + in: + status: + gen: "array" + len: 1000 + of: + gen: "int" + min: 0 + max: 1 + elemType: "int" + candies: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 1000 + elemType: "int" + keys: + gen: "array" + len: 1000 + of: + gen: "array" + len: 32 + of: + gen: "int" + min: 0 + max: 999 + distinct: true + elemType: "int" + elemType: "int" + containedBoxes: + gen: "array" + len: 1000 + of: + gen: "array" + len: 0 + of: + gen: "int" + min: 0 + max: 999 + elemType: "int" + elemType: "int" + initialBoxes: + gen: "array" + len: 1000 + of: + gen: "int" + min: 0 + max: 999 + distinct: true + elemType: "int" diff --git a/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.cpp b/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.cpp new file mode 100644 index 00000000..c409411a --- /dev/null +++ b/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int maxCandies(vector& status, vector& candies, vector>& keys, vector>& containedBoxes, vector& initialBoxes) { + unordered_set owned(initialBoxes.begin(), initialBoxes.end()); + unordered_set opened; + bool changed = true; + int totalCandies = 0; + while (changed) { + changed = false; + vector ownedVec(owned.begin(), owned.end()); + for (int boxId : ownedVec) { + if (opened.count(boxId) || status[boxId] == 0) continue; + opened.insert(boxId); + changed = true; + totalCandies += candies[boxId]; + for (int keyId : keys[boxId]) { + status[keyId] = 1; + } + for (int box : containedBoxes[boxId]) { + owned.insert(box); + } + } + } + return totalCandies; + } +}; diff --git a/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.cs b/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.cs new file mode 100644 index 00000000..b26b2da6 --- /dev/null +++ b/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.cs @@ -0,0 +1,25 @@ +public class Solution { + public int MaxCandies(int[] status, int[] candies, int[][] keys, int[][] containedBoxes, int[] initialBoxes) { + var owned = new HashSet(initialBoxes); + var opened = new HashSet(); + bool changed = true; + int totalCandies = 0; + while (changed) { + changed = false; + var ownedList = new List(owned); + foreach (int boxId in ownedList) { + if (opened.Contains(boxId) || status[boxId] == 0) continue; + opened.Add(boxId); + changed = true; + totalCandies += candies[boxId]; + foreach (int keyId in keys[boxId]) { + status[keyId] = 1; + } + foreach (int box in containedBoxes[boxId]) { + owned.Add(box); + } + } + } + return totalCandies; + } +} diff --git a/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.dart b/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.dart new file mode 100644 index 00000000..0e296743 --- /dev/null +++ b/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.dart @@ -0,0 +1,22 @@ +class Solution { + int maxCandies(List status, List candies, List> keys, List> containedBoxes, List initialBoxes) { + var owned = initialBoxes.toSet(); + var opened = {}; + var changed = true; + var totalCandies = 0; + while (changed) { + changed = false; + for (var boxId in owned.toList()) { + if (opened.contains(boxId) || status[boxId] == 0) continue; + opened.add(boxId); + changed = true; + totalCandies += candies[boxId]; + for (var keyId in keys[boxId]) { + status[keyId] = 1; + } + owned.addAll(containedBoxes[boxId]); + } + } + return totalCandies; + } +} diff --git a/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.go b/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.go new file mode 100644 index 00000000..14442794 --- /dev/null +++ b/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.go @@ -0,0 +1,27 @@ +func maxCandies(status []int, candies []int, keys [][]int, containedBoxes [][]int, initialBoxes []int) int { + owned := make(map[int]bool) + for _, box := range initialBoxes { + owned[box] = true + } + opened := make(map[int]bool) + changed := true + totalCandies := 0 + for changed { + changed = false + for boxId := range owned { + if opened[boxId] || status[boxId] == 0 { + continue + } + opened[boxId] = true + changed = true + totalCandies += candies[boxId] + for _, keyId := range keys[boxId] { + status[keyId] = 1 + } + for _, box := range containedBoxes[boxId] { + owned[box] = true + } + } + } + return totalCandies +} diff --git a/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.java b/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.java new file mode 100644 index 00000000..aab92c22 --- /dev/null +++ b/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.java @@ -0,0 +1,26 @@ +class Solution { + public int maxCandies(int[] status, int[] candies, int[][] keys, int[][] containedBoxes, int[] initialBoxes) { + java.util.Set owned = new java.util.HashSet<>(); + for (int box : initialBoxes) owned.add(box); + java.util.Set opened = new java.util.HashSet<>(); + boolean changed = true; + int totalCandies = 0; + while (changed) { + changed = false; + Integer[] ownedArr = owned.toArray(new Integer[0]); + for (int boxId : ownedArr) { + if (opened.contains(boxId) || status[boxId] == 0) continue; + opened.add(boxId); + changed = true; + totalCandies += candies[boxId]; + for (int keyId : keys[boxId]) { + status[keyId] = 1; + } + for (int box : containedBoxes[boxId]) { + owned.add(box); + } + } + } + return totalCandies; + } +} diff --git a/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.kt b/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.kt new file mode 100644 index 00000000..27024193 --- /dev/null +++ b/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.kt @@ -0,0 +1,23 @@ +class Solution { + fun maxCandies(status: IntArray, candies: IntArray, keys: Array, containedBoxes: Array, initialBoxes: IntArray): Int { + val owned = initialBoxes.toMutableSet() + val opened = mutableSetOf() + var changed = true + var totalCandies = 0 + while (changed) { + changed = false + val ownedList = owned.toList() + for (boxId in ownedList) { + if (boxId in opened || status[boxId] == 0) continue + opened.add(boxId) + changed = true + totalCandies += candies[boxId] + for (keyId in keys[boxId]) { + status[keyId] = 1 + } + owned.addAll(containedBoxes[boxId].toList()) + } + } + return totalCandies + } +} diff --git a/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.py b/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.py new file mode 100644 index 00000000..ce95c653 --- /dev/null +++ b/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.py @@ -0,0 +1,18 @@ +class Solution(object): + def maxCandies(self, status, candies, keys, containedBoxes, initialBoxes): + owned = set(initialBoxes) + opened = set() + changed = True + totalCandies = 0 + while changed: + changed = False + for boxId in list(owned): + if boxId in opened or not status[boxId]: + continue + opened.add(boxId) + changed = True + totalCandies += candies[boxId] + for keyId in keys[boxId]: + status[keyId] = 1 + owned.update(containedBoxes[boxId]) + return totalCandies diff --git a/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.py2 b/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.py2 new file mode 100644 index 00000000..4af12981 --- /dev/null +++ b/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.py2 @@ -0,0 +1,26 @@ +class Solution(object): + def maxCandies(self, status, candies, keys, containedBoxes, initialBoxes): + """ + :type status: List[int] + :type candies: List[int] + :type keys: List[List[int]] + :type containedBoxes: List[List[int]] + :type initialBoxes: List[int] + :rtype: int + """ + owned = set(initialBoxes) + opened = set() + changed = True + totalCandies = 0 + while changed: + changed = False + for boxId in list(owned): + if boxId in opened or not status[boxId]: + continue + opened.add(boxId) + changed = True + totalCandies += candies[boxId] + for keyId in keys[boxId]: + status[keyId] = 1 + owned.update(containedBoxes[boxId]) + return totalCandies diff --git a/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.rb b/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.rb new file mode 100644 index 00000000..21cb6537 --- /dev/null +++ b/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.rb @@ -0,0 +1,24 @@ +# @param {Integer[]} status +# @param {Integer[]} candies +# @param {Integer[][]} keys +# @param {Integer[][]} contained_boxes +# @param {Integer[]} initial_boxes +# @return {Integer} +def max_candies(status, candies, keys, contained_boxes, initial_boxes) + owned = initial_boxes.to_set + opened = Set.new + changed = true + total_candies = 0 + while changed + changed = false + owned.to_a.each do |box_id| + next if opened.include?(box_id) || status[box_id] == 0 + opened.add(box_id) + changed = true + total_candies += candies[box_id] + keys[box_id].each { |key_id| status[key_id] = 1 } + owned.merge(contained_boxes[box_id]) + end + end + total_candies +end diff --git a/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.rs b/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.rs new file mode 100644 index 00000000..e68dfdbd --- /dev/null +++ b/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.rs @@ -0,0 +1,27 @@ +impl Solution { + pub fn max_candies(mut status: Vec, candies: Vec, keys: Vec>, contained_boxes: Vec>, initial_boxes: Vec) -> i32 { + let mut owned: HashSet = initial_boxes.into_iter().collect(); + let mut opened: HashSet = HashSet::new(); + let mut changed = true; + let mut total_candies = 0; + while changed { + changed = false; + let owned_list: Vec = owned.iter().cloned().collect(); + for box_id in owned_list { + if opened.contains(&box_id) || status[box_id as usize] == 0 { + continue; + } + opened.insert(box_id); + changed = true; + total_candies += candies[box_id as usize]; + for &key_id in &keys[box_id as usize] { + status[key_id as usize] = 1; + } + for &contained_box in &contained_boxes[box_id as usize] { + owned.insert(contained_box); + } + } + } + total_candies + } +} diff --git a/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.swift b/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.swift new file mode 100644 index 00000000..11c6f264 --- /dev/null +++ b/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.swift @@ -0,0 +1,25 @@ +class Solution { + func maxCandies(_ status: [Int], _ candies: [Int], _ keys: [[Int]], _ containedBoxes: [[Int]], _ initialBoxes: [Int]) -> Int { + var status = status + var owned = Set(initialBoxes) + var opened = Set() + var changed = true + var totalCandies = 0 + while changed { + changed = false + for boxId in owned { + if opened.contains(boxId) || status[boxId] == 0 { + continue + } + opened.insert(boxId) + changed = true + totalCandies += candies[boxId] + for keyId in keys[boxId] { + status[keyId] = 1 + } + owned.formUnion(containedBoxes[boxId]) + } + } + return totalCandies + } +} diff --git a/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.ts b/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.ts new file mode 100644 index 00000000..14f429fe --- /dev/null +++ b/tests/1001-1500/1298. maximum-candies-you-can-get-from-boxes/sol.ts @@ -0,0 +1,29 @@ +function maxCandies( + status: number[], + candies: number[], + keys: number[][], + containedBoxes: number[][], + initialBoxes: number[], +): number { + const owned = new Set(initialBoxes); + const opened = new Set(); + let changed = true; + let totalCandies = 0; + while (changed) { + changed = false; + const ownedArr = Array.from(owned); + for (const boxId of ownedArr) { + if (opened.has(boxId) || status[boxId] === 0) continue; + opened.add(boxId); + changed = true; + totalCandies += candies[boxId]; + for (const keyId of keys[boxId]) { + status[keyId] = 1; + } + for (const box of containedBoxes[boxId]) { + owned.add(box); + } + } + } + return totalCandies; +} diff --git a/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/manifest.yaml b/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/manifest.yaml new file mode 100644 index 00000000..7a6095ea --- /dev/null +++ b/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/manifest.yaml @@ -0,0 +1,247 @@ +entry: + id: 1299 + title: "replace-elements-with-greatest-element-on-right-side" + params: + arr: + type: array + items: + type: int + call: + cpp: "Solution().replaceElements({arr})" + rust: "Solution::replace_elements({arr})" + python3: "Solution().replaceElements({arr})" + python2: "Solution().replaceElements({arr})" + ruby: "replace_elements({arr})" + java: "new Solution().replaceElements({arr})" + csharp: "new Solution().ReplaceElements({arr})" + kotlin: "Solution().replaceElements({arr})" + go: "replaceElements({arr})" + dart: "Solution().replaceElements({arr})" + swift: "Solution().replaceElements({arr})" + typescript: "replaceElements({arr})" +judge: + type: "exact" +limits: + time_ms: 500 + memory_mb: 300 +oracle: + python3: + call: "Checker().replaceElements(arr, {result})" + checker: | + class Checker: + def replaceElements(self, arr, result): + if not isinstance(result, list) or len(result) != len(arr): + return False + greatest_right = -1 + for i in range(len(arr) - 1, -1, -1): + if result[i] != greatest_right: + return False + greatest_right = max(greatest_right, arr[i]) + return True +seed: 1299 +tests: + - name: "example_one" + in: + arr: [17, 18, 5, 4, 6, 1] + out: [18, 6, 6, 6, 1, -1] + - name: "example_two_singleton" + in: + arr: [400] + out: [-1] + - name: "single_minimum" + in: + arr: [1] + out: [-1] + - name: "single_maximum" + in: + arr: [100000] + out: [-1] + - name: "two_descending" + in: + arr: [2, 1] + out: [1, -1] + - name: "two_equal" + in: + arr: [8, 8] + out: [8, -1] + - name: "strictly_increasing" + in: + arr: [1, 2, 3, 4, 5] + out: [5, 5, 5, 5, -1] + - name: "strictly_decreasing" + in: + arr: [5, 4, 3, 2, 1] + out: [4, 3, 2, 1, -1] + - name: "all_equal" + in: + arr: [7, 7, 7, 7, 7] + out: [7, 7, 7, 7, -1] + - name: "max_at_start" + in: + arr: [100000, 1, 2, 3] + out: [3, 3, 3, -1] + - name: "max_at_end" + in: + arr: [1, 2, 3, 100000] + out: [100000, 100000, 100000, -1] + - name: "repeated_global_maxima" + in: + arr: [4, 9, 2, 9, 1] + out: [9, 9, 9, 1, -1] + - name: "alternating_peaks" + in: + arr: [1, 9, 2, 8, 3, 7] + out: [9, 8, 8, 7, 7, -1] + - name: "local_peak_followed_by_larger_peak" + in: + arr: [2, 1, 4, 3, 5, 1] + out: [5, 5, 5, 5, 1, -1] + - name: "low_plateau_before_peak" + in: + arr: [1, 1, 1, 2, 1, 1] + out: [2, 2, 2, 1, 1, -1] + - name: "constraint_boundaries" + in: + arr: [1, 100000, 1, 100000, 1] + out: [100000, 100000, 100000, 1, -1] + - name: "descending_zigzag" + in: + arr: [9, 1, 8, 2, 7, 3, 6] + out: [8, 8, 7, 7, 6, 6, -1] + - name: "constant_then_final_peak" + in: + arr: [5, 5, 5, 10] + out: [10, 10, 10, -1] + - name: "initial_peak_then_constant" + in: + arr: [10, 5, 5, 5] + out: [5, 5, 5, -1] + - name: "middle_peak" + in: + arr: [2, 10, 3] + out: [10, 3, -1] + - name: "alternating_descending_records" + in: + arr: [10, 1, 9, 2, 8, 3, 7, 4] + out: [9, 9, 8, 8, 7, 7, 4, -1] + - name: "duplicate_low_values" + in: + arr: [2, 2, 1, 2, 1] + out: [2, 2, 2, 1, -1] + - name: "near_maximum_middle" + in: + arr: [1, 2, 99999, 3, 4] + out: [99999, 99999, 4, 4, -1] + - name: "multiple_suffix_record_changes" + in: + arr: [8, 3, 12, 4, 6, 2, 15, 1, 10] + out: [15, 15, 15, 15, 15, 15, 10, 10, -1] + - name: "nearby_large_records" + in: + arr: [100, 1, 99, 2] + out: [99, 99, 2, -1] + - name: "plateau_steps" + in: + arr: [4, 4, 6, 6, 2, 2] + out: [6, 6, 6, 2, 2, -1] + - name: "interleaved_bounds" + in: + arr: [1, 100, 2, 99, 3, 98] + out: [100, 99, 99, 98, 98, -1] + - name: "long_constant" + in: + arr: [42, 42, 42, 42, 42, 42, 42, 42] + out: [42, 42, 42, 42, 42, 42, 42, -1] + - name: "rightmost_dominates" + in: + arr: [50, 1, 49, 2, 48, 100] + out: [100, 100, 100, 100, 100, -1] + - name: "rightmost_minimum" + in: + arr: [100000, 99999, 1] + out: [99999, 1, -1] + - name: "repeated_suffix_maximum" + in: + arr: [6, 1, 6, 1, 6, 1] + out: [6, 6, 6, 6, 1, -1] + - name: "short_mixed_values" + in: + arr: [11, 3, 14, 2, 13, 4] + out: [14, 14, 13, 13, 4, -1] + - name: "descending_peak_staircase" + in: + arr: [3, 10, 2, 9, 1, 8] + out: [10, 9, 9, 8, 8, -1] + - name: "trailing_equal_maxima" + in: + arr: [1, 5, 5] + out: [5, 5, -1] + - name: "small_generated_range" + seed: 11 + in: + arr: + gen: "array" + len: + gen: "int" + min: 1 + max: 20 + of: + gen: "int" + min: 1 + max: 100 + - name: "duplicate_heavy_generated" + seed: 22 + in: + arr: + gen: "array" + len: + gen: "int" + min: 20 + max: 100 + of: + gen: "int" + min: 1 + max: 5 + - name: "medium_full_value_range" + seed: 33 + in: + arr: + gen: "array" + len: + gen: "int" + min: 500 + max: 1000 + of: + gen: "int" + min: 1 + max: 100000 + - name: "large_uniform_range" + seed: 44 + in: + arr: + gen: "array" + len: 5000 + of: + gen: "int" + min: 1 + max: 100000 + - name: "near_limit_full_range" + seed: 55 + in: + arr: + gen: "array" + len: 9999 + of: + gen: "int" + min: 1 + max: 100000 + - name: "maximum_length_duplicate_stress" + seed: 66 + in: + arr: + gen: "array" + len: 10000 + of: + gen: "int" + min: 1 + max: 10 diff --git a/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.cpp b/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.cpp new file mode 100644 index 00000000..c05b796c --- /dev/null +++ b/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + vector replaceElements(vector& arr) { + int max_element = -1; + for (int i = arr.size() - 1; i >= 0; i--) { + int temp = arr[i]; + arr[i] = max_element; + max_element = max(max_element, temp); + } + return arr; + } +}; diff --git a/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.cs b/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.cs new file mode 100644 index 00000000..1123c952 --- /dev/null +++ b/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.cs @@ -0,0 +1,11 @@ +public class Solution { + public int[] ReplaceElements(int[] arr) { + int maxElement = -1; + for (int i = arr.Length - 1; i >= 0; i--) { + int temp = arr[i]; + arr[i] = maxElement; + maxElement = Math.Max(maxElement, temp); + } + return arr; + } +} diff --git a/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.dart b/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.dart new file mode 100644 index 00000000..ac87b104 --- /dev/null +++ b/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.dart @@ -0,0 +1,13 @@ +class Solution { + List replaceElements(List arr) { + int maxElement = -1; + for (int i = arr.length - 1; i >= 0; i--) { + int temp = arr[i]; + arr[i] = maxElement; + if (temp > maxElement) { + maxElement = temp; + } + } + return arr; + } +} diff --git a/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.go b/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.go new file mode 100644 index 00000000..ef3635e1 --- /dev/null +++ b/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.go @@ -0,0 +1,11 @@ +func replaceElements(arr []int) []int { + maxElement := -1 + for i := len(arr) - 1; i >= 0; i-- { + temp := arr[i] + arr[i] = maxElement + if temp > maxElement { + maxElement = temp + } + } + return arr +} diff --git a/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.java b/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.java new file mode 100644 index 00000000..acd11a77 --- /dev/null +++ b/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.java @@ -0,0 +1,11 @@ +class Solution { + public int[] replaceElements(int[] arr) { + int maxElement = -1; + for (int i = arr.length - 1; i >= 0; i--) { + int temp = arr[i]; + arr[i] = maxElement; + maxElement = Math.max(maxElement, temp); + } + return arr; + } +} diff --git a/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.kt b/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.kt new file mode 100644 index 00000000..5df2291a --- /dev/null +++ b/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.kt @@ -0,0 +1,11 @@ +class Solution { + fun replaceElements(arr: IntArray): IntArray { + var maxElement = -1 + for (i in arr.indices.reversed()) { + val temp = arr[i] + arr[i] = maxElement + maxElement = maxOf(maxElement, temp) + } + return arr + } +} diff --git a/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.py b/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.py new file mode 100644 index 00000000..705da973 --- /dev/null +++ b/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.py @@ -0,0 +1,6 @@ +class Solution: + def replaceElements(self, arr: List[int]) -> List[int]: + max_element = -1 + for i in range(len(arr) - 1, -1, -1): + arr[i], max_element = max_element, max(max_element, arr[i]) + return arr diff --git a/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.py2 b/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.py2 new file mode 100644 index 00000000..3fb15277 --- /dev/null +++ b/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.py2 @@ -0,0 +1,10 @@ +class Solution(object): + def replaceElements(self, arr): + """ + :type arr: List[int] + :rtype: List[int] + """ + max_element = -1 + for i in range(len(arr)-1, -1, -1): + arr[i], max_element = max_element, max(max_element, arr[i]) + return arr diff --git a/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.rb b/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.rb new file mode 100644 index 00000000..558dd1fc --- /dev/null +++ b/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.rb @@ -0,0 +1,9 @@ +# @param {Integer[]} arr +# @return {Integer[]} +def replace_elements(arr) + max_element = -1 + (arr.length - 1).downto(0) do |i| + arr[i], max_element = max_element, [max_element, arr[i]].max + end + arr +end diff --git a/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.rs b/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.rs new file mode 100644 index 00000000..fd5048b1 --- /dev/null +++ b/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.rs @@ -0,0 +1,12 @@ +impl Solution { + pub fn replace_elements(arr: Vec) -> Vec { + let mut arr = arr; + let mut max_element = -1; + for i in (0..arr.len()).rev() { + let temp = arr[i]; + arr[i] = max_element; + max_element = max_element.max(temp); + } + arr + } +} diff --git a/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.swift b/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.swift new file mode 100644 index 00000000..40554092 --- /dev/null +++ b/tests/1001-1500/1299. replace-elements-with-greatest-element-on-right-side/sol.swift @@ -0,0 +1,12 @@ +class Solution { + func replaceElements(_ arr: [Int]) -> [Int] { + var arr = arr + var maxElement = -1 + for i in (0..= 0; i--) { + let temp = arr[i]; + arr[i] = maxElement; + maxElement = Math.max(maxElement, temp); + } + return arr; +} diff --git a/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/manifest.yaml b/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/manifest.yaml new file mode 100644 index 00000000..7feca620 --- /dev/null +++ b/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/manifest.yaml @@ -0,0 +1,333 @@ +entry: + id: 1300 + title: "sum-of-mutated-array-closest-to-target" + params: + arr: + type: array + items: + type: int + target: + type: int + call: + cpp: "Solution().findBestValue({arr}, {target})" + rust: "Solution::find_best_value({arr}, {target})" + python3: "Solution().findBestValue({arr}, {target})" + python2: "Solution().findBestValue({arr}, {target})" + ruby: "find_best_value({arr}, {target})" + java: "new Solution().findBestValue({arr}, {target})" + csharp: "new Solution().FindBestValue({arr}, {target})" + kotlin: "Solution().findBestValue({arr}, {target})" + go: "findBestValue({arr}, {target})" + dart: "Solution().findBestValue({arr}, {target})" + swift: "Solution().findBestValue({arr}, {target})" + typescript: "findBestValue({arr}, {target})" + +judge: + type: "exact" + +limits: + time_ms: 700 + memory_mb: 300 + +oracle: + python3: + call: "Checker().findBestValue(arr, target, {result})" + checker: | + class Checker: + def findBestValue(self, arr, target, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + maximum = max(arr) + if result < 0 or result > maximum: + return False + + def mutated_sum(value): + return sum(min(item, value) for item in arr) + + # The sum is monotone, so only the caps bracketing target can be optimal. + low, high = 0, maximum + while low < high: + mid = (low + high) // 2 + if mutated_sum(mid) < target: + low = mid + 1 + else: + high = mid + lower = max(0, low - 1) + expected = min((lower, low), key=lambda value: (abs(mutated_sum(value) - target), value)) + return result == expected + +seed: 130000 + +tests: + - name: "example_one" + in: + arr: [4, 9, 3] + target: 10 + out: 3 + - name: "example_two" + in: + arr: [2, 3, 5] + target: 10 + out: 5 + - name: "example_three" + in: + arr: [60864, 25176, 27249, 21296, 20204] + target: 56803 + out: 11361 + - name: "single_exact" + in: + arr: [10] + target: 10 + out: 10 + - name: "single_partial" + in: + arr: [10] + target: 3 + out: 3 + - name: "single_target_above_sum" + in: + arr: [10] + target: 20 + out: 10 + - name: "all_equal_exact" + in: + arr: [5, 5, 5] + target: 15 + out: 5 + - name: "all_equal_round_down" + in: + arr: [5, 5, 5] + target: 10 + out: 3 + - name: "zero_cap_is_closest" + in: + arr: [5, 5, 5] + target: 1 + out: 0 + - name: "uncapped_sum_exact" + in: + arr: [1, 2, 3, 4] + target: 10 + out: 4 + - name: "one_vs_zero_tie" + in: + arr: [1, 2, 3] + target: 1 + out: 0 + - name: "small_exact_cap" + in: + arr: [1, 2] + target: 2 + out: 1 + - name: "nonmember_exact_answer" + in: + arr: [2, 4] + target: 5 + out: 3 + - name: "duplicates_with_outlier" + in: + arr: [4, 4, 4, 100] + target: 20 + out: 8 + - name: "small_values_with_outlier" + in: + arr: [1, 1, 1, 1000] + target: 10 + out: 7 + - name: "ascending_exact" + in: + arr: [1, 2, 3, 4, 5] + target: 12 + out: 3 + - name: "descending_order_irrelevant" + in: + arr: [5, 4, 3, 2, 1] + target: 12 + out: 3 + - name: "two_elements_nonmember" + in: + arr: [2, 8] + target: 9 + out: 7 + - name: "many_ones" + in: + arr: [1, 1, 1, 1, 1, 1] + target: 4 + out: 1 + - name: "powers_of_two" + in: + arr: [1, 2, 4, 8, 16] + target: 25 + out: 10 + - name: "large_values_exact" + in: + arr: [100000, 99999, 99998] + target: 150000 + out: 50000 + - name: "minimum_values" + in: + arr: [1, 1, 1, 1] + target: 3 + out: 1 + - name: "half_of_two_maxima" + in: + arr: [100000, 100000] + target: 100000 + out: 50000 + - name: "plateau_then_linear" + in: + arr: [3, 3, 3, 7, 20] + target: 25 + out: 9 + - name: "large_gap_exact" + in: + arr: [1, 50, 100] + target: 75 + out: 37 + - name: "repeated_large_values" + in: + arr: [1000, 1000, 1000, 1] + target: 2500 + out: 833 + - name: "mixed_even_values" + in: + arr: [2, 4, 6, 8, 10, 12] + target: 30 + out: 6 + - name: "tie_uses_lower_cap" + in: + arr: [10, 20, 30] + target: 41 + out: 15 + - name: "near_uncapped_sum" + in: + arr: [7, 8, 9, 10] + target: 33 + out: 9 + - name: "outlier_dominates" + in: + arr: [2, 2, 2, 2, 50] + target: 20 + out: 12 + - name: "high_cardinality_tie" + in: + arr: [11, 22, 33, 44, 55, 66, 77, 88] + target: 300 + out: 47 + - name: "small_target_large_elements" + in: + arr: [100, 200, 300, 400] + target: 5 + out: 1 + - name: "near_maximum_nonmember" + in: + arr: [1, 100000] + target: 100000 + out: 99999 + - name: "large_cap_after_small_prefix" + in: + arr: [1, 1, 1, 1, 100000] + target: 99999 + out: 99995 + - name: "generated_large_random_a" + seed: 130001 + in: + arr: + gen: "array" + len: 10000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + target: + gen: "int" + min: 1 + max: 100000 + - name: "generated_large_random_b" + seed: 130002 + in: + arr: + gen: "array" + len: 10000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + target: + gen: "int" + min: 1 + max: 100000 + - name: "generated_large_random_c" + seed: 130003 + in: + arr: + gen: "array" + len: 10000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + target: + gen: "int" + min: 1 + max: 100000 + - name: "generated_large_random_d" + seed: 130004 + in: + arr: + gen: "array" + len: 10000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + target: + gen: "int" + min: 1 + max: 100000 + - name: "generated_large_random_e" + seed: 130005 + in: + arr: + gen: "array" + len: 10000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + target: + gen: "int" + min: 1 + max: 100000 + - name: "generated_large_random_f" + seed: 130006 + in: + arr: + gen: "array" + len: 10000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + target: + gen: "int" + min: 1 + max: 100000 diff --git a/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.cpp b/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.cpp new file mode 100644 index 00000000..78942ad7 --- /dev/null +++ b/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + int findBestValue(vector& arr, int target) { + auto getMutatedSum = [&](int value) -> int { + int sum = 0; + for (int x : arr) { + sum += min(x, value); + } + return sum; + }; + + int low = 0; + int high = *max_element(arr.begin(), arr.end()); + int result = high; + int minDiff = INT_MAX; + + while (low <= high) { + int mid = low + (high - low) / 2; + int currSum = getMutatedSum(mid); + int diff = abs(currSum - target); + + if (diff < minDiff || (diff == minDiff && mid < result)) { + minDiff = diff; + result = mid; + } + + if (currSum < target) { + low = mid + 1; + } else { + high = mid - 1; + } + } + + return result; + } +}; diff --git a/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.cs b/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.cs new file mode 100644 index 00000000..802a1d91 --- /dev/null +++ b/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.cs @@ -0,0 +1,35 @@ +public class Solution { + public int FindBestValue(int[] arr, int target) { + int GetMutatedSum(int value) { + int sum = 0; + foreach (int x in arr) { + sum += Math.Min(x, value); + } + return sum; + } + + int low = 0; + int high = arr.Max(); + int result = high; + int minDiff = int.MaxValue; + + while (low <= high) { + int mid = low + (high - low) / 2; + int currSum = GetMutatedSum(mid); + int diff = Math.Abs(currSum - target); + + if (diff < minDiff || (diff == minDiff && mid < result)) { + minDiff = diff; + result = mid; + } + + if (currSum < target) { + low = mid + 1; + } else { + high = mid - 1; + } + } + + return result; + } +} diff --git a/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.dart b/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.dart new file mode 100644 index 00000000..949580c9 --- /dev/null +++ b/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.dart @@ -0,0 +1,35 @@ +class Solution { + int findBestValue(List arr, int target) { + int getMutatedSum(int value) { + int sum = 0; + for (int x in arr) { + sum += x < value ? x : value; + } + return sum; + } + + int low = 0; + int high = arr.reduce((a, b) => a > b ? a : b); + int result = high; + int minDiff = 1 << 63 - 1; // MaxInt approximation + + while (low <= high) { + int mid = low + (high - low) ~/ 2; + int currSum = getMutatedSum(mid); + int diff = (currSum - target).abs(); + + if (diff < minDiff || (diff == minDiff && mid < result)) { + minDiff = diff; + result = mid; + } + + if (currSum < target) { + low = mid + 1; + } else { + high = mid - 1; + } + } + + return result; + } +} diff --git a/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.go b/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.go new file mode 100644 index 00000000..0d79ef72 --- /dev/null +++ b/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.go @@ -0,0 +1,45 @@ +func findBestValue(arr []int, target int) int { + getMutatedSum := func(value int) int { + sum := 0 + for _, x := range arr { + if x < value { + sum += x + } else { + sum += value + } + } + return sum + } + + low, high := 0, 0 + for _, x := range arr { + if x > high { + high = x + } + } + + result := high + minDiff := int(^uint(0) >> 1) // MaxInt + + for low <= high { + mid := low + (high - low) / 2 + currSum := getMutatedSum(mid) + diff := currSum - target + if diff < 0 { + diff = -diff + } + + if diff < minDiff || (diff == minDiff && mid < result) { + minDiff = diff + result = mid + } + + if currSum < target { + low = mid + 1 + } else { + high = mid - 1 + } + } + + return result +} diff --git a/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.java b/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.java new file mode 100644 index 00000000..5e8fdab8 --- /dev/null +++ b/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.java @@ -0,0 +1,34 @@ +class Solution { + public int findBestValue(int[] arr, int target) { + int low = 0; + int high = 0; + for (int x : arr) { + if (x > high) high = x; + } + + int result = high; + int minDiff = Integer.MAX_VALUE; + + while (low <= high) { + int mid = low + (high - low) / 2; + int currSum = 0; + for (int x : arr) { + currSum += Math.min(x, mid); + } + int diff = Math.abs(currSum - target); + + if (diff < minDiff || (diff == minDiff && mid < result)) { + minDiff = diff; + result = mid; + } + + if (currSum < target) { + low = mid + 1; + } else { + high = mid - 1; + } + } + + return result; + } +} diff --git a/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.kt b/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.kt new file mode 100644 index 00000000..86b3fff3 --- /dev/null +++ b/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.kt @@ -0,0 +1,27 @@ +class Solution { + fun findBestValue(arr: IntArray, target: Int): Int { + var low = 0 + var high = arr.max() + var result = high + var minDiff = Int.MAX_VALUE + + while (low <= high) { + val mid = low + (high - low) / 2 + val currSum = arr.sumOf { minOf(it, mid) } + val diff = Math.abs(currSum - target) + + if (diff < minDiff || (diff == minDiff && mid < result)) { + minDiff = diff + result = mid + } + + if (currSum < target) { + low = mid + 1 + } else { + high = mid - 1 + } + } + + return result + } +} diff --git a/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.py b/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.py new file mode 100644 index 00000000..3984f201 --- /dev/null +++ b/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.py @@ -0,0 +1,30 @@ +class Solution(object): + def findBestValue(self, arr, target): + """ + :type arr: List[int] + :type target: int + :rtype: int + """ + + def get_mutated_sum(value): + return sum(min(x, value) for x in arr) + + low, high = 0, max(arr) + result = high + min_diff = float("inf") + + while low <= high: + mid = (low + high) // 2 + curr_sum = get_mutated_sum(mid) + diff = abs(curr_sum - target) + + if diff < min_diff or (diff == min_diff and mid < result): + min_diff = diff + result = mid + + if curr_sum < target: + low = mid + 1 + else: + high = mid - 1 + + return result diff --git a/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.py2 b/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.py2 new file mode 100644 index 00000000..30244799 --- /dev/null +++ b/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.py2 @@ -0,0 +1,29 @@ +class Solution(object): + def findBestValue(self, arr, target): + """ + :type arr: List[int] + :type target: int + :rtype: int + """ + def get_mutated_sum(value): + return sum(min(x, value) for x in arr) + + low, high = 0, max(arr) + result = high + min_diff = float('inf') + + while low <= high: + mid = (low + high) // 2 + curr_sum = get_mutated_sum(mid) + diff = abs(curr_sum - target) + + if diff < min_diff or (diff == min_diff and mid < result): + min_diff = diff + result = mid + + if curr_sum < target: + low = mid + 1 + else: + high = mid - 1 + + return result diff --git a/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.rb b/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.rb new file mode 100644 index 00000000..e778837a --- /dev/null +++ b/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.rb @@ -0,0 +1,32 @@ +# @param {Integer[]} arr +# @param {Integer} target +# @return {Integer} +def find_best_value(arr, target) + get_mutated_sum = ->(value) { + arr.sum { |x| [x, value].min } + } + + low = 0 + high = arr.max + result = high + min_diff = Float::INFINITY + + while low <= high + mid = (low + high) / 2 + curr_sum = get_mutated_sum.call(mid) + diff = (curr_sum - target).abs + + if diff < min_diff || (diff == min_diff && mid < result) + min_diff = diff + result = mid + end + + if curr_sum < target + low = mid + 1 + else + high = mid - 1 + end + end + + result +end diff --git a/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.rs b/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.rs new file mode 100644 index 00000000..9e1b459b --- /dev/null +++ b/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.rs @@ -0,0 +1,31 @@ +impl Solution { + pub fn find_best_value(arr: Vec, target: i32) -> i32 { + let get_mutated_sum = |value: i32| -> i32 { + arr.iter().map(|&x| x.min(value)).sum() + }; + + let mut low = 0; + let mut high = *arr.iter().max().unwrap(); + let mut result = high; + let mut min_diff = i32::MAX; + + while low <= high { + let mid = low + (high - low) / 2; + let curr_sum = get_mutated_sum(mid); + let diff = (curr_sum - target).abs(); + + if diff < min_diff || (diff == min_diff && mid < result) { + min_diff = diff; + result = mid; + } + + if curr_sum < target { + low = mid + 1; + } else { + high = mid - 1; + } + } + + result + } +} diff --git a/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.swift b/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.swift new file mode 100644 index 00000000..95bf6c5f --- /dev/null +++ b/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.swift @@ -0,0 +1,31 @@ +class Solution { + func findBestValue(_ arr: [Int], _ target: Int) -> Int { + func getMutatedSum(_ value: Int) -> Int { + return arr.reduce(0) { $0 + min($1, value) } + } + + var low = 0 + var high = arr.max()! + var result = high + var minDiff = Int.max + + while low <= high { + let mid = low + (high - low) / 2 + let currSum = getMutatedSum(mid) + let diff = abs(currSum - target) + + if diff < minDiff || (diff == minDiff && mid < result) { + minDiff = diff + result = mid + } + + if currSum < target { + low = mid + 1 + } else { + high = mid - 1 + } + } + + return result + } +} diff --git a/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.ts b/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.ts new file mode 100644 index 00000000..617b98f2 --- /dev/null +++ b/tests/1001-1500/1300. sum-of-mutated-array-closest-to-target/sol.ts @@ -0,0 +1,29 @@ +function findBestValue(arr: number[], target: number): number { + const getMutatedSum = (value: number): number => { + return arr.reduce((sum, x) => sum + Math.min(x, value), 0); + }; + + let low = 0; + let high = Math.max(...arr); + let result = high; + let minDiff = Infinity; + + while (low <= high) { + const mid = Math.floor((low + high) / 2); + const currSum = getMutatedSum(mid); + const diff = Math.abs(currSum - target); + + if (diff < minDiff || (diff === minDiff && mid < result)) { + minDiff = diff; + result = mid; + } + + if (currSum < target) { + low = mid + 1; + } else { + high = mid - 1; + } + } + + return result; +} diff --git a/tests/1001-1500/1301. number-of-paths-with-max-score/manifest.yaml b/tests/1001-1500/1301. number-of-paths-with-max-score/manifest.yaml new file mode 100644 index 00000000..0caae137 --- /dev/null +++ b/tests/1001-1500/1301. number-of-paths-with-max-score/manifest.yaml @@ -0,0 +1,486 @@ +entry: + id: 1301 + title: "number-of-paths-with-max-score" + params: + board: + type: array + items: + type: string + call: + cpp: "Solution().pathsWithMaxScore({board})" + rust: "Solution::paths_with_max_score({board})" + python3: "Solution().pathsWithMaxScore({board})" + python2: "Solution().pathsWithMaxScore({board})" + ruby: "paths_with_max_score({board})" + java: "new Solution().pathsWithMaxScore({board})" + csharp: "new Solution().PathsWithMaxScore({board})" + kotlin: "Solution().pathsWithMaxScore({board})" + go: "pathsWithMaxScore({board})" + dart: "Solution().pathsWithMaxScore({board})" + swift: "Solution().pathsWithMaxScore({board})" + typescript: "pathsWithMaxScore({board})" + +judge: + type: "exact" + +limits: + time_ms: 2500 + memory_mb: 256 + +oracle: + python3: + call: "Checker().pathsWithMaxScore(board, {result})" + checker: | + class Checker: + def pathsWithMaxScore(self, board, result): + mod = 1000000007 + n = len(board) + score = [[-1] * n for _ in range(n)] + ways = [[0] * n for _ in range(n)] + score[n - 1][n - 1] = 0 + ways[n - 1][n - 1] = 1 + for i in range(n - 1, -1, -1): + for j in range(n - 1, -1, -1): + if board[i][j] == 'X' or (i == n - 1 and j == n - 1): + continue + choices = [] + for di, dj in ((1, 0), (0, 1), (1, 1)): + ni, nj = i + di, j + dj + if ni < n and nj < n and score[ni][nj] >= 0: + choices.append((score[ni][nj], ways[ni][nj])) + if choices: + best = max(value for value, _ in choices) + score[i][j] = best + (0 if board[i][j] == 'E' else int(board[i][j])) + ways[i][j] = sum(count for value, count in choices if value == best) % mod + expected = [0, 0] if score[0][0] < 0 else [score[0][0], ways[0][0]] + return result == expected + +seed: 1301 + +tests: + - name: "example-one" + in: + board: ["E23", "2X2", "12S"] + out: [7, 1] + - name: "example-two" + in: + board: ["E12", "1X1", "21S"] + out: [4, 2] + - name: "example-three" + in: + board: ["E11", "XXX", "11S"] + out: [0, 0] + - name: "two-by-two-zero" + in: + board: ["E0", "0S"] + out: [0, 3] + - name: "two-by-two-diagonal" + in: + board: ["E1", "1S"] + out: [1, 2] + - name: "two-by-two-blocked" + in: + board: ["EX", "XS"] + out: [0, 1] + - name: "two-by-two-top-route" + in: + board: ["E5", "1S"] + out: [5, 1] + - name: "two-by-two-left-route" + in: + board: ["E1", "5S"] + out: [5, 1] + - name: "three-direct-diagonal" + in: + board: ["E00", "000", "00S"] + out: [0, 13] + - name: "three-all-ones" + in: + board: ["E11", "111", "11S"] + out: [3, 6] + - name: "three-all-nines" + in: + board: ["E99", "999", "99S"] + out: [27, 6] + - name: "three-no-path-row" + in: + board: ["EX1", "XXX", "11S"] + out: [0, 0] + - name: "three-no-path-column" + in: + board: ["E1X", "1XX", "11S"] + out: [3, 1] + - name: "three-central-obstacle" + in: + board: ["E12", "3X4", "56S"] + out: [14, 1] + - name: "three-high-diagonal" + in: + board: ["E99", "9X9", "99S"] + out: [27, 2] + - name: "three-low-corners" + in: + board: ["E01", "0X1", "01S"] + out: [2, 1] + - name: "three-obstacle-corridor" + in: + board: ["E1X", "2XX", "34S"] + out: [9, 1] + - name: "three-left-heavy" + in: + board: ["E90", "9X0", "90S"] + out: [18, 1] + - name: "three-right-heavy" + in: + board: ["E09", "0X9", "09S"] + out: [18, 1] + - name: "four-zero-board" + in: + board: ["E000", "0000", "0000", "000S"] + out: [0, 63] + - name: "four-nine-board" + in: + board: ["E999", "9999", "9999", "999S"] + out: [45, 20] + - name: "four-diagonal-obstacles" + in: + board: ["E123", "4X56", "78X9", "123S"] + out: [24, 1] + - name: "four-blocked-top" + in: + board: ["EXXX", "1XXX", "11XX", "111S"] + out: [5, 2] + - name: "four-blocked-bottom" + in: + board: ["E111", "XX11", "XXX1", "111S"] + out: [5, 2] + - name: "four-single-corridor" + in: + board: ["E1XX", "11XX", "111X", "111S"] + out: [5, 7] + - name: "four-symmetric-tie" + in: + board: ["E111", "1111", "1111", "111S"] + out: [5, 20] + - name: "four-high-center" + in: + board: ["E919", "1991", "9199", "991S"] + out: [45, 1] + - name: "four-low-alternating" + in: + board: ["E101", "0101", "1010", "010S"] + out: [3, 12] + - name: "four-no-path" + in: + board: ["EXXX", "XXXX", "XXXX", "XXXS"] + out: [0, 0] + - name: "five-zero-board" + in: + board: ["E0000", "00000", "00000", "00000", "0000S"] + out: [0, 321] + - name: "five-nine-board" + in: + board: ["E9999", "99999", "99999", "99999", "9999S"] + out: [63, 70] + - name: "five-obstacle-maze" + in: + board: ["E1234", "5X7X9", "12X45", "6X789", "1234S"] + out: [33, 1] + - name: "five-top-wall" + in: + board: ["EXXXX", "11111", "11111", "11111", "1111S"] + out: [7, 35] + - name: "five-dense-ties" + in: + board: ["E1111", "11111", "11111", "11111", "1111S"] + out: [7, 70] + - name: "five-mixed-values" + in: + board: ["E2468", "13579", "24680", "97531", "8642S"] + out: [32, 2] + - name: "stress-ten-zero-ties" + in: + board: + [ + "E000000000", + "0000000000", + "0000000000", + "0000000000", + "0000000000", + "0000000000", + "0000000000", + "0000000000", + "0000000000", + "000000000S", + ] + out: [0, 1462563] + - name: "stress-twenty-nine-score" + in: + board: + [ + "E9999999999999999999", + "99999999999999999999", + "99999999999999999999", + "99999999999999999999", + "99999999999999999999", + "99999999999999999999", + "99999999999999999999", + "99999999999999999999", + "99999999999999999999", + "99999999999999999999", + "99999999999999999999", + "99999999999999999999", + "99999999999999999999", + "99999999999999999999", + "99999999999999999999", + "99999999999999999999", + "99999999999999999999", + "99999999999999999999", + "99999999999999999999", + "9999999999999999999S", + ] + out: [333, 345263555] + - name: "stress-thirty-zero-modulo" + in: + board: + [ + "E00000000000000000000000000000", + "000000000000000000000000000000", + "000000000000000000000000000000", + "000000000000000000000000000000", + "000000000000000000000000000000", + "000000000000000000000000000000", + "000000000000000000000000000000", + "000000000000000000000000000000", + "000000000000000000000000000000", + "000000000000000000000000000000", + "000000000000000000000000000000", + "000000000000000000000000000000", + "000000000000000000000000000000", + "000000000000000000000000000000", + "000000000000000000000000000000", + "000000000000000000000000000000", + "000000000000000000000000000000", + "000000000000000000000000000000", + "000000000000000000000000000000", + "000000000000000000000000000000", + "000000000000000000000000000000", + "000000000000000000000000000000", + "000000000000000000000000000000", + "000000000000000000000000000000", + "000000000000000000000000000000", + "000000000000000000000000000000", + "000000000000000000000000000000", + "000000000000000000000000000000", + "000000000000000000000000000000", + "00000000000000000000000000000S", + ] + out: [0, 857594387] + - name: "stress-hundred-zero-modulo" + in: + board: + - &zero_top "E000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + - &zero_row "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - *zero_row + - "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000S" + out: [0, 888974356] + - name: "stress-hundred-nine-score" + in: + board: + - &nine_top "E999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999" + - &nine_row "9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999" + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - *nine_row + - "999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999S" + out: [1773, 690285631] diff --git a/tests/1001-1500/1301. number-of-paths-with-max-score/sol.cpp b/tests/1001-1500/1301. number-of-paths-with-max-score/sol.cpp new file mode 100644 index 00000000..84b3c890 --- /dev/null +++ b/tests/1001-1500/1301. number-of-paths-with-max-score/sol.cpp @@ -0,0 +1,62 @@ +class Solution { +public: + vector pathsWithMaxScore(vector& board) { + const int MOD = 1'000'000'007; + int n = board.size(); + + vector nextScore(n + 1, -1); + vector nextWays(n + 1, 0); + + for (int i = n - 1; i >= 0; --i) { + vector currScore(n + 1, -1); + vector currWays(n + 1, 0); + + const string& row = board[i]; + for (int j = n - 1; j >= 0; --j) { + char cell = row[j]; + + if (cell == 'X') { + continue; + } + + if (cell == 'S') { + currScore[j] = 0; + currWays[j] = 1; + continue; + } + + int best = max({nextScore[j], currScore[j + 1], nextScore[j + 1]}); + + if (best == -1) { + continue; + } + + int ways = 0; + + if (nextScore[j] == best) { + ways = (ways + nextWays[j]) % MOD; + } + if (currScore[j + 1] == best) { + ways = (ways + currWays[j + 1]) % MOD; + } + if (nextScore[j + 1] == best) { + ways = (ways + nextWays[j + 1]) % MOD; + } + + int value = (cell == 'E') ? 0 : (cell - '0'); + + currScore[j] = best + value; + currWays[j] = ways; + } + + nextScore = std::move(currScore); + nextWays = std::move(currWays); + } + + if (nextScore[0] == -1) { + return {0, 0}; + } + + return {nextScore[0], nextWays[0]}; + } +}; diff --git a/tests/1001-1500/1301. number-of-paths-with-max-score/sol.cs b/tests/1001-1500/1301. number-of-paths-with-max-score/sol.cs new file mode 100644 index 00000000..2dd8a007 --- /dev/null +++ b/tests/1001-1500/1301. number-of-paths-with-max-score/sol.cs @@ -0,0 +1,67 @@ +public class Solution { + public int[] PathsWithMaxScore(IList board) { + const int MOD = 1_000_000_007; + int n = board.Count; + + int[] nextScore = new int[n + 1]; + int[] nextWays = new int[n + 1]; + for (int j = 0; j <= n; j++) { + nextScore[j] = -1; + } + + for (int i = n - 1; i >= 0; i--) { + int[] currScore = new int[n + 1]; + int[] currWays = new int[n + 1]; + for (int j = 0; j <= n; j++) { + currScore[j] = -1; + } + + string row = board[i]; + for (int j = n - 1; j >= 0; j--) { + char cell = row[j]; + + if (cell == 'X') { + continue; + } + + if (cell == 'S') { + currScore[j] = 0; + currWays[j] = 1; + continue; + } + + int best = Math.Max(nextScore[j], Math.Max(currScore[j + 1], nextScore[j + 1])); + + if (best == -1) { + continue; + } + + int ways = 0; + + if (nextScore[j] == best) { + ways = (ways + nextWays[j]) % MOD; + } + if (currScore[j + 1] == best) { + ways = (ways + currWays[j + 1]) % MOD; + } + if (nextScore[j + 1] == best) { + ways = (ways + nextWays[j + 1]) % MOD; + } + + int value = (cell == 'E') ? 0 : (cell - '0'); + + currScore[j] = best + value; + currWays[j] = ways; + } + + nextScore = currScore; + nextWays = currWays; + } + + if (nextScore[0] == -1) { + return new int[] { 0, 0 }; + } + + return new int[] { nextScore[0], nextWays[0] }; + } +} diff --git a/tests/1001-1500/1301. number-of-paths-with-max-score/sol.dart b/tests/1001-1500/1301. number-of-paths-with-max-score/sol.dart new file mode 100644 index 00000000..062c1aba --- /dev/null +++ b/tests/1001-1500/1301. number-of-paths-with-max-score/sol.dart @@ -0,0 +1,64 @@ +class Solution { + List pathsWithMaxScore(List board) { + const int mod = 1000000007; + final int n = board.length; + + List nextScore = List.filled(n + 1, -1); + List nextWays = List.filled(n + 1, 0); + + for (int i = n - 1; i >= 0; i--) { + List currScore = List.filled(n + 1, -1); + List currWays = List.filled(n + 1, 0); + final String row = board[i]; + + for (int j = n - 1; j >= 0; j--) { + final String cell = row[j]; + + if (cell == 'X') { + continue; + } + + if (cell == 'S') { + currScore[j] = 0; + currWays[j] = 1; + continue; + } + + int best = nextScore[j]; + if (currScore[j + 1] > best) { + best = currScore[j + 1]; + } + if (nextScore[j + 1] > best) { + best = nextScore[j + 1]; + } + + if (best == -1) { + continue; + } + + int ways = 0; + if (nextScore[j] == best) { + ways += nextWays[j]; + } + if (currScore[j + 1] == best) { + ways += currWays[j + 1]; + } + if (nextScore[j + 1] == best) { + ways += nextWays[j + 1]; + } + + final int value = cell == 'E' ? 0 : cell.codeUnitAt(0) - 48; + currScore[j] = best + value; + currWays[j] = ways % mod; + } + + nextScore = currScore; + nextWays = currWays; + } + + if (nextScore[0] == -1) { + return [0, 0]; + } + return [nextScore[0], nextWays[0]]; + } +} diff --git a/tests/1001-1500/1301. number-of-paths-with-max-score/sol.go b/tests/1001-1500/1301. number-of-paths-with-max-score/sol.go new file mode 100644 index 00000000..4df14c69 --- /dev/null +++ b/tests/1001-1500/1301. number-of-paths-with-max-score/sol.go @@ -0,0 +1,74 @@ +func pathsWithMaxScore(board []string) []int { + const MOD = 1_000_000_007 + n := len(board) + + nextScore := make([]int, n+1) + nextWays := make([]int, n+1) + for j := 0; j <= n; j++ { + nextScore[j] = -1 + } + + for i := n - 1; i >= 0; i-- { + currScore := make([]int, n+1) + currWays := make([]int, n+1) + for j := 0; j <= n; j++ { + currScore[j] = -1 + } + + row := board[i] + for j := n - 1; j >= 0; j-- { + cell := row[j] + + if cell == 'X' { + continue + } + + if cell == 'S' { + currScore[j] = 0 + currWays[j] = 1 + continue + } + + best := nextScore[j] + if currScore[j+1] > best { + best = currScore[j+1] + } + if nextScore[j+1] > best { + best = nextScore[j+1] + } + + if best == -1 { + continue + } + + ways := 0 + + if nextScore[j] == best { + ways = (ways + nextWays[j]) % MOD + } + if currScore[j+1] == best { + ways = (ways + currWays[j+1]) % MOD + } + if nextScore[j+1] == best { + ways = (ways + nextWays[j+1]) % MOD + } + + value := 0 + if cell != 'E' { + value = int(cell - '0') + } + + currScore[j] = best + value + currWays[j] = ways + } + + nextScore = currScore + nextWays = currWays + } + + if nextScore[0] == -1 { + return []int{0, 0} + } + + return []int{nextScore[0], nextWays[0]} +} diff --git a/tests/1001-1500/1301. number-of-paths-with-max-score/sol.java b/tests/1001-1500/1301. number-of-paths-with-max-score/sol.java new file mode 100644 index 00000000..5756504c --- /dev/null +++ b/tests/1001-1500/1301. number-of-paths-with-max-score/sol.java @@ -0,0 +1,67 @@ +class Solution { + public int[] pathsWithMaxScore(String[] board) { + int MOD = 1_000_000_007; + int n = board.length; + + int[] nextScore = new int[n + 1]; + int[] nextWays = new int[n + 1]; + for (int j = 0; j <= n; j++) { + nextScore[j] = -1; + } + + for (int i = n - 1; i >= 0; i--) { + int[] currScore = new int[n + 1]; + int[] currWays = new int[n + 1]; + for (int j = 0; j <= n; j++) { + currScore[j] = -1; + } + + String row = board[i]; + for (int j = n - 1; j >= 0; j--) { + char cell = row.charAt(j); + + if (cell == 'X') { + continue; + } + + if (cell == 'S') { + currScore[j] = 0; + currWays[j] = 1; + continue; + } + + int best = Math.max(nextScore[j], Math.max(currScore[j + 1], nextScore[j + 1])); + + if (best == -1) { + continue; + } + + int ways = 0; + + if (nextScore[j] == best) { + ways = (ways + nextWays[j]) % MOD; + } + if (currScore[j + 1] == best) { + ways = (ways + currWays[j + 1]) % MOD; + } + if (nextScore[j + 1] == best) { + ways = (ways + nextWays[j + 1]) % MOD; + } + + int value = (cell == 'E') ? 0 : (cell - '0'); + + currScore[j] = best + value; + currWays[j] = ways; + } + + nextScore = currScore; + nextWays = currWays; + } + + if (nextScore[0] == -1) { + return new int[]{0, 0}; + } + + return new int[]{nextScore[0], nextWays[0]}; + } +} diff --git a/tests/1001-1500/1301. number-of-paths-with-max-score/sol.kt b/tests/1001-1500/1301. number-of-paths-with-max-score/sol.kt new file mode 100644 index 00000000..5a0f9277 --- /dev/null +++ b/tests/1001-1500/1301. number-of-paths-with-max-score/sol.kt @@ -0,0 +1,61 @@ +class Solution { + fun pathsWithMaxScore(board: Array): IntArray { + val MOD = 1_000_000_007 + val n = board.size + + var nextScore = IntArray(n + 1) { -1 } + var nextWays = IntArray(n + 1) { 0 } + + for (i in n - 1 downTo 0) { + val currScore = IntArray(n + 1) { -1 } + val currWays = IntArray(n + 1) { 0 } + + val row = board[i] + for (j in n - 1 downTo 0) { + val cell = row[j] + + if (cell == 'X') { + continue + } + + if (cell == 'S') { + currScore[j] = 0 + currWays[j] = 1 + continue + } + + val best = maxOf(nextScore[j], currScore[j + 1], nextScore[j + 1]) + + if (best == -1) { + continue + } + + var ways = 0 + + if (nextScore[j] == best) { + ways = (ways + nextWays[j]) % MOD + } + if (currScore[j + 1] == best) { + ways = (ways + currWays[j + 1]) % MOD + } + if (nextScore[j + 1] == best) { + ways = (ways + nextWays[j + 1]) % MOD + } + + val value = if (cell == 'E') 0 else cell - '0' + + currScore[j] = best + value + currWays[j] = ways + } + + nextScore = currScore + nextWays = currWays + } + + if (nextScore[0] == -1) { + return intArrayOf(0, 0) + } + + return intArrayOf(nextScore[0], nextWays[0]) + } +} diff --git a/tests/1001-1500/1301. number-of-paths-with-max-score/sol.py b/tests/1001-1500/1301. number-of-paths-with-max-score/sol.py new file mode 100644 index 00000000..9a42ce15 --- /dev/null +++ b/tests/1001-1500/1301. number-of-paths-with-max-score/sol.py @@ -0,0 +1,50 @@ +class Solution: + def pathsWithMaxScore(self, board: List[str]) -> List[int]: + MOD = 10**9 + 7 + n = len(board) + + next_score = [-1] * (n + 1) + next_ways = [0] * (n + 1) + + for i in range(n - 1, -1, -1): + # Fresh arrays store the current row. + curr_score = [-1] * (n + 1) + curr_ways = [0] * (n + 1) + + for j in range(n - 1, -1, -1): + cell = board[i][j] + + if cell == "X": + continue + + if cell == "S": + curr_score[j] = 0 + curr_ways[j] = 1 + continue + + best = max(next_score[j], curr_score[j + 1], next_score[j + 1]) + + if best == -1: + continue + + ways = 0 + + if next_score[j] == best: + ways += next_ways[j] + if curr_score[j + 1] == best: + ways += curr_ways[j + 1] + if next_score[j + 1] == best: + ways += next_ways[j + 1] + + value = 0 if cell == "E" else int(cell) + + curr_score[j] = best + value + curr_ways[j] = ways % MOD + + next_score = curr_score + next_ways = curr_ways + + if next_score[0] == -1: + return [0, 0] + + return [next_score[0], next_ways[0]] diff --git a/tests/1001-1500/1301. number-of-paths-with-max-score/sol.py2 b/tests/1001-1500/1301. number-of-paths-with-max-score/sol.py2 new file mode 100644 index 00000000..7492ac74 --- /dev/null +++ b/tests/1001-1500/1301. number-of-paths-with-max-score/sol.py2 @@ -0,0 +1,57 @@ +class Solution(object): + def pathsWithMaxScore(self, board): + """ + :type board: List[str] + :rtype: List[int] + """ + MOD = 10**9 + 7 + n = len(board) + + next_score = [-1] * (n + 1) + next_ways = [0] * (n + 1) + + for i in range(n - 1, -1, -1): + curr_score = [-1] * (n + 1) + curr_ways = [0] * (n + 1) + + for j in range(n - 1, -1, -1): + cell = board[i][j] + + if cell == 'X': + continue + + if cell == 'S': + curr_score[j] = 0 + curr_ways[j] = 1 + continue + + best = max( + next_score[j], + curr_score[j + 1], + next_score[j + 1] + ) + + if best == -1: + continue + + ways = 0 + + if next_score[j] == best: + ways += next_ways[j] + if curr_score[j + 1] == best: + ways += curr_ways[j + 1] + if next_score[j + 1] == best: + ways += next_ways[j + 1] + + value = 0 if cell == 'E' else int(cell) + + curr_score[j] = best + value + curr_ways[j] = ways % MOD + + next_score = curr_score + next_ways = curr_ways + + if next_score[0] == -1: + return [0, 0] + + return [next_score[0], next_ways[0]] diff --git a/tests/1001-1500/1301. number-of-paths-with-max-score/sol.rb b/tests/1001-1500/1301. number-of-paths-with-max-score/sol.rb new file mode 100644 index 00000000..704425ec --- /dev/null +++ b/tests/1001-1500/1301. number-of-paths-with-max-score/sol.rb @@ -0,0 +1,48 @@ +# @param {String[]} board +# @return {Integer[]} +def paths_with_max_score(board) + mod = 10**9 + 7 + n = board.length + + next_score = Array.new(n + 1, -1) + next_ways = Array.new(n + 1, 0) + + (n - 1).downto(0) do |i| + curr_score = Array.new(n + 1, -1) + curr_ways = Array.new(n + 1, 0) + + (n - 1).downto(0) do |j| + cell = board[i][j] + + next if cell == 'X' + + if cell == 'S' + curr_score[j] = 0 + curr_ways[j] = 1 + next + end + + best = [next_score[j], curr_score[j + 1], next_score[j + 1]].max + + next if best == -1 + + ways = 0 + + ways += next_ways[j] if next_score[j] == best + ways += curr_ways[j + 1] if curr_score[j + 1] == best + ways += next_ways[j + 1] if next_score[j + 1] == best + + value = cell == 'E' ? 0 : cell.to_i + + curr_score[j] = best + value + curr_ways[j] = ways % mod + end + + next_score = curr_score + next_ways = curr_ways + end + + return [0, 0] if next_score[0] == -1 + + [next_score[0], next_ways[0]] +end diff --git a/tests/1001-1500/1301. number-of-paths-with-max-score/sol.rs b/tests/1001-1500/1301. number-of-paths-with-max-score/sol.rs new file mode 100644 index 00000000..d165a3b5 --- /dev/null +++ b/tests/1001-1500/1301. number-of-paths-with-max-score/sol.rs @@ -0,0 +1,63 @@ +impl Solution { + pub fn paths_with_max_score(board: Vec) -> Vec { + const MOD: i32 = 1_000_000_007; + let n = board.len(); + + let mut next_score = vec![-1; n + 1]; + let mut next_ways = vec![0; n + 1]; + + let board: Vec> = board.into_iter().map(|s| s.chars().collect()).collect(); + + for i in (0..n).rev() { + let mut curr_score = vec![-1; n + 1]; + let mut curr_ways = vec![0; n + 1]; + + let row = &board[i]; + for j in (0..n).rev() { + let cell = row[j]; + + if cell == 'X' { + continue; + } + + if cell == 'S' { + curr_score[j] = 0; + curr_ways[j] = 1; + continue; + } + + let best = next_score[j].max(curr_score[j + 1]).max(next_score[j + 1]); + + if best == -1 { + continue; + } + + let mut ways = 0; + + if next_score[j] == best { + ways = (ways + next_ways[j]) % MOD; + } + if curr_score[j + 1] == best { + ways = (ways + curr_ways[j + 1]) % MOD; + } + if next_score[j + 1] == best { + ways = (ways + next_ways[j + 1]) % MOD; + } + + let value = if cell == 'E' { 0 } else { cell.to_digit(10).unwrap() as i32 }; + + curr_score[j] = best + value; + curr_ways[j] = ways; + } + + next_score = curr_score; + next_ways = curr_ways; + } + + if next_score[0] == -1 { + return vec![0, 0]; + } + + vec![next_score[0], next_ways[0]] + } +} diff --git a/tests/1001-1500/1301. number-of-paths-with-max-score/sol.swift b/tests/1001-1500/1301. number-of-paths-with-max-score/sol.swift new file mode 100644 index 00000000..db8b98f8 --- /dev/null +++ b/tests/1001-1500/1301. number-of-paths-with-max-score/sol.swift @@ -0,0 +1,63 @@ +class Solution { + func pathsWithMaxScore(_ board: [String]) -> [Int] { + let MOD = 1_000_000_007 + let n = board.count + + var nextScore = [Int](repeating: -1, count: n + 1) + var nextWays = [Int](repeating: 0, count: n + 1) + + let boardChars = board.map { Array($0) } + + for i in stride(from: n - 1, through: 0, by: -1) { + var currScore = [Int](repeating: -1, count: n + 1) + var currWays = [Int](repeating: 0, count: n + 1) + + let row = boardChars[i] + for j in stride(from: n - 1, through: 0, by: -1) { + let cell = row[j] + + if cell == "X" { + continue + } + + if cell == "S" { + currScore[j] = 0 + currWays[j] = 1 + continue + } + + let best = max(nextScore[j], currScore[j + 1], nextScore[j + 1]) + + if best == -1 { + continue + } + + var ways = 0 + + if nextScore[j] == best { + ways = (ways + nextWays[j]) % MOD + } + if currScore[j + 1] == best { + ways = (ways + currWays[j + 1]) % MOD + } + if nextScore[j + 1] == best { + ways = (ways + nextWays[j + 1]) % MOD + } + + let value = (cell == "E") ? 0 : Int(String(cell))! + + currScore[j] = best + value + currWays[j] = ways + } + + nextScore = currScore + nextWays = currWays + } + + if nextScore[0] == -1 { + return [0, 0] + } + + return [nextScore[0], nextWays[0]] + } +} diff --git a/tests/1001-1500/1301. number-of-paths-with-max-score/sol.ts b/tests/1001-1500/1301. number-of-paths-with-max-score/sol.ts new file mode 100644 index 00000000..7522d1bf --- /dev/null +++ b/tests/1001-1500/1301. number-of-paths-with-max-score/sol.ts @@ -0,0 +1,59 @@ +function pathsWithMaxScore(board: string[]): number[] { + const MOD = 1_000_000_007; + const n = board.length; + + let nextScore: number[] = new Array(n + 1).fill(-1); + let nextWays: number[] = new Array(n + 1).fill(0); + + for (let i = n - 1; i >= 0; i--) { + const currScore: number[] = new Array(n + 1).fill(-1); + const currWays: number[] = new Array(n + 1).fill(0); + + const row = board[i]; + for (let j = n - 1; j >= 0; j--) { + const cell = row[j]; + + if (cell === "X") { + continue; + } + + if (cell === "S") { + currScore[j] = 0; + currWays[j] = 1; + continue; + } + + const best = Math.max(nextScore[j], currScore[j + 1], nextScore[j + 1]); + + if (best === -1) { + continue; + } + + let ways = 0; + + if (nextScore[j] === best) { + ways = (ways + nextWays[j]) % MOD; + } + if (currScore[j + 1] === best) { + ways = (ways + currWays[j + 1]) % MOD; + } + if (nextScore[j + 1] === best) { + ways = (ways + nextWays[j + 1]) % MOD; + } + + const value = cell === "E" ? 0 : parseInt(cell); + + currScore[j] = best + value; + currWays[j] = ways; + } + + nextScore = currScore; + nextWays = currWays; + } + + if (nextScore[0] === -1) { + return [0, 0]; + } + + return [nextScore[0], nextWays[0]]; +} diff --git a/tests/1001-1500/1302. deepest-leaves-sum/manifest.yaml b/tests/1001-1500/1302. deepest-leaves-sum/manifest.yaml new file mode 100644 index 00000000..89de7832 --- /dev/null +++ b/tests/1001-1500/1302. deepest-leaves-sum/manifest.yaml @@ -0,0 +1,335 @@ +entry: + id: 1302 + title: deepest-leaves-sum + params: + root: + type: tree_node + call: + cpp: "Solution().deepestLeavesSum({root})" + rust: "Solution::deepest_leaves_sum({root})" + python3: "Solution().deepestLeavesSum({root})" + python2: "Solution().deepestLeavesSum({root})" + ruby: "deepest_leaves_sum({root})" + java: "new Solution().deepestLeavesSum({root})" + csharp: "new Solution().DeepestLeavesSum({root})" + kotlin: "Solution().deepestLeavesSum({root})" + go: "deepestLeavesSum({root})" + dart: "Solution().deepestLeavesSum({root})" + swift: "Solution().deepestLeavesSum({root})" + typescript: "deepestLeavesSum({root})" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().deepestLeavesSum(root, {result})" + checker: | + class Checker: + def deepestLeavesSum(self, root, result): + if type(result) is not int: + return False + deepest_depth = -1 + deepest_sum = 0 + stack = [(root, 0)] + while stack: + node, depth = stack.pop() + if node.left is None and node.right is None: + if depth > deepest_depth: + deepest_depth = depth + deepest_sum = node.val + elif depth == deepest_depth: + deepest_sum += node.val + else: + if node.left is not None: + stack.append((node.left, depth + 1)) + if node.right is not None: + stack.append((node.right, depth + 1)) + return result == deepest_sum +seed: 1302 +tests: + - name: example_one + in: + root: [1, 2, 3, 4, 5, null, 6, 7, null, null, null, null, 8] + out: 15 + - name: example_two + in: + root: [6, 7, 8, 2, 7, 1, 3, 9, null, 1, 4, null, null, null, 5] + out: 19 + - name: single_minimum_value + in: + root: [1] + out: 1 + - name: single_maximum_value + in: + root: [100] + out: 100 + - name: two_leaf_children + in: + root: [10, 20, 30] + out: 50 + - name: left_chain + in: + root: [10, 20, null, 30, null, 40] + out: 40 + - name: right_chain + in: + root: [10, null, 20, null, 30, null, 40] + out: 40 + - name: zigzag_chain + in: + root: [1, 2, null, null, 3, 4] + out: 4 + - name: shallow_leaf_ignored_for_deeper_leaf + in: + root: [1, 2, 3, 4] + out: 4 + - name: shallow_maximum_leaf_ignored_for_deep_right_leaf + in: + root: [1, 100, 2, null, null, 3] + out: 3 + - name: complete_three_levels + in: + root: [1, 2, 3, 4, 5, 6, 7] + out: 22 + - name: complete_four_levels + in: + root: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] + out: 92 + - name: deepest_pair_on_left + in: + root: [5, 8, 2, 11, 13] + out: 24 + - name: deepest_pair_across_subtrees + in: + root: [5, 8, 2, 11, null, null, 13] + out: 24 + - name: unequal_leaf_depths + in: + root: [9, 4, 12, 2, null, 10, 18, null, 3] + out: 3 + - name: deepest_leaves_under_one_parent + in: + root: [9, 4, 12, null, 7, null, null, 15, 16] + out: 31 + - name: sparse_left_then_right + in: + root: [8, 3, null, null, 5, 9] + out: 9 + - name: sparse_right_then_left + in: + root: [8, null, 3, 5, null, 9] + out: 9 + - name: duplicate_deepest_values + in: + root: [7, 7, 7, 7, 7, 7, 7] + out: 28 + - name: all_maximum_values + in: + root: [100, 100, 100, 100, 100, 100, 100] + out: 400 + - name: left_branch_deeper_than_right + in: + root: [20, 10, 30, 5, 15, null, null, 1, null, null, 2] + out: 3 + - name: right_branch_deeper_than_left + in: + root: [20, 10, 30, null, null, 25, 35, null, 28, null, 40] + out: 68 + - name: internal_node_at_last_complete_level + in: + root: [4, 2, 8, 1, 3, 6, 9, null, null, null, null, 5] + out: 5 + - name: multiple_deepest_leaves_with_gaps + in: + root: [4, 2, 8, 1, null, 6, 9, null, 3, 5, null, null, 10] + out: 18 + - name: leftmost_deep_leaf + in: + root: [50, 40, 60, 30, null, null, null, 20, null, 10] + out: 10 + - name: rightmost_deep_leaf + in: + root: [50, 40, 60, null, null, null, 70, null, 80, null, 90] + out: 90 + - name: uneven_three_deepest_leaves + in: + root: [1, 2, 3, 4, 5, 6, null, 7, null, null, 8, null, 9] + out: 24 + - name: full_level_values_one_to_thirty_one + in: + root: + [ + 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: 376 + - name: full_level_values_one_to_sixty_three + in: + root: + [ + 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, + ] + out: 1520 + - name: wide_last_level_with_maximum_values + in: + root: [1, 1, 1, 1, 1, 1, 1, 100, 100, 100, 100, 100, 100, 100, 100] + out: 800 + - name: sparse_broad_tree + in: + root: [10, 20, 30, 40, null, 50, 60, null, 70, null, null, 80, null, 90] + out: 90 + - name: deep_left_subtree_two_leaves + in: + root: [10, 20, 30, 40, null, null, null, 50, 60] + out: 110 + - name: deep_right_subtree_two_leaves + in: + root: [10, 20, 30, null, null, 40, null, 50, 60] + out: 110 + - name: leaf_at_every_earlier_level + in: + root: [1, 2, 3, 4, null, null, null, 5] + out: 5 + - name: alternating_sparse_branches + in: + root: [11, 22, 33, null, 44, 55, null, 66, null, null, 77] + out: 143 + - name: maximum_sum_two_deepest_leaves + in: + root: [100, 99, 98, 97, null, null, 96, 100, 100] + out: 200 + - name: balanced_with_one_extended_leaf + in: + root: + [15, 10, 20, 5, 12, 18, 25, null, null, 11, null, null, null, null, 30] + out: 41 + - name: dense_then_sparse_final_level + in: + root: [3, 6, 9, 12, 15, 18, 21, null, 24, 27, null, null, 30, null, 33] + out: 114 + - name: four_deepest_leaves_sparse + in: + root: [1, 2, 3, 4, 5, 6, 7, 8, null, 9, null, null, 10, null, 11] + out: 38 + - name: deep_mixed_branching + in: + root: + [ + 25, + 15, + 35, + 10, + 20, + 30, + 40, + null, + 12, + 18, + null, + null, + 32, + null, + 45, + 11, + 14, + 17, + 19, + 31, + 33, + 44, + 46, + ] + out: 215 diff --git a/tests/1001-1500/1302. deepest-leaves-sum/sol.cpp b/tests/1001-1500/1302. deepest-leaves-sum/sol.cpp new file mode 100644 index 00000000..f3d4213d --- /dev/null +++ b/tests/1001-1500/1302. deepest-leaves-sum/sol.cpp @@ -0,0 +1,33 @@ +/** + * 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: + int deepestLeavesSum(TreeNode* root) { + unordered_map depthMap; + dfs(root, 0, depthMap); + int maxDepth = 0; + for (const auto& pair : depthMap) { + maxDepth = max(maxDepth, pair.first); + } + return depthMap[maxDepth]; + } + +private: + void dfs(TreeNode* node, int depth, unordered_map& depthMap) { + if (!node) return; + if (!node->left && !node->right) { + depthMap[depth] += node->val; + } + dfs(node->left, depth + 1, depthMap); + dfs(node->right, depth + 1, depthMap); + } +}; diff --git a/tests/1001-1500/1302. deepest-leaves-sum/sol.cs b/tests/1001-1500/1302. deepest-leaves-sum/sol.cs new file mode 100644 index 00000000..8f342fe3 --- /dev/null +++ b/tests/1001-1500/1302. deepest-leaves-sum/sol.cs @@ -0,0 +1,37 @@ +/** + * 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 DeepestLeavesSum(TreeNode root) { + Dictionary depthMap = new Dictionary(); + DFS(root, 0, depthMap); + int maxDepth = 0; + foreach (int depth in depthMap.Keys) { + if (depth > maxDepth) maxDepth = depth; + } + return depthMap[maxDepth]; + } + + private void DFS(TreeNode node, int depth, Dictionary depthMap) { + if (node == null) return; + if (node.left == null && node.right == null) { + if (depthMap.ContainsKey(depth)) { + depthMap[depth] += node.val; + } else { + depthMap[depth] = node.val; + } + } + DFS(node.left, depth + 1, depthMap); + DFS(node.right, depth + 1, depthMap); + } +} diff --git a/tests/1001-1500/1302. deepest-leaves-sum/sol.dart b/tests/1001-1500/1302. deepest-leaves-sum/sol.dart new file mode 100644 index 00000000..9958f806 --- /dev/null +++ b/tests/1001-1500/1302. deepest-leaves-sum/sol.dart @@ -0,0 +1,28 @@ +/** + * 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 deepestLeavesSum(TreeNode? root) { + final depthMap = {}; + + void dfs(TreeNode? node, int depth) { + if (node == null) return; + if (node.left == null && node.right == null) { + depthMap[depth] = (depthMap[depth] ?? 0) + node.val; + } + dfs(node.left, depth + 1); + dfs(node.right, depth + 1); + } + + dfs(root, 0); + + int maxDepth = depthMap.keys.reduce((a, b) => a > b ? a : b); + return depthMap[maxDepth] ?? 0; + } +} diff --git a/tests/1001-1500/1302. deepest-leaves-sum/sol.go b/tests/1001-1500/1302. deepest-leaves-sum/sol.go new file mode 100644 index 00000000..0b364323 --- /dev/null +++ b/tests/1001-1500/1302. deepest-leaves-sum/sol.go @@ -0,0 +1,34 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func deepestLeavesSum(root *TreeNode) int { + depthMap := make(map[int]int) + + var dfs func(*TreeNode, int) + dfs = func(node *TreeNode, depth int) { + if node == nil { + return + } + if node.Left == nil && node.Right == nil { + depthMap[depth] += node.Val + } + dfs(node.Left, depth+1) + dfs(node.Right, depth+1) + } + + dfs(root, 0) + + maxDepth := 0 + for depth := range depthMap { + if depth > maxDepth { + maxDepth = depth + } + } + + return depthMap[maxDepth] +} diff --git a/tests/1001-1500/1302. deepest-leaves-sum/sol.java b/tests/1001-1500/1302. deepest-leaves-sum/sol.java new file mode 100644 index 00000000..65d80eca --- /dev/null +++ b/tests/1001-1500/1302. deepest-leaves-sum/sol.java @@ -0,0 +1,32 @@ +/** + * 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 deepestLeavesSum(TreeNode root) { + Map depthMap = new HashMap<>(); + dfs(root, 0, depthMap); + int maxDepth = Collections.max(depthMap.keySet()); + return depthMap.get(maxDepth); + } + + private void dfs(TreeNode node, int depth, Map depthMap) { + if (node == null) return; + if (node.left == null && node.right == null) { + depthMap.put(depth, depthMap.getOrDefault(depth, 0) + node.val); + } + dfs(node.left, depth + 1, depthMap); + dfs(node.right, depth + 1, depthMap); + } +} diff --git a/tests/1001-1500/1302. deepest-leaves-sum/sol.kt b/tests/1001-1500/1302. deepest-leaves-sum/sol.kt new file mode 100644 index 00000000..6b41d5fa --- /dev/null +++ b/tests/1001-1500/1302. deepest-leaves-sum/sol.kt @@ -0,0 +1,28 @@ +/** + * 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 deepestLeavesSum(root: TreeNode?): Int { + val depthMap = mutableMapOf() + + fun dfs(node: TreeNode?, depth: Int) { + if (node == null) return + if (node.left == null && node.right == null) { + depthMap[depth] = depthMap.getOrDefault(depth, 0) + node.`val` + } + dfs(node.left, depth + 1) + dfs(node.right, depth + 1) + } + + dfs(root, 0) + val maxDepth = depthMap.keys.maxOrNull() ?: 0 + return depthMap[maxDepth] ?: 0 + } +} diff --git a/tests/1001-1500/1302. deepest-leaves-sum/sol.py b/tests/1001-1500/1302. deepest-leaves-sum/sol.py new file mode 100644 index 00000000..30064c37 --- /dev/null +++ b/tests/1001-1500/1302. deepest-leaves-sum/sol.py @@ -0,0 +1,31 @@ +import collections +from typing import Optional + + +# 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 deepestLeavesSum(self, root: Optional[TreeNode]) -> int: + + leaves = collections.Counter() + + def dfs(node, depth): + + if not node: + return + + if not node.left and not node.right: + leaves[depth] += node.val + + dfs(node.left, depth + 1) + dfs(node.right, depth + 1) + + dfs(root, 0) + + max_depth = max(leaves.keys()) + + return leaves[max_depth] diff --git a/tests/1001-1500/1302. deepest-leaves-sum/sol.py2 b/tests/1001-1500/1302. deepest-leaves-sum/sol.py2 new file mode 100644 index 00000000..aa52fd9d --- /dev/null +++ b/tests/1001-1500/1302. deepest-leaves-sum/sol.py2 @@ -0,0 +1,26 @@ +# 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 deepestLeavesSum(self, root): + """ + :type root: Optional[TreeNode] + :rtype: int + """ + from collections import defaultdict + depth_map = defaultdict(int) + + def dfs(node, depth): + if not node: + return + if not node.left and not node.right: + depth_map[depth] += node.val + dfs(node.left, depth + 1) + dfs(node.right, depth + 1) + + dfs(root, 0) + max_depth = max(depth_map.keys()) + return depth_map[max_depth] diff --git a/tests/1001-1500/1302. deepest-leaves-sum/sol.rb b/tests/1001-1500/1302. deepest-leaves-sum/sol.rb new file mode 100644 index 00000000..689d9a8e --- /dev/null +++ b/tests/1001-1500/1302. deepest-leaves-sum/sol.rb @@ -0,0 +1,27 @@ +# 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 {Integer} +def deepest_leaves_sum(root) + depth_map = Hash.new(0) + + dfs = lambda do |node, depth| + return unless node + if node.left.nil? && node.right.nil? + depth_map[depth] += node.val + end + dfs.call(node.left, depth + 1) + dfs.call(node.right, depth + 1) + end + + dfs.call(root, 0) + max_depth = depth_map.keys.max + depth_map[max_depth] +end diff --git a/tests/1001-1500/1302. deepest-leaves-sum/sol.rs b/tests/1001-1500/1302. deepest-leaves-sum/sol.rs new file mode 100644 index 00000000..f92a620b --- /dev/null +++ b/tests/1001-1500/1302. deepest-leaves-sum/sol.rs @@ -0,0 +1,39 @@ +// 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 deepest_leaves_sum(root: Option>>) -> i32 { + let mut depth_map: HashMap = HashMap::new(); + + fn dfs(node: Option<&Rc>>, depth: i32, depth_map: &mut HashMap) { + if let Some(n) = node { + let n = n.borrow(); + if n.left.is_none() && n.right.is_none() { + *depth_map.entry(depth).or_insert(0) += n.val; + } + dfs(n.left.as_ref(), depth + 1, depth_map); + dfs(n.right.as_ref(), depth + 1, depth_map); + } + } + + dfs(root.as_ref(), 0, &mut depth_map); + + let max_depth = depth_map.keys().max().copied().unwrap_or(0); + *depth_map.get(&max_depth).unwrap_or(&0) + } +} diff --git a/tests/1001-1500/1302. deepest-leaves-sum/sol.swift b/tests/1001-1500/1302. deepest-leaves-sum/sol.swift new file mode 100644 index 00000000..ea314ae0 --- /dev/null +++ b/tests/1001-1500/1302. deepest-leaves-sum/sol.swift @@ -0,0 +1,33 @@ +/** + * 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 deepestLeavesSum(_ root: TreeNode?) -> Int { + var depthMap: [Int: Int] = [:] + + func dfs(_ node: TreeNode?, _ depth: Int) { + guard let node = node else { return } + if node.left == nil && node.right == nil { + depthMap[depth, default: 0] += node.val + } + dfs(node.left, depth + 1) + dfs(node.right, depth + 1) + } + + dfs(root, 0) + let maxDepth = depthMap.keys.max() ?? 0 + return depthMap[maxDepth] ?? 0 + } +} diff --git a/tests/1001-1500/1302. deepest-leaves-sum/sol.ts b/tests/1001-1500/1302. deepest-leaves-sum/sol.ts new file mode 100644 index 00000000..cbfc93f8 --- /dev/null +++ b/tests/1001-1500/1302. deepest-leaves-sum/sol.ts @@ -0,0 +1,35 @@ +/** + * 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 deepestLeavesSum(root: TreeNode | null): number { + const depthMap: Map = new Map(); + + function dfs(node: TreeNode | null, depth: number): void { + if (node === null) return; + if (node.left === null && node.right === null) { + depthMap.set(depth, (depthMap.get(depth) || 0) + node.val); + } + dfs(node.left, depth + 1); + dfs(node.right, depth + 1); + } + + dfs(root, 0); + + let maxDepth = 0; + for (const depth of depthMap.keys()) { + if (depth > maxDepth) maxDepth = depth; + } + + return depthMap.get(maxDepth) || 0; +} diff --git a/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/manifest.yaml b/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/manifest.yaml new file mode 100644 index 00000000..40a75632 --- /dev/null +++ b/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/manifest.yaml @@ -0,0 +1,181 @@ +entry: + id: 1304 + title: "find-n-unique-integers-sum-up-to-zero" + params: + n: + type: int + call: + cpp: "Solution().sumZero({n})" + rust: "Solution::sum_zero({n})" + python3: "Solution().sumZero({n})" + python2: "Solution().sumZero({n})" + ruby: "sum_zero({n})" + java: "new Solution().sumZero({n})" + csharp: "new Solution().SumZero({n})" + kotlin: "Solution().sumZero({n})" + go: "sumZero({n})" + dart: "Solution().sumZero({n})" + swift: "Solution().sumZero({n})" + typescript: "sumZero({n})" +judge: + type: "exact" +limits: + time_ms: 300 + memory_mb: 300 +oracle: + python3: + call: "Checker().sumZero(n, {result})" + checker: | + class Checker: + def sumZero(self, n, result): + if not isinstance(result, list) or len(result) != n: + return False + if any(isinstance(value, bool) or not isinstance(value, int) for value in result): + return False + return len(set(result)) == n and sum(result) == 0 +seed: 1304 +tests: + - name: "minimum_singleton" + in: + n: 1 + - name: "smallest_even" + in: + n: 2 + - name: "smallest_odd" + in: + n: 3 + - name: "even_four" + in: + n: 4 + - name: "example_five" + in: + n: 5 + - name: "even_six" + in: + n: 6 + - name: "odd_seven" + in: + n: 7 + - name: "power_of_two_eight" + in: + n: 8 + - name: "odd_nine" + in: + n: 9 + - name: "two_digits_even" + in: + n: 10 + - name: "two_digits_odd" + in: + n: 11 + - name: "dozen" + in: + n: 12 + - name: "mid_teens_odd" + in: + n: 15 + - name: "power_of_two_sixteen" + in: + n: 16 + - name: "mid_teens_odd_successor" + in: + n: 17 + - name: "score" + in: + n: 20 + - name: "quarter_century" + in: + n: 25 + - name: "thirty" + in: + n: 30 + - name: "power_boundary_minus_one" + in: + n: 31 + - name: "power_of_two_thirty_two" + in: + n: 32 + - name: "half_century" + in: + n: 50 + - name: "power_of_two_sixty_four" + in: + n: 64 + - name: "century_minus_one" + in: + n: 99 + - name: "century" + in: + n: 100 + - name: "power_boundary_127" + in: + n: 127 + - name: "power_of_two_128" + in: + n: 128 + - name: "power_boundary_129" + in: + n: 129 + - name: "two_hundred" + in: + n: 200 + - name: "power_boundary_255" + in: + n: 255 + - name: "power_of_two_256" + in: + n: 256 + - name: "power_boundary_257" + in: + n: 257 + - name: "half_maximum" + in: + n: 500 + - name: "maximum_minus_one" + in: + n: 999 + - name: "maximum" + in: + n: 1000 + - name: "generated_small_range" + seed: 13041 + in: + n: + gen: "int" + min: 1 + max: 20 + - name: "generated_low_middle_range" + seed: 13042 + in: + n: + gen: "int" + min: 21 + max: 150 + - name: "generated_middle_range" + seed: 13043 + in: + n: + gen: "int" + min: 151 + max: 500 + - name: "generated_upper_middle_range" + seed: 13044 + in: + n: + gen: "int" + min: 501 + max: 800 + - name: "generated_high_range" + seed: 13045 + in: + n: + gen: "int" + min: 801 + max: 999 + - name: "generated_full_constraint_range" + seed: 13046 + in: + n: + gen: "int" + min: 1 + max: 1000 diff --git a/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.cpp b/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.cpp new file mode 100644 index 00000000..679c725b --- /dev/null +++ b/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + vector sumZero(int n) { + vector result(n); + for (int i = 0; i < n; i++) { + result[i] = i * 2 - n + 1; + } + return result; + } +}; diff --git a/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.cs b/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.cs new file mode 100644 index 00000000..5e35a441 --- /dev/null +++ b/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.cs @@ -0,0 +1,9 @@ +public class Solution { + public int[] SumZero(int n) { + int[] result = new int[n]; + for (int i = 0; i < n; i++) { + result[i] = i * 2 - n + 1; + } + return result; + } +} diff --git a/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.dart b/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.dart new file mode 100644 index 00000000..57bbc074 --- /dev/null +++ b/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.dart @@ -0,0 +1,5 @@ +class Solution { + List sumZero(int n) { + return List.generate(n, (i) => i * 2 - n + 1); + } +} diff --git a/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.go b/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.go new file mode 100644 index 00000000..613753d3 --- /dev/null +++ b/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.go @@ -0,0 +1,7 @@ +func sumZero(n int) []int { + result := make([]int, n) + for i := 0; i < n; i++ { + result[i] = i * 2 - n + 1 + } + return result +} diff --git a/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.java b/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.java new file mode 100644 index 00000000..ec5b3e45 --- /dev/null +++ b/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.java @@ -0,0 +1,9 @@ +class Solution { + public int[] sumZero(int n) { + int[] result = new int[n]; + for (int i = 0; i < n; i++) { + result[i] = i * 2 - n + 1; + } + return result; + } +} diff --git a/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.kt b/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.kt new file mode 100644 index 00000000..155865ee --- /dev/null +++ b/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.kt @@ -0,0 +1,5 @@ +class Solution { + fun sumZero(n: Int): IntArray { + return IntArray(n) { i -> i * 2 - n + 1 } + } +} diff --git a/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.py b/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.py new file mode 100644 index 00000000..1afc08dd --- /dev/null +++ b/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.py @@ -0,0 +1,3 @@ +class Solution: + def sumZero(self, n: int) -> List[int]: + return [i * 2 - n + 1 for i in range(n)] diff --git a/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.py2 b/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.py2 new file mode 100644 index 00000000..d563a1a6 --- /dev/null +++ b/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.py2 @@ -0,0 +1,7 @@ +class Solution(object): + def sumZero(self, n): + """ + :type n: int + :rtype: List[int] + """ + return [i * 2 - n + 1 for i in range(n)] diff --git a/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.rb b/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.rb new file mode 100644 index 00000000..459bee7d --- /dev/null +++ b/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.rb @@ -0,0 +1,5 @@ +# @param {Integer} n +# @return {Integer[]} +def sum_zero(n) + Array.new(n) { |i| i * 2 - n + 1 } +end diff --git a/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.rs b/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.rs new file mode 100644 index 00000000..30e3e4ee --- /dev/null +++ b/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.rs @@ -0,0 +1,5 @@ +impl Solution { + pub fn sum_zero(n: i32) -> Vec { + (0..n).map(|i| i * 2 - n + 1).collect() + } +} diff --git a/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.swift b/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.swift new file mode 100644 index 00000000..6f11b227 --- /dev/null +++ b/tests/1001-1500/1304. find-n-unique-integers-sum-up-to-zero/sol.swift @@ -0,0 +1,5 @@ +class Solution { + func sumZero(_ n: Int) -> [Int] { + return (0.. i * 2 - n + 1); +} diff --git a/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/manifest.yaml b/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/manifest.yaml new file mode 100644 index 00000000..d4f7f849 --- /dev/null +++ b/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/manifest.yaml @@ -0,0 +1,416 @@ +entry: + id: 1305 + title: "all-elements-in-two-binary-search-trees" + params: + root1: + type: tree_node + root2: + type: tree_node + call: + cpp: "Solution().getAllElements({root1}, {root2})" + rust: "Solution::get_all_elements({root1}, {root2})" + python3: "Solution().getAllElements({root1}, {root2})" + python2: "Solution().getAllElements({root1}, {root2})" + ruby: "get_all_elements({root1}, {root2})" + java: "new Solution().getAllElements({root1}, {root2})" + csharp: "new Solution().GetAllElements({root1}, {root2})" + kotlin: "Solution().getAllElements({root1}, {root2})" + go: "getAllElements({root1}, {root2})" + dart: "Solution().getAllElements({root1}, {root2})" + swift: "Solution().getAllElements({root1}, {root2})" + typescript: "getAllElements({root1}, {root2})" + +judge: + type: "exact" + +limits: + time_ms: 700 + memory_mb: 300 + +oracle: + python3: + call: "Checker().getAllElements(root1, root2, {result})" + checker: | + class Checker: + def getAllElements(self, root1, root2, result): + if not isinstance(result, list) or any(not isinstance(value, int) for value in result): + return False + def inorder(values): + if not values: + return [] + nodes = [[values[0], None, None]] + queue = [0] + cursor = 1 + for parent in queue: + if cursor == len(values): + break + left = values[cursor] + cursor += 1 + if left is not None: + nodes.append([left, None, None]) + nodes[parent][1] = len(nodes) - 1 + queue.append(len(nodes) - 1) + if cursor == len(values): + break + right = values[cursor] + cursor += 1 + if right is not None: + nodes.append([right, None, None]) + nodes[parent][2] = len(nodes) - 1 + queue.append(len(nodes) - 1) + def visit(index): + if index is None: + return [] + return visit(nodes[index][1]) + [nodes[index][0]] + visit(nodes[index][2]) + return visit(0) + return result == sorted(inorder(root1) + inorder(root2)) + +seed: 130500 + +tests: + - name: "example_one" + in: + root1: [2, 1, 4] + root2: [1, 0, 3] + out: [0, 1, 1, 2, 3, 4] + - name: "example_two" + in: + root1: [1, null, 8] + root2: [8, 1] + out: [1, 1, 8, 8] + - name: "both_empty" + in: + root1: [] + root2: [] + out: [] + - name: "left_empty" + in: + root1: [] + root2: [5] + out: [5] + - name: "right_empty" + in: + root1: [5] + root2: [] + out: [5] + - name: "two_singletons" + in: + root1: [1] + root2: [2] + out: [1, 2] + - name: "duplicate_singletons" + in: + root1: [1] + root2: [1] + out: [1, 1] + - name: "negative_values" + in: + root1: [-2, -3, -1] + root2: [0, null, 2] + out: [-3, -2, -1, 0, 2] + - name: "balanced_overlapping" + in: + root1: [4, 2, 6, 1, 3, 5, 7] + root2: [8, 6, 10, 5, 7, 9, 11] + out: [1, 2, 3, 4, 5, 5, 6, 6, 7, 7, 8, 9, 10, 11] + - name: "left_skewed" + in: + root1: [4, 3, null, 2, null, 1] + root2: [8, 7, null, 6, null, 5] + out: [1, 2, 3, 4, 5, 6, 7, 8] + - name: "right_skewed" + in: + root1: [1, null, 2, null, 3, null, 4] + root2: [5, null, 6, null, 7] + out: [1, 2, 3, 4, 5, 6, 7] + - name: "identical_trees" + in: + root1: [2, 1, 3] + root2: [2, 1, 3] + out: [1, 1, 2, 2, 3, 3] + - name: "all_negative" + in: + root1: [-5, -8, -2] + root2: [-4, -7, -1] + out: [-8, -7, -5, -4, -2, -1] + - name: "mixed_sign" + in: + root1: [0, -5, 5, -8, -2, 2, 8] + root2: [1, -3, 4] + out: [-8, -5, -3, -2, 0, 1, 2, 4, 5, 8] + - name: "duplicate_nodes" + in: + root1: [3, 2, 4, 1, 2] + root2: [3, 2, 4, 1, 2] + out: [1, 1, 2, 2, 2, 2, 3, 3, 4, 4] + - name: "nested_ranges" + in: + root1: [10, 5, 15, 2, 7, 12, 20] + root2: [11, 6, 16, 1, 8, 13, 21] + out: [1, 2, 5, 6, 7, 8, 10, 11, 12, 13, 15, 16, 20, 21] + - name: "alternating_chains" + in: + root1: [1, null, 3, null, 5] + root2: [2, null, 4, null, 6] + out: [1, 2, 3, 4, 5, 6] + - name: "extreme_separated" + in: + root1: [-100000, null, -99999] + root2: [99999, null, 100000] + out: [-100000, -99999, 99999, 100000] + - name: "first_unbalanced" + in: + root1: [8, 4, 12, 2, 6, null, 14, 1] + root2: [3, 1, 5] + out: [1, 1, 2, 3, 4, 5, 6, 8, 12, 14] + - name: "second_unbalanced" + in: + root1: [0] + root2: [8, 4, 12, 2, 6, 10, 14, null, 3] + out: [0, 2, 3, 4, 6, 8, 10, 12, 14] + - name: "repeated_boundaries" + in: + root1: [0, -1, 1] + root2: [0, -1, 1] + out: [-1, -1, 0, 0, 1, 1] + - name: "negative_duplicates" + in: + root1: [-1, -2, 0] + root2: [-1, -3, 1] + out: [-3, -2, -1, -1, 0, 1] + - name: "ten_nodes_total" + in: + root1: [5, 2, 8, 1, 3, 7, 9] + root2: [4, 0, 6] + out: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + - name: "dense_values" + in: + root1: [6, 3, 9, 2, 4, 8, 10, 1, null, null, 5] + root2: [7, 3, 11, 2, 5, 9, 12] + out: [1, 2, 2, 3, 3, 4, 5, 5, 6, 7, 8, 9, 9, 10, 11, 12] + - name: "alternating_signs" + in: + root1: [0, -4, 4, -6, -2, 2, 6] + root2: [1, -3, 5, -5, -1, 3, 7] + out: [-6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7] + - name: "large_balanced" + in: + root1: [16, 8, 24, 4, 12, 20, 28, 2, 6, 10, 14, 18, 22, 26, 30] + root2: [15, 7, 23, 3, 11, 19, 27, 1, 5, 9, 13, 17, 21, 25, 29] + 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, + ] + - name: "extreme_values" + in: + root1: [0, -100000, 100000] + root2: [-1, -99999, 99999] + out: [-100000, -99999, -1, 0, 99999, 100000] + - name: "overlapping_duplicates" + in: + root1: [4, 2, 6, 2, 3, 5, 6] + root2: [4, 2, 6, 1, 3, 5, 7] + out: [1, 2, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 6, 7] + - name: "long_right_chains" + in: + root1: [1, null, 2, null, 3, null, 4, null, 5, null, 6] + root2: [0, null, 2, null, 4, null, 6, null, 8] + out: [0, 1, 2, 2, 3, 4, 4, 5, 6, 6, 8] + - name: "long_left_chains" + in: + root1: [6, 5, null, 4, null, 3, null, 2, null, 1] + root2: [8, 7, null, 6, null, 5] + out: [1, 2, 3, 4, 5, 5, 6, 6, 7, 8] + - name: "one_tree_contains_other_range" + in: + root1: [50, 25, 75, 10, 30, 60, 90] + root2: [50, 40, 55, 35, 45, 52, 58] + out: [10, 25, 30, 35, 40, 45, 50, 50, 52, 55, 58, 60, 75, 90] + - name: "asymmetric_null_children" + in: + root1: [7, 3, 9, null, 5, 8, null, 4, 6] + root2: [10, 2, 12, 1, null, 11, 13] + out: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] + - name: "root_values_interleave" + in: + root1: [30, 10, 50, 5, 20, 40, 60] + root2: [35, 15, 55, 12, 25, 45, 65] + out: [5, 10, 12, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65] + - name: "deep_left_against_deep_right" + in: + root1: [0, -1, null, -2, null, -3, null, -4, null, -5] + root2: [1, null, 2, null, 3, null, 4, null, 5] + out: [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5] + - name: "duplicate_minimum_and_maximum" + in: + root1: [0, -100000, 100000] + root2: [0, -100000, 100000] + out: [-100000, -100000, 0, 0, 100000, 100000] + - name: "complete_thirty_one_nodes" + in: + root1: + [ + 16, + 8, + 24, + 4, + 12, + 20, + 28, + 2, + 6, + 10, + 14, + 18, + 22, + 26, + 30, + 1, + 3, + 5, + 7, + 9, + 11, + 13, + 15, + 17, + 19, + 21, + 23, + 25, + 27, + 29, + 31, + ] + root2: [] + 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, + ] + - name: "two_complete_fifteen_node_trees" + in: + root1: [15, 7, 23, 3, 11, 19, 27, 1, 5, 9, 13, 17, 21, 25, 29] + root2: [16, 8, 24, 4, 12, 20, 28, 2, 6, 10, 14, 18, 22, 26, 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, + ] + - name: "large_value_spread" + in: + root1: [0, -50000, 50000, -75000, -25000, 25000, 75000] + root2: [-1, -99999, 99999, null, -50001, 1, null, null, -2, null, 50001] + out: + [ + -99999, + -75000, + -50001, + -50000, + -25000, + -2, + -1, + 0, + 1, + 25000, + 50000, + 50001, + 75000, + 99999, + ] + - name: "disjoint_negative_positive_complete" + in: + root1: [-4, -6, -2, -7, -5, -3, -1] + root2: [4, 2, 6, 1, 3, 5, 7] + out: [-7, -6, -5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6, 7] + - name: "sparse_internal_frontier" + in: + root1: [20, 10, 30, null, 15, 25, null, 12, 17] + root2: [18, 9, 27, 4, null, 22, 29] + out: [4, 9, 10, 12, 15, 17, 18, 20, 22, 25, 27, 29, 30] diff --git a/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.cpp b/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.cpp new file mode 100644 index 00000000..1bb97c70 --- /dev/null +++ b/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.cpp @@ -0,0 +1,55 @@ +/** + * 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: + vector getAllElements(TreeNode* root1, TreeNode* root2) { + vector stack1, stack2; + vector output; + + while (root1 || root2 || !stack1.empty() || !stack2.empty()) { + while (root1) { + stack1.push_back(root1); + root1 = root1->left; + } + while (root2) { + stack2.push_back(root2); + root2 = root2->left; + } + + if (!stack1.empty() && !stack2.empty()) { + if (stack1.back()->val <= stack2.back()->val) { + root1 = stack1.back(); + stack1.pop_back(); + output.push_back(root1->val); + root1 = root1->right; + } else { + root2 = stack2.back(); + stack2.pop_back(); + output.push_back(root2->val); + root2 = root2->right; + } + } else if (stack1.empty()) { + root2 = stack2.back(); + stack2.pop_back(); + output.push_back(root2->val); + root2 = root2->right; + } else { + root1 = stack1.back(); + stack1.pop_back(); + output.push_back(root1->val); + root1 = root1->right; + } + } + + return output; + } +}; diff --git a/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.cs b/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.cs new file mode 100644 index 00000000..33faf8b6 --- /dev/null +++ b/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.cs @@ -0,0 +1,53 @@ +/** + * 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 IList GetAllElements(TreeNode root1, TreeNode root2) { + Stack stack1 = new Stack(); + Stack stack2 = new Stack(); + List output = new List(); + + while (root1 != null || root2 != null || stack1.Count > 0 || stack2.Count > 0) { + while (root1 != null) { + stack1.Push(root1); + root1 = root1.left; + } + while (root2 != null) { + stack2.Push(root2); + root2 = root2.left; + } + + if (stack1.Count > 0 && stack2.Count > 0) { + if (stack1.Peek().val <= stack2.Peek().val) { + root1 = stack1.Pop(); + output.Add(root1.val); + root1 = root1.right; + } else { + root2 = stack2.Pop(); + output.Add(root2.val); + root2 = root2.right; + } + } else if (stack1.Count == 0) { + root2 = stack2.Pop(); + output.Add(root2.val); + root2 = root2.right; + } else { + root1 = stack1.Pop(); + output.Add(root1.val); + root1 = root1.right; + } + } + + return output; + } +} diff --git a/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.dart b/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.dart new file mode 100644 index 00000000..ccb900ba --- /dev/null +++ b/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.dart @@ -0,0 +1,49 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * int val; + * TreeNode? left; + * TreeNode? right; + * TreeNode([this.val = 0, this.left, this.right]); + * } + */ +class Solution { + List getAllElements(TreeNode? root1, TreeNode? root2) { + List stack1 = []; + List stack2 = []; + List output = []; + + while (root1 != null || root2 != null || stack1.isNotEmpty || stack2.isNotEmpty) { + while (root1 != null) { + stack1.add(root1); + root1 = root1.left; + } + while (root2 != null) { + stack2.add(root2); + root2 = root2.left; + } + + if (stack1.isNotEmpty && stack2.isNotEmpty) { + if (stack1.last.val <= stack2.last.val) { + root1 = stack1.removeLast(); + output.add(root1.val); + root1 = root1.right; + } else { + root2 = stack2.removeLast(); + output.add(root2.val); + root2 = root2.right; + } + } else if (stack1.isEmpty) { + root2 = stack2.removeLast(); + output.add(root2.val); + root2 = root2.right; + } else { + root1 = stack1.removeLast(); + output.add(root1.val); + root1 = root1.right; + } + } + + return output; + } +} diff --git a/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.go b/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.go new file mode 100644 index 00000000..1789a54f --- /dev/null +++ b/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.go @@ -0,0 +1,50 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func getAllElements(root1 *TreeNode, root2 *TreeNode) []int { + stack1 := []*TreeNode{} + stack2 := []*TreeNode{} + output := []int{} + + for root1 != nil || root2 != nil || len(stack1) > 0 || len(stack2) > 0 { + for root1 != nil { + stack1 = append(stack1, root1) + root1 = root1.Left + } + for root2 != nil { + stack2 = append(stack2, root2) + root2 = root2.Left + } + + if len(stack1) > 0 && len(stack2) > 0 { + if stack1[len(stack1)-1].Val <= stack2[len(stack2)-1].Val { + root1 = stack1[len(stack1)-1] + stack1 = stack1[:len(stack1)-1] + output = append(output, root1.Val) + root1 = root1.Right + } else { + root2 = stack2[len(stack2)-1] + stack2 = stack2[:len(stack2)-1] + output = append(output, root2.Val) + root2 = root2.Right + } + } else if len(stack1) == 0 { + root2 = stack2[len(stack2)-1] + stack2 = stack2[:len(stack2)-1] + output = append(output, root2.Val) + root2 = root2.Right + } else { + root1 = stack1[len(stack1)-1] + stack1 = stack1[:len(stack1)-1] + output = append(output, root1.Val) + root1 = root1.Right + } + } + + return output +} diff --git a/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.java b/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.java new file mode 100644 index 00000000..3f5ea4d9 --- /dev/null +++ b/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.java @@ -0,0 +1,55 @@ +/** + * 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 List getAllElements(TreeNode root1, TreeNode root2) { + Deque stack1 = new ArrayDeque<>(); + Deque stack2 = new ArrayDeque<>(); + List output = new ArrayList<>(); + + while (root1 != null || root2 != null || !stack1.isEmpty() || !stack2.isEmpty()) { + while (root1 != null) { + stack1.push(root1); + root1 = root1.left; + } + while (root2 != null) { + stack2.push(root2); + root2 = root2.left; + } + + if (!stack1.isEmpty() && !stack2.isEmpty()) { + if (stack1.peek().val <= stack2.peek().val) { + root1 = stack1.pop(); + output.add(root1.val); + root1 = root1.right; + } else { + root2 = stack2.pop(); + output.add(root2.val); + root2 = root2.right; + } + } else if (stack1.isEmpty()) { + root2 = stack2.pop(); + output.add(root2.val); + root2 = root2.right; + } else { + root1 = stack1.pop(); + output.add(root1.val); + root1 = root1.right; + } + } + + return output; + } +} diff --git a/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.kt b/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.kt new file mode 100644 index 00000000..58b38930 --- /dev/null +++ b/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.kt @@ -0,0 +1,52 @@ +/** + * 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 getAllElements(root1: TreeNode?, root2: TreeNode?): List { + val stack1 = ArrayDeque() + val stack2 = ArrayDeque() + val output = mutableListOf() + var r1 = root1 + var r2 = root2 + + while (r1 != null || r2 != null || stack1.isNotEmpty() || stack2.isNotEmpty()) { + while (r1 != null) { + stack1.addLast(r1) + r1 = r1.left + } + while (r2 != null) { + stack2.addLast(r2) + r2 = r2.left + } + + if (stack1.isNotEmpty() && stack2.isNotEmpty()) { + if (stack1.last().`val` <= stack2.last().`val`) { + r1 = stack1.removeLast() + output.add(r1.`val`) + r1 = r1.right + } else { + r2 = stack2.removeLast() + output.add(r2.`val`) + r2 = r2.right + } + } else if (stack1.isEmpty()) { + r2 = stack2.removeLast() + output.add(r2.`val`) + r2 = r2.right + } else { + r1 = stack1.removeLast() + output.add(r1.`val`) + r1 = r1.right + } + } + + return output + } +} diff --git a/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.py b/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.py new file mode 100644 index 00000000..782244d8 --- /dev/null +++ b/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.py @@ -0,0 +1,45 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + + +class Solution: + def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]: + stack1, stack2, output = [], [], [] + + while root1 or root2 or stack1 or stack2: + # update both stacks + # by going left till possible + while root1: + stack1.append(root1) + root1 = root1.left + while root2: + stack2.append(root2) + root2 = root2.left + + # Add the smallest value into output, + # pop it from the stack, + # and then do one step right + if stack2 and stack1: + if stack1[-1].val <= stack2[-1].val: + root1 = stack1.pop() + output.append(root1.val) + root1 = root1.right + else: + root2 = stack2.pop() + output.append(root2.val) + root2 = root2.right + + elif not stack1: + root2 = stack2.pop() + output.append(root2.val) + root2 = root2.right + else: + root1 = stack1.pop() + output.append(root1.val) + root1 = root1.right + + return output diff --git a/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.py2 b/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.py2 new file mode 100644 index 00000000..0f6309ed --- /dev/null +++ b/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.py2 @@ -0,0 +1,42 @@ +# 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 getAllElements(self, root1, root2): + """ + :type root1: Optional[TreeNode] + :type root2: Optional[TreeNode] + :rtype: List[int] + """ + stack1, stack2, output = [], [], [] + + while root1 or root2 or stack1 or stack2: + while root1: + stack1.append(root1) + root1 = root1.left + while root2: + stack2.append(root2) + root2 = root2.left + + if stack2 and stack1: + if stack1[-1].val <= stack2[-1].val: + root1 = stack1.pop() + output.append(root1.val) + root1 = root1.right + else: + root2 = stack2.pop() + output.append(root2.val) + root2 = root2.right + elif not stack1: + root2 = stack2.pop() + output.append(root2.val) + root2 = root2.right + else: + root1 = stack1.pop() + output.append(root1.val) + root1 = root1.right + + return output diff --git a/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.rb b/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.rb new file mode 100644 index 00000000..ce70e9a9 --- /dev/null +++ b/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.rb @@ -0,0 +1,48 @@ +# 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} root1 +# @param {TreeNode} root2 +# @return {Integer[]} +def get_all_elements(root1, root2) + stack1, stack2, output = [], [], [] + + while root1 || root2 || !stack1.empty? || !stack2.empty? + while root1 + stack1.push(root1) + root1 = root1.left + end + while root2 + stack2.push(root2) + root2 = root2.left + end + + if !stack1.empty? && !stack2.empty? + if stack1[-1].val <= stack2[-1].val + root1 = stack1.pop() + output.push(root1.val) + root1 = root1.right + else + root2 = stack2.pop() + output.push(root2.val) + root2 = root2.right + end + elsif stack1.empty? + root2 = stack2.pop() + output.push(root2.val) + root2 = root2.right + else + root1 = stack1.pop() + output.push(root1.val) + root1 = root1.right + end + end + + output +end diff --git a/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.rs b/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.rs new file mode 100644 index 00000000..5c66b16b --- /dev/null +++ b/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.rs @@ -0,0 +1,60 @@ +// 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 get_all_elements(root1: Option>>, root2: Option>>) -> Vec { + let mut stack1: Vec>> = Vec::new(); + let mut stack2: Vec>> = Vec::new(); + let mut output: Vec = Vec::new(); + let mut r1 = root1.clone(); + let mut r2 = root2.clone(); + + while r1.is_some() || r2.is_some() || !stack1.is_empty() || !stack2.is_empty() { + while let Some(node) = r1 { + r1 = node.borrow().left.clone(); + stack1.push(node); + } + while let Some(node) = r2 { + r2 = node.borrow().left.clone(); + stack2.push(node); + } + + if !stack1.is_empty() && !stack2.is_empty() { + if stack1.last().unwrap().borrow().val <= stack2.last().unwrap().borrow().val { + r1 = stack1.pop(); + output.push(r1.as_ref().unwrap().borrow().val); + r1 = r1.unwrap().borrow().right.clone(); + } else { + r2 = stack2.pop(); + output.push(r2.as_ref().unwrap().borrow().val); + r2 = r2.unwrap().borrow().right.clone(); + } + } else if stack1.is_empty() { + r2 = stack2.pop(); + output.push(r2.as_ref().unwrap().borrow().val); + r2 = r2.unwrap().borrow().right.clone(); + } else { + r1 = stack1.pop(); + output.push(r1.as_ref().unwrap().borrow().val); + r1 = r1.unwrap().borrow().right.clone(); + } + } + + output + } +} diff --git a/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.swift b/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.swift new file mode 100644 index 00000000..699841a3 --- /dev/null +++ b/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.swift @@ -0,0 +1,57 @@ +/** + * 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 getAllElements(_ root1: TreeNode?, _ root2: TreeNode?) -> [Int] { + var stack1: [TreeNode] = [] + var stack2: [TreeNode] = [] + var output: [Int] = [] + var r1 = root1 + var r2 = root2 + + while r1 != nil || r2 != nil || !stack1.isEmpty || !stack2.isEmpty { + while let node = r1 { + stack1.append(node) + r1 = node.left + } + while let node = r2 { + stack2.append(node) + r2 = node.left + } + + if !stack1.isEmpty && !stack2.isEmpty { + if stack1.last!.val <= stack2.last!.val { + r1 = stack1.removeLast() + output.append(r1!.val) + r1 = r1!.right + } else { + r2 = stack2.removeLast() + output.append(r2!.val) + r2 = r2!.right + } + } else if stack1.isEmpty { + r2 = stack2.removeLast() + output.append(r2!.val) + r2 = r2!.right + } else { + r1 = stack1.removeLast() + output.append(r1!.val) + r1 = r1!.right + } + } + + return output + } +} diff --git a/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.ts b/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.ts new file mode 100644 index 00000000..dd51e67c --- /dev/null +++ b/tests/1001-1500/1305. all-elements-in-two-binary-search-trees/sol.ts @@ -0,0 +1,60 @@ +/** + * 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 getAllElements( + root1: TreeNode | null, + root2: TreeNode | null, +): number[] { + const stack1: TreeNode[] = []; + const stack2: TreeNode[] = []; + const output: number[] = []; + + while ( + root1 !== null || + root2 !== null || + stack1.length > 0 || + stack2.length > 0 + ) { + while (root1 !== null) { + stack1.push(root1); + root1 = root1.left; + } + while (root2 !== null) { + stack2.push(root2); + root2 = root2.left; + } + + if (stack1.length > 0 && stack2.length > 0) { + if (stack1[stack1.length - 1].val <= stack2[stack2.length - 1].val) { + root1 = stack1.pop()!; + output.push(root1.val); + root1 = root1.right; + } else { + root2 = stack2.pop()!; + output.push(root2.val); + root2 = root2.right; + } + } else if (stack1.length === 0) { + root2 = stack2.pop()!; + output.push(root2.val); + root2 = root2.right; + } else { + root1 = stack1.pop()!; + output.push(root1.val); + root1 = root1.right; + } + } + + return output; +} diff --git a/tests/1001-1500/1306. jump-game-iii/manifest.yaml b/tests/1001-1500/1306. jump-game-iii/manifest.yaml new file mode 100644 index 00000000..ce32ffa0 --- /dev/null +++ b/tests/1001-1500/1306. jump-game-iii/manifest.yaml @@ -0,0 +1,316 @@ +entry: + id: 1306 + title: "jump-game-iii" + params: + arr: + type: array + items: + type: int + start_value: + type: int + call: + cpp: "Solution().canReach({arr}, {start_value})" + rust: "Solution::can_reach({arr}, {start_value})" + python3: "Solution().canReach({arr}, {start_value})" + python2: "Solution().canReach({arr}, {start_value})" + ruby: "can_reach({arr}, {start_value})" + java: "new Solution().canReach({arr}, {start_value})" + csharp: "new Solution().CanReach({arr}, {start_value})" + kotlin: "Solution().canReach({arr}, {start_value})" + go: "canReach({arr}, {start_value})" + dart: "Solution().canReach({arr}, {start_value})" + swift: "Solution().canReach({arr}, {start_value})" + typescript: "canReach({arr}, {start_value})" + +judge: + type: "exact" + +limits: + time_ms: 2500 + memory_mb: 256 + +oracle: + python3: + call: "Checker().canReach(arr, start_value, {result})" + checker: | + from collections import deque + + class Checker: + def canReach(self, arr, start_value, result): + if not isinstance(result, bool): + return False + queue = deque([start_value]) + seen = {start_value} + while queue: + index = queue.popleft() + if arr[index] == 0: + return result is True + for next_index in (index + arr[index], index - arr[index]): + if 0 <= next_index < len(arr) and next_index not in seen: + seen.add(next_index) + queue.append(next_index) + return result is False + +seed: 1306 + +tests: + - name: "example-one" + in: + arr: [4, 2, 3, 0, 3, 1, 2] + start_value: 5 + out: true + - name: "example-two" + in: + arr: [4, 2, 3, 0, 3, 1, 2] + start_value: 0 + out: true + - name: "example-three" + in: + arr: [3, 0, 2, 1, 2] + start_value: 2 + out: false + - name: "singleton-zero" + in: + arr: [0] + start_value: 0 + out: true + - name: "start-already-zero" + in: + arr: [0, 2, 2] + start_value: 0 + out: true + - name: "direct-forward-jump" + in: + arr: [3, 1, 1, 0] + start_value: 0 + out: true + - name: "direct-backward-jump" + in: + arr: [0, 1, 1, 3] + start_value: 3 + out: true + - name: "three-node-cycle-without-zero" + in: + arr: [1, 1, 1] + start_value: 0 + out: false + - name: "two-node-bounce-without-zero" + in: + arr: [1, 1] + start_value: 0 + out: false + - name: "cycle-with-an-exit" + in: + arr: [2, 1, 1, 0] + start_value: 1 + out: true + - name: "backward-chain-to-zero" + in: + arr: [0, 1, 1, 1, 4] + start_value: 4 + out: true + - name: "parity-component-cannot-reach-zero" + in: + arr: [2, 2, 0, 2, 2, 2] + start_value: 3 + out: false + - name: "parity-component-reaches-zero" + in: + arr: [1, 1, 1, 0, 1, 1] + start_value: 5 + out: true + - name: "long-boundary-jump-to-zero" + in: + arr: [5, 1, 1, 1, 1, 0] + start_value: 0 + out: true + - name: "long-boundary-jump-without-zero" + in: + arr: [5, 1, 1, 1, 1, 1] + start_value: 0 + out: false + - name: "multiple-zeros" + in: + arr: [0, 2, 0, 1, 2] + start_value: 4 + out: true + - name: "start-near-right-boundary" + in: + arr: [2, 2, 2, 0, 1, 1, 1] + start_value: 6 + out: true + - name: "endpoint-cycle-without-zero" + in: + arr: [6, 1, 1, 1, 1, 1, 1] + start_value: 0 + out: false + - name: "forced-negative-direction-route" + in: + arr: [0, 1, 1, 2, 1, 4] + start_value: 5 + out: true + - name: "out-of-bounds-branches-only" + in: + arr: [2, 2, 2, 0] + start_value: 0 + out: false + - name: "branching-route-to-zero" + in: + arr: [3, 1, 2, 2, 0, 1] + start_value: 0 + out: true + - name: "unreachable-zero-in-other-component" + in: + arr: [2, 2, 0, 2, 2, 2, 2] + start_value: 5 + out: false + - name: "maximum-legal-first-jump" + in: + arr: [5, 4, 3, 2, 1, 0] + start_value: 0 + out: true + - name: "large-jump-cycle-misses-zero" + in: + arr: [4, 1, 1, 1, 4, 0] + start_value: 0 + out: false + - name: "mixed-jump-route-from-end" + in: + arr: [2, 3, 1, 2, 0, 3, 1] + start_value: 6 + out: true + - name: "mixed-jump-dead-component" + in: + arr: [3, 2, 1, 2, 0, 2, 4] + start_value: 6 + out: false + - name: "backward-zero-after-long-jump" + in: + arr: [1, 2, 1, 2, 0, 4, 1, 3] + start_value: 7 + out: true + - name: "cycle-blocks-nearby-zero" + in: + arr: [1, 2, 1, 2, 0, 4, 1, 3] + start_value: 1 + out: false + - name: "jump-over-intermediate-values" + in: + arr: [2, 1, 3, 1, 2, 0, 2, 1] + start_value: 2 + out: true + - name: "right-edge-route-to-zero" + in: + arr: [2, 1, 3, 1, 2, 0, 2, 1] + start_value: 7 + out: true + - name: "two-element-zero-reached-forward" + in: + arr: [1, 0] + start_value: 0 + out: true + - name: "middle-start-reaches-right-zero" + in: + arr: [2, 1, 0] + start_value: 1 + out: true + - name: "left-start-skips-to-zero" + in: + arr: [2, 1, 0] + start_value: 0 + out: true + - name: "odd-cycle-misses-terminal-zero" + in: + arr: [2, 2, 1, 2, 0] + start_value: 1 + out: false + - name: "generated-small-valid-domain" + seed: 13061 + in: + arr: + gen: "array" + len: 64 + of: + gen: "int" + min: 0 + max: 63 + elemType: "int" + start_value: + gen: "int" + min: 0 + max: 63 + - name: "generated-medium-valid-domain" + seed: 13062 + in: + arr: + gen: "array" + len: 512 + of: + gen: "int" + min: 0 + max: 511 + elemType: "int" + start_value: + gen: "int" + min: 0 + max: 511 + - name: "generated-large-random-reachability" + seed: 13063 + in: + arr: + gen: "array" + len: 10000 + of: + gen: "int" + min: 0 + max: 9999 + elemType: "int" + start_value: + gen: "int" + min: 0 + max: 9999 + - name: "generated-near-maximum-random" + seed: 13064 + in: + arr: + gen: "array" + len: 50000 + of: + gen: "int" + min: 0 + max: 49999 + elemType: "int" + start_value: + gen: "int" + min: 0 + max: 49999 + - name: "generated-near-maximum-without-zero" + seed: 13065 + in: + arr: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 49999 + elemType: "int" + start_value: + gen: "int" + min: 0 + max: 49999 + - name: "generated-large-zero-heavy" + seed: 13066 + in: + arr: + gen: "array" + len: 25000 + of: + gen: "int" + min: 0 + max: 3 + elemType: "int" + start_value: + gen: "int" + min: 0 + max: 24999 diff --git a/tests/1001-1500/1306. jump-game-iii/sol.cpp b/tests/1001-1500/1306. jump-game-iii/sol.cpp new file mode 100644 index 00000000..719b8c87 --- /dev/null +++ b/tests/1001-1500/1306. jump-game-iii/sol.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + bool canReach(vector& arr, int start) { + unordered_set seen; + queue q; + q.push(start); + while (!q.empty()) { + int index = q.front(); + q.pop(); + if (index < 0 || index >= arr.size() || seen.count(index)) { + continue; + } + if (arr[index] == 0) { + return true; + } + seen.insert(index); + q.push(index + arr[index]); + q.push(index - arr[index]); + } + return false; + } +}; diff --git a/tests/1001-1500/1306. jump-game-iii/sol.cs b/tests/1001-1500/1306. jump-game-iii/sol.cs new file mode 100644 index 00000000..c8a4ec07 --- /dev/null +++ b/tests/1001-1500/1306. jump-game-iii/sol.cs @@ -0,0 +1,20 @@ +public class Solution { + public bool CanReach(int[] arr, int start) { + var seen = new HashSet(); + var queue = new Queue(); + queue.Enqueue(start); + while (queue.Count > 0) { + int index = queue.Dequeue(); + if (index < 0 || index >= arr.Length || seen.Contains(index)) { + continue; + } + if (arr[index] == 0) { + return true; + } + seen.Add(index); + queue.Enqueue(index + arr[index]); + queue.Enqueue(index - arr[index]); + } + return false; + } +} diff --git a/tests/1001-1500/1306. jump-game-iii/sol.dart b/tests/1001-1500/1306. jump-game-iii/sol.dart new file mode 100644 index 00000000..8fca84f8 --- /dev/null +++ b/tests/1001-1500/1306. jump-game-iii/sol.dart @@ -0,0 +1,21 @@ +class Solution { + bool canReach(List arr, int start) { + var seen = {}; + var queue = [start]; + var head = 0; + while (head < queue.length) { + var index = queue[head]; + head++; + if (index < 0 || index >= arr.length || seen.contains(index)) { + continue; + } + if (arr[index] == 0) { + return true; + } + seen.add(index); + queue.add(index + arr[index]); + queue.add(index - arr[index]); + } + return false; + } +} diff --git a/tests/1001-1500/1306. jump-game-iii/sol.go b/tests/1001-1500/1306. jump-game-iii/sol.go new file mode 100644 index 00000000..90fd0124 --- /dev/null +++ b/tests/1001-1500/1306. jump-game-iii/sol.go @@ -0,0 +1,19 @@ +func canReach(arr []int, start int) bool { + seen := make(map[int]bool) + queue := []int{start} + head := 0 + for head < len(queue) { + index := queue[head] + head++ + if index < 0 || index >= len(arr) || seen[index] { + continue + } + if arr[index] == 0 { + return true + } + seen[index] = true + queue = append(queue, index+arr[index]) + queue = append(queue, index-arr[index]) + } + return false +} diff --git a/tests/1001-1500/1306. jump-game-iii/sol.java b/tests/1001-1500/1306. jump-game-iii/sol.java new file mode 100644 index 00000000..161d9434 --- /dev/null +++ b/tests/1001-1500/1306. jump-game-iii/sol.java @@ -0,0 +1,20 @@ +class Solution { + public boolean canReach(int[] arr, int start) { + java.util.Set seen = new java.util.HashSet<>(); + java.util.Queue queue = new java.util.LinkedList<>(); + queue.offer(start); + while (!queue.isEmpty()) { + int index = queue.poll(); + if (index < 0 || index >= arr.length || seen.contains(index)) { + continue; + } + if (arr[index] == 0) { + return true; + } + seen.add(index); + queue.offer(index + arr[index]); + queue.offer(index - arr[index]); + } + return false; + } +} diff --git a/tests/1001-1500/1306. jump-game-iii/sol.kt b/tests/1001-1500/1306. jump-game-iii/sol.kt new file mode 100644 index 00000000..0ef3eb6d --- /dev/null +++ b/tests/1001-1500/1306. jump-game-iii/sol.kt @@ -0,0 +1,20 @@ +class Solution { + fun canReach(arr: IntArray, start: Int): Boolean { + val seen = mutableSetOf() + val queue = ArrayDeque() + queue.add(start) + while (queue.isNotEmpty()) { + val index = queue.removeFirst() + if (index < 0 || index >= arr.size || index in seen) { + continue + } + if (arr[index] == 0) { + return true + } + seen.add(index) + queue.add(index + arr[index]) + queue.add(index - arr[index]) + } + return false + } +} diff --git a/tests/1001-1500/1306. jump-game-iii/sol.py b/tests/1001-1500/1306. jump-game-iii/sol.py new file mode 100644 index 00000000..de4e72b4 --- /dev/null +++ b/tests/1001-1500/1306. jump-game-iii/sol.py @@ -0,0 +1,16 @@ +class Solution: + def canReach(self, arr, start): + seen = set() + queue = [start] + head = 0 + while head < len(queue): + index = queue[head] + head += 1 + if index < 0 or index >= len(arr) or index in seen: + continue + if arr[index] == 0: + return True + seen.add(index) + queue.append(index + arr[index]) + queue.append(index - arr[index]) + return False diff --git a/tests/1001-1500/1306. jump-game-iii/sol.py2 b/tests/1001-1500/1306. jump-game-iii/sol.py2 new file mode 100644 index 00000000..fd74caa8 --- /dev/null +++ b/tests/1001-1500/1306. jump-game-iii/sol.py2 @@ -0,0 +1,21 @@ +class Solution(object): + def canReach(self, arr, start): + """ + :type arr: List[int] + :type start: int + :rtype: bool + """ + seen = set() + queue = [start] + head = 0 + while head < len(queue): + index = queue[head] + head += 1 + if index < 0 or index >= len(arr) or index in seen: + continue + if arr[index] == 0: + return True + seen.add(index) + queue.append(index + arr[index]) + queue.append(index - arr[index]) + return False diff --git a/tests/1001-1500/1306. jump-game-iii/sol.rb b/tests/1001-1500/1306. jump-game-iii/sol.rb new file mode 100644 index 00000000..4638447e --- /dev/null +++ b/tests/1001-1500/1306. jump-game-iii/sol.rb @@ -0,0 +1,22 @@ +# @param {Integer[]} arr +# @param {Integer} start +# @return {Boolean} +def can_reach(arr, start) + seen = Set.new + queue = [start] + head = 0 + while head < queue.length + index = queue[head] + head += 1 + if index < 0 or index >= arr.length or seen.include?(index) + next + end + if arr[index] == 0 + return true + end + seen.add(index) + queue.push(index + arr[index]) + queue.push(index - arr[index]) + end + return false +end diff --git a/tests/1001-1500/1306. jump-game-iii/sol.rs b/tests/1001-1500/1306. jump-game-iii/sol.rs new file mode 100644 index 00000000..58ce7a6b --- /dev/null +++ b/tests/1001-1500/1306. jump-game-iii/sol.rs @@ -0,0 +1,25 @@ +impl Solution { + pub fn can_reach(arr: Vec, start: i32) -> bool { + use std::collections::{HashSet, VecDeque}; + let mut seen = HashSet::new(); + let mut queue = VecDeque::new(); + queue.push_back(start as usize); + while let Some(index) = queue.pop_front() { + if index >= arr.len() || seen.contains(&index) { + continue; + } + if arr[index] == 0 { + return true; + } + seen.insert(index); + let val = arr[index] as usize; + if index >= val { + queue.push_back(index - val); + } + if index + val < arr.len() { + queue.push_back(index + val); + } + } + false + } +} diff --git a/tests/1001-1500/1306. jump-game-iii/sol.swift b/tests/1001-1500/1306. jump-game-iii/sol.swift new file mode 100644 index 00000000..9a4e85b2 --- /dev/null +++ b/tests/1001-1500/1306. jump-game-iii/sol.swift @@ -0,0 +1,21 @@ +class Solution { + func canReach(_ arr: [Int], _ start: Int) -> Bool { + var seen = Set() + var queue = [start] + var head = 0 + while head < queue.count { + let index = queue[head] + head += 1 + if index < 0 || index >= arr.count || seen.contains(index) { + continue + } + if arr[index] == 0 { + return true + } + seen.insert(index) + queue.append(index + arr[index]) + queue.append(index - arr[index]) + } + return false + } +} diff --git a/tests/1001-1500/1306. jump-game-iii/sol.ts b/tests/1001-1500/1306. jump-game-iii/sol.ts new file mode 100644 index 00000000..085fbd9e --- /dev/null +++ b/tests/1001-1500/1306. jump-game-iii/sol.ts @@ -0,0 +1,19 @@ +function canReach(arr: number[], start: number): boolean { + const seen = new Set(); + const queue: number[] = [start]; + let head = 0; + while (head < queue.length) { + const index = queue[head]; + head++; + if (index < 0 || index >= arr.length || seen.has(index)) { + continue; + } + if (arr[index] === 0) { + return true; + } + seen.add(index); + queue.push(index + arr[index]); + queue.push(index - arr[index]); + } + return false; +} diff --git a/tests/1001-1500/1307. verbal-arithmetic-puzzle/manifest.yaml b/tests/1001-1500/1307. verbal-arithmetic-puzzle/manifest.yaml new file mode 100644 index 00000000..f65d57cd --- /dev/null +++ b/tests/1001-1500/1307. verbal-arithmetic-puzzle/manifest.yaml @@ -0,0 +1,295 @@ +entry: + id: 1307 + title: "verbal-arithmetic-puzzle" + params: + words: + type: array + items: + type: string + result: + type: string + call: + cpp: "Solution().isSolvable({words}, {result})" + rust: "Solution::is_solvable({words}, {result})" + python3: "Solution().isSolvable({words}, {result})" + python2: "Solution().isSolvable({words}, {result})" + ruby: "is_solvable({words}, {result})" + java: "new Solution().isSolvable({words}, {result})" + csharp: "new Solution().IsSolvable({words}, {result})" + kotlin: "Solution().isSolvable({words}, {result})" + go: "isSolvable({words}, {result})" + dart: "Solution().isSolvable({words}, {result})" + swift: "Solution().isSolvable({words}, {result})" + typescript: "isSolvable({words}, {result})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 300 + +oracle: + python3: + call: "Checker().isSolvable(words, result, {result})" + checker: | + class Checker: + def isSolvable(self, words, result, answer): + if type(answer) is not bool: + return False + letters = set(''.join(words) + result) + if len(letters) > 10: + return False + if max(map(len, words)) > len(result): + return answer is False + leading = {word[0] for word in words + [result] if len(word) > 1} + assigned = {} + used = set() + width = max(len(result), max(map(len, words))) + + def solve_column(column, carry): + if column == width: + return carry == 0 + + def add_word(index, total): + if index == len(words): + digit = total % 10 + next_carry = total // 10 + letter = result[-1 - column] if column < len(result) else None + if letter is None: + return digit == 0 and solve_column(column + 1, next_carry) + if letter in assigned: + return assigned[letter] == digit and solve_column(column + 1, next_carry) + if digit in used or (digit == 0 and letter in leading): + return False + assigned[letter] = digit + used.add(digit) + found = solve_column(column + 1, next_carry) + used.remove(digit) + del assigned[letter] + return found + + word = words[index] + if column >= len(word): + return add_word(index + 1, total) + letter = word[-1 - column] + if letter in assigned: + return add_word(index + 1, total + assigned[letter]) + for digit in range(10): + if digit in used or (digit == 0 and letter in leading): + continue + assigned[letter] = digit + used.add(digit) + if add_word(index + 1, total + digit): + return True + used.remove(digit) + del assigned[letter] + return False + + return add_word(0, carry) + + return solve_column(0, 0) is answer + +seed: 1307 + +tests: + - name: "example_send_more_money" + in: + words: ["SEND", "MORE"] + result: "MONEY" + out: true + - name: "example_six_seven_twenty" + in: + words: ["SIX", "SEVEN", "SEVEN"] + result: "TWENTY" + out: true + - name: "example_leet_code_point" + in: + words: ["LEET", "CODE"] + result: "POINT" + out: false + - name: "single_digit_double" + in: + words: ["A", "A"] + result: "B" + out: true + - name: "single_digit_distinct_sum" + in: + words: ["A", "B"] + result: "C" + out: true + - name: "single_digit_add_zero" + in: + words: ["A", "B"] + result: "A" + out: true + - name: "result_cannot_lead_zero" + in: + words: ["A", "B"] + result: "BA" + out: false + - name: "word_longer_than_result" + in: + words: ["AB", "C"] + result: "A" + out: false + - name: "two_digit_no_carry" + in: + words: ["AB", "C"] + result: "AD" + out: true + - name: "two_digit_distinct_addends" + in: + words: ["BC", "DE"] + result: "FG" + out: true + - name: "repeated_digit_words" + in: + words: ["AA", "BB"] + result: "CC" + out: true + - name: "mirrored_addition" + in: + words: ["AB", "BA"] + result: "CC" + out: true + - name: "mirrored_requires_equal_letters" + in: + words: ["AB", "BA"] + result: "CD" + out: false + - name: "doubled_two_digit_word" + in: + words: ["AB", "AB"] + result: "CD" + out: true + - name: "triple_single_digit" + in: + words: ["B", "B", "B"] + result: "D" + out: true + - name: "five_addends_single_digit" + in: + words: ["B", "B", "B", "B", "B"] + result: "E" + out: true + - name: "four_addends_with_carry" + in: + words: ["A", "A", "A", "A"] + result: "B" + out: true + - name: "all_zero_single_letter" + in: + words: ["A", "A", "A"] + result: "A" + out: true + - name: "two_leading_words_cannot_cancel" + in: + words: ["AA", "BB"] + result: "AA" + out: false + - name: "result_prefix_cannot_disappear" + in: + words: ["AA", "B"] + result: "AB" + out: false + - name: "nine_distinct_letters" + in: + words: ["BCD", "EFG"] + result: "FHI" + out: true + - name: "two_column_carry" + in: + words: ["BII", "BII"] + result: "DGH" + out: true + - name: "seven_digit_repeated_addends" + in: + words: ["BBBBBBB", "CCCCCCC"] + result: "EEEEEEE" + out: true + - name: "five_seven_digit_addends" + in: + words: ["BBBBBBB", "BBBBBBB", "BBBBBBB", "BBBBBBB", "BBBBBBB"] + result: "EEEEEEE" + out: true + - name: "seven_digit_full_carry" + in: + words: ["IIIIII", "BBBBBC"] + result: "JAAAAAA" + out: true + - name: "internal_zero" + in: + words: ["BAC", "BDB"] + result: "CED" + out: true + - name: "this_is_too_funny" + in: + words: ["THIS", "IS", "TOO"] + result: "FUNNY" + out: true + - name: "result_two_digits_too_long" + in: + words: ["ABC", "DEF"] + result: "GHIJK" + out: false + - name: "left_addend_must_be_zero" + in: + words: ["A", "B"] + result: "B" + out: true + - name: "single_zero_addend_with_long_word" + in: + words: ["AA", "B"] + result: "AA" + out: true + - name: "duplicated_three_digit_word" + in: + words: ["ABC", "ABC"] + result: "DEF" + out: true + - name: "three_digit_to_four_digit_carry" + in: + words: ["ABC", "ABC"] + result: "DDEF" + out: true + - name: "cyclic_two_digit_addends" + in: + words: ["AB", "BC", "CA"] + result: "DD" + out: true + - name: "four_distinct_single_addends" + in: + words: ["A", "B", "C", "D"] + result: "EA" + out: true + - name: "five_distinct_single_addends" + in: + words: ["A", "B", "C", "D", "E"] + result: "AE" + out: true + - name: "zero_in_trailing_position" + in: + words: ["BA", "BA"] + result: "CA" + out: true + - name: "seven_digit_zero_addend" + in: + words: ["AAAAAAA", "B"] + result: "AAAAAAA" + out: true + - name: "same_length_forces_leading_zero" + in: + words: ["A", "B"] + result: "AB" + out: false + - name: "five_addends_exceed_single_digit" + in: + words: ["A", "B", "C", "D", "E"] + result: "F" + out: false + - name: "result_shorter_than_longest_word" + in: + words: ["ABCDEFG", "H"] + result: "ABCDEF" + out: false diff --git a/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.cpp b/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.cpp new file mode 100644 index 00000000..85525052 --- /dev/null +++ b/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.cpp @@ -0,0 +1,76 @@ +class Solution { +public: + bool isSolvable(vector& words, string result) { + unordered_set zeroes; + int m = 0; + for (const auto& word : words) { + if (word.length() > 1) { + zeroes.insert(word[0]); + } + m = max(m, (int)word.length()); + } + if (m > result.length()) return false; + + unordered_map d; + for (const auto& word : words) { + for (char c : word) { + d[c] = -1; + } + } + for (char c : result) { + d[c] = -1; + } + + vector wordsRev; + for (const auto& word : words) { + string rev = word; + reverse(rev.begin(), rev.end()); + wordsRev.push_back(rev); + } + reverse(result.begin(), result.end()); + string resultRev = result; + int R = resultRev.length(); + int N = wordsRev.size(); + unordered_set visited = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + + function rec = [&](int wi, int ri, int rem) -> bool { + if (ri == R) { + return rem == 0 && (resultRev.length() == 1 || d[resultRev[R-1]] != 0); + } + if (wi == N) { + if (d[resultRev[ri]] != -1) { + if (d[resultRev[ri]] != rem % 10) return false; + return rec(0, ri + 1, rem / 10); + } else if (visited.count(rem % 10)) { + int val = rem % 10; + visited.erase(val); + d[resultRev[ri]] = val; + bool ret = rec(wi, ri, rem); + d[resultRev[ri]] = -1; + visited.insert(val); + if (ret) return true; + } + return false; + } + if (wordsRev[wi].length() <= ri) { + return rec(wi + 1, ri, rem); + } + if (d[wordsRev[wi][ri]] != -1) { + return rec(wi + 1, ri, rem + d[wordsRev[wi][ri]]); + } + for (int val = 0; val < 10; val++) { + if (visited.count(val) && (val != 0 || !zeroes.count(wordsRev[wi][ri]))) { + visited.erase(val); + d[wordsRev[wi][ri]] = val; + bool ret = rec(wi + 1, ri, rem + val); + d[wordsRev[wi][ri]] = -1; + visited.insert(val); + if (ret) return true; + } + } + return false; + }; + + return rec(0, 0, 0); + } +}; diff --git a/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.cs b/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.cs new file mode 100644 index 00000000..90da9ace --- /dev/null +++ b/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.cs @@ -0,0 +1,70 @@ +public class Solution { + public bool IsSolvable(string[] words, string result) { + var zeroes = new HashSet(); + int m = 0; + foreach (var word in words) { + if (word.Length > 1) { + zeroes.Add(word[0]); + } + m = Math.Max(m, word.Length); + } + if (m > result.Length) return false; + + var d = new Dictionary(); + foreach (var word in words) { + foreach (var c in word) { + d[c] = -1; + } + } + foreach (var c in result) { + d[c] = -1; + } + + var wordsRev = words.Select(w => new string(w.Reverse().ToArray())).ToArray(); + var resultRev = new string(result.Reverse().ToArray()); + int R = resultRev.Length; + int N = wordsRev.Length; + var visited = new HashSet { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; + + Func rec = null; + rec = (wi, ri, rem) => { + if (ri == R) { + return rem == 0 && (result.Length == 1 || d[resultRev[R - 1]] != 0); + } + if (wi == N) { + if (d[resultRev[ri]] != -1) { + if (d[resultRev[ri]] != rem % 10) return false; + return rec(0, ri + 1, rem / 10); + } else if (visited.Contains(rem % 10)) { + int val = rem % 10; + visited.Remove(val); + d[resultRev[ri]] = val; + bool ret = rec(wi, ri, rem); + d[resultRev[ri]] = -1; + visited.Add(val); + if (ret) return true; + } + return false; + } + if (wordsRev[wi].Length <= ri) { + return rec(wi + 1, ri, rem); + } + if (d[wordsRev[wi][ri]] != -1) { + return rec(wi + 1, ri, rem + d[wordsRev[wi][ri]]); + } + for (int val = 0; val < 10; val++) { + if (visited.Contains(val) && (val != 0 || !zeroes.Contains(wordsRev[wi][ri]))) { + visited.Remove(val); + d[wordsRev[wi][ri]] = val; + bool ret = rec(wi + 1, ri, rem + val); + d[wordsRev[wi][ri]] = -1; + visited.Add(val); + if (ret) return true; + } + } + return false; + }; + + return rec(0, 0, 0); + } +} diff --git a/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.dart b/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.dart new file mode 100644 index 00000000..0296533f --- /dev/null +++ b/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.dart @@ -0,0 +1,65 @@ +class Solution { + bool isSolvable(List words, String result) { + Set zeroes = {}; + int m = 0; + for (var word in words) { + if (word.length > 1) { + zeroes.add(word[0]); + } + m = m > word.length ? m : word.length; + } + if (m > result.length) return false; + + Map d = {}; + for (var word in words + [result]) { + for (var c in word.split('')) { + d[c] = -1; + } + } + List wordsRev = words.map((w) => w.split('').reversed.join()).toList(); + String resultRev = result.split('').reversed.join(); + int R = resultRev.length; + int N = wordsRev.length; + Set visited = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + + bool rec(int wi, int ri, int rem) { + if (ri == R) { + return rem == 0 && (result.length == 1 || d[resultRev[R - 1]] != 0); + } + if (wi == N) { + if (d[resultRev[ri]] != -1) { + if (d[resultRev[ri]] != rem % 10) return false; + return rec(0, ri + 1, rem ~/ 10); + } else if (visited.contains(rem % 10)) { + int val = rem % 10; + visited.remove(val); + d[resultRev[ri]] = val; + bool ret = rec(wi, ri, rem); + d[resultRev[ri]] = -1; + visited.add(val); + if (ret) return true; + } + return false; + } + if (wordsRev[wi].length <= ri) { + return rec(wi + 1, ri, rem); + } + if (d[wordsRev[wi][ri]] != -1) { + return rec(wi + 1, ri, rem + d[wordsRev[wi][ri]]!); + } + for (int val = 0; val < 10; val++) { + if (visited.contains(val) && (val != 0 || !zeroes.contains(wordsRev[wi][ri]))) { + visited.remove(val); + d[wordsRev[wi][ri]] = val; + bool ret = rec(wi + 1, ri, rem + val); + d[wordsRev[wi][ri]] = -1; + visited.add(val); + if (ret) return true; + } + } + return false; + } + + return rec(0, 0, 0); + } +} diff --git a/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.go b/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.go new file mode 100644 index 00000000..5be0e557 --- /dev/null +++ b/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.go @@ -0,0 +1,90 @@ +func isSolvable(words []string, result string) bool { + zeroes := make(map[byte]bool) + m := 0 + for _, word := range words { + if len(word) > 1 { + zeroes[word[0]] = true + } + if len(word) > m { + m = len(word) + } + } + if m > len(result) { + return false + } + d := make(map[byte]int) + for _, word := range words { + for i := 0; i < len(word); i++ { + d[word[i]] = -1 + } + } + for i := 0; i < len(result); i++ { + d[result[i]] = -1 + } + wordsRev := make([]string, len(words)) + for i, word := range words { + wordsRev[i] = reverse(word) + } + resultRev := reverse(result) + R := len(resultRev) + N := len(wordsRev) + visited := make(map[int]bool) + for i := 0; i < 10; i++ { + visited[i] = true + } + + var rec func(wi, ri, rem int) bool + rec = func(wi, ri, rem int) bool { + if ri == R { + return rem == 0 && (len(resultRev) == 1 || d[resultRev[R-1]] != 0) + } + if wi == N { + if d[resultRev[ri]] != -1 { + if d[resultRev[ri]] != rem%10 { + return false + } else { + return rec(0, ri+1, rem/10) + } + } else if visited[rem%10] { + val := rem % 10 + delete(visited, val) + d[resultRev[ri]] = val + ret := rec(wi, ri, rem) + d[resultRev[ri]] = -1 + visited[val] = true + if ret { + return true + } + } + return false + } + if len(wordsRev[wi]) <= ri { + return rec(wi+1, ri, rem) + } + if d[wordsRev[wi][ri]] != -1 { + return rec(wi+1, ri, rem+d[wordsRev[wi][ri]]) + } + for val := 0; val < 10; val++ { + if visited[val] && (val != 0 || !zeroes[wordsRev[wi][ri]]) { + delete(visited, val) + d[wordsRev[wi][ri]] = val + ret := rec(wi+1, ri, rem+val) + d[wordsRev[wi][ri]] = -1 + visited[val] = true + if ret { + return true + } + } + } + return false + } + return rec(0, 0, 0) +} + +func reverse(s string) string { + runes := []byte(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) +} diff --git a/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.java b/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.java new file mode 100644 index 00000000..25fe3823 --- /dev/null +++ b/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.java @@ -0,0 +1,81 @@ +import java.util.*; + +class Solution { + public boolean isSolvable(String[] words, String result) { + Set zeroes = new HashSet<>(); + int m = 0; + for (String word : words) { + if (word.length() > 1) { + zeroes.add(word.charAt(0)); + } + m = Math.max(m, word.length()); + } + if (m > result.length()) { + return false; + } + Map d = new HashMap<>(); + for (String word : words) { + for (char c : word.toCharArray()) { + d.put(c, -1); + } + } + for (char c : result.toCharArray()) { + d.put(c, -1); + } + String[] wRev = new String[words.length]; + for (int i = 0; i < words.length; i++) { + wRev[i] = new StringBuilder(words[i]).reverse().toString(); + } + String rRev = new StringBuilder(result).reverse().toString(); + int R = rRev.length(); + int N = wRev.length; + Set visited = new HashSet<>(); + for (int i = 0; i < 10; i++) { + visited.add(i); + } + return rec(0, 0, 0, wRev, rRev, d, zeroes, visited, R, N); + } + + private boolean rec(int wi, int ri, int rem, String[] words, String result, + Map d, Set zeroes, + Set visited, int R, int N) { + if (ri == R) { + return rem == 0 && (result.length() == 1 || d.get(result.charAt(R-1)) != 0); + } + if (wi == N) { + if (d.get(result.charAt(ri)) != -1) { + if (d.get(result.charAt(ri)) != rem % 10) { + return false; + } else { + return rec(0, ri+1, rem/10, words, result, d, zeroes, visited, R, N); + } + } else if (visited.contains(rem % 10)) { + int val = rem % 10; + visited.remove(val); + d.put(result.charAt(ri), val); + boolean ret = rec(wi, ri, rem, words, result, d, zeroes, visited, R, N); + d.put(result.charAt(ri), -1); + visited.add(val); + if (ret) return true; + } + return false; + } + if (words[wi].length() <= ri) { + return rec(wi+1, ri, rem, words, result, d, zeroes, visited, R, N); + } + if (d.get(words[wi].charAt(ri)) != -1) { + return rec(wi+1, ri, rem + d.get(words[wi].charAt(ri)), words, result, d, zeroes, visited, R, N); + } + for (int val = 0; val < 10; val++) { + if (visited.contains(val) && (val != 0 || !zeroes.contains(words[wi].charAt(ri)))) { + visited.remove(val); + d.put(words[wi].charAt(ri), val); + boolean ret = rec(wi+1, ri, rem + val, words, result, d, zeroes, visited, R, N); + d.put(words[wi].charAt(ri), -1); + visited.add(val); + if (ret) return true; + } + } + return false; + } +} diff --git a/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.kt b/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.kt new file mode 100644 index 00000000..37a61acb --- /dev/null +++ b/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.kt @@ -0,0 +1,65 @@ +class Solution { + fun isSolvable(words: Array, result: String): Boolean { + val zeroes = mutableSetOf() + var m = 0 + for (word in words) { + if (word.length > 1) { + zeroes.add(word[0]) + } + m = maxOf(m, word.length) + } + if (m > result.length) return false + + val d = mutableMapOf() + for (word in words + result) { + for (c in word) { + d[c] = -1 + } + } + val wordsRev = words.map { it.reversed() } + val resultRev = result.reversed() + val R = resultRev.length + val N = wordsRev.size + val visited = (0..9).toMutableSet() + + fun rec(wi: Int, ri: Int, rem: Int): Boolean { + if (ri == R) { + return rem == 0 && (result.length == 1 || d[resultRev[R-1]] != 0) + } + if (wi == N) { + if (d[resultRev[ri]] != -1) { + if (d[resultRev[ri]] != rem % 10) return false + else return rec(0, ri+1, rem/10) + } else if (rem % 10 in visited) { + val v = rem % 10 + visited.remove(v) + d[resultRev[ri]] = v + val ret = rec(wi, ri, rem) + d[resultRev[ri]] = -1 + visited.add(v) + if (ret) return true + } + return false + } + if (wordsRev[wi].length <= ri) { + return rec(wi+1, ri, rem) + } + if (d[wordsRev[wi][ri]] != -1) { + return rec(wi+1, ri, rem + d[wordsRev[wi][ri]]!!) + } + for (v in 0..9) { + if (v in visited && (v != 0 || wordsRev[wi][ri] !in zeroes)) { + visited.remove(v) + d[wordsRev[wi][ri]] = v + val ret = rec(wi+1, ri, rem + v) + d[wordsRev[wi][ri]] = -1 + visited.add(v) + if (ret) return true + } + } + return false + } + + return rec(0, 0, 0) + } +} diff --git a/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.py b/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.py new file mode 100644 index 00000000..12b57507 --- /dev/null +++ b/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.py @@ -0,0 +1,52 @@ +class Solution: + def isSolvable(self, wL: List[str], res: str) -> bool: + zeroes = set() + m = 0 + for word in wL: + if len(word) > 1: + zeroes.add(word[0]) + m = max(m, len(word)) + if m > len(res): + return False + d = {i: -1 for word in wL + [res] for i in word} + wL = [word[::-1] for word in wL] + res = res[::-1] + R = len(res) + N = len(wL) + visited = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0} + + def rec(wi, ri, rem): + if ri == R: + return rem == 0 and (len(res) == 1 or d[res[R - 1]] != 0) + if wi == N: + if d[res[ri]] != -1: + if d[res[ri]] != rem % 10: + return False + else: + return rec(0, ri + 1, rem // 10) + elif rem % 10 in visited: + val = rem % 10 + visited.remove(val) + d[res[ri]] = val + ret = rec(wi, ri, rem) + d[res[ri]] = -1 + visited.add(val) + if ret: + return True + return False + if len(wL[wi]) <= ri: + return rec(wi + 1, ri, rem) + if d[wL[wi][ri]] != -1: + return rec(wi + 1, ri, rem + d[wL[wi][ri]]) + for val in range(0, 10): + if val in visited and (val != 0 or wL[wi][ri] not in zeroes): + visited.remove(val) + d[wL[wi][ri]] = val + ret = rec(wi + 1, ri, rem + val) + d[wL[wi][ri]] = -1 + visited.add(val) + if ret: + return True + return False + + return rec(0, 0, 0) diff --git a/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.py2 b/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.py2 new file mode 100644 index 00000000..576f8400 --- /dev/null +++ b/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.py2 @@ -0,0 +1,57 @@ +class Solution(object): + def isSolvable(self, words, result): + """ + :type words: List[str] + :type result: str + :rtype: bool + """ + zeroes = set() + m = 0 + for word in words: + if len(word) > 1: + zeroes.add(word[0]) + m = max(m, len(word)) + if m > len(result): + return False + d = {i: -1 for word in words + [result] for i in word} + words = [word[::-1] for word in words] + result = result[::-1] + R = len(result) + N = len(words) + visited = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} + + def rec(wi, ri, rem): + if ri == R: + return rem == 0 and (len(result) == 1 or d[result[R-1]] != 0) + if wi == N: + if d[result[ri]] != -1: + if d[result[ri]] != rem % 10: + return False + else: + return rec(0, ri+1, rem//10) + elif rem % 10 in visited: + val = rem % 10 + visited.remove(val) + d[result[ri]] = val + ret = rec(wi, ri, rem) + d[result[ri]] = -1 + visited.add(val) + if ret: + return True + return False + if len(words[wi]) <= ri: + return rec(wi+1, ri, rem) + if d[words[wi][ri]] != -1: + return rec(wi+1, ri, rem + d[words[wi][ri]]) + for val in range(10): + if val in visited and (val != 0 or words[wi][ri] not in zeroes): + visited.remove(val) + d[words[wi][ri]] = val + ret = rec(wi+1, ri, rem + val) + d[words[wi][ri]] = -1 + visited.add(val) + if ret: + return True + return False + + return rec(0, 0, 0) diff --git a/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.rb b/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.rb new file mode 100644 index 00000000..34c6d05d --- /dev/null +++ b/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.rb @@ -0,0 +1,68 @@ +# @param {String[]} words +# @param {String} result +# @return {Boolean} +def is_solvable(words, result) + zeroes = Set.new + m = 0 + words.each do |word| + if word.length > 1 + zeroes.add(word[0]) + end + m = [m, word.length].max + end + if m > result.length + return false + end + d = {} + (words + [result]).each do |word| + word.each_char { |c| d[c] = -1 } + end + words = words.map { |word| word.reverse } + result = result.reverse + r_len = result.length + n = words.length + visited = (0..9).to_set + + recursive = lambda do |wi, ri, rem| + if ri == r_len + return rem == 0 && (result.length == 1 || d[result[r_len-1]] != 0) + end + if wi == n + if d[result[ri]] != -1 + if d[result[ri]] != rem % 10 + return false + else + return recursive.call(0, ri+1, rem/10) + end + elsif visited.include?(rem % 10) + val = rem % 10 + visited.delete(val) + d[result[ri]] = val + ret = recursive.call(wi, ri, rem) + d[result[ri]] = -1 + visited.add(val) + return true if ret + end + return false + end + if words[wi].length <= ri + return recursive.call(wi+1, ri, rem) + end + if d[words[wi][ri]] != -1 + return recursive.call(wi+1, ri, rem + d[words[wi][ri]]) + end + (0..9).each do |val| + if visited.include?(val) && (val != 0 || !zeroes.include?(words[wi][ri])) + visited.delete(val) + d[words[wi][ri]] = val + ret = recursive.call(wi+1, ri, rem + val) + d[words[wi][ri]] = -1 + visited.add(val) + return true if ret + end + end + false + end + + recursive.call(0, 0, 0) +end diff --git a/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.rs b/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.rs new file mode 100644 index 00000000..6c23c36e --- /dev/null +++ b/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.rs @@ -0,0 +1,92 @@ +impl Solution { + pub fn is_solvable(words: Vec, result: String) -> bool { + use std::collections::{HashMap, HashSet}; + + let mut zeroes = HashSet::new(); + let mut m = 0; + for word in &words { + if word.len() > 1 { + zeroes.insert(word.as_bytes()[0] as char); + } + m = m.max(word.len()); + } + if m > result.len() { + return false; + } + + let mut d: HashMap = HashMap::new(); + for word in words.iter().chain(std::iter::once(&result)) { + for c in word.chars() { + d.insert(c, -1); + } + } + + let words_rev: Vec = words.iter().map(|w| w.chars().rev().collect()).collect(); + let result_rev: String = result.chars().rev().collect(); + let r = result_rev.len(); + let n = words_rev.len(); + let mut visited: HashSet = (0..10).collect(); + + fn rec( + wi: usize, + ri: usize, + rem: i32, + words_rev: &[String], + result_rev: &str, + d: &mut HashMap, + zeroes: &HashSet, + visited: &mut HashSet, + r: usize, + n: usize, + ) -> bool { + if ri == r { + return rem == 0 && (result_rev.len() == 1 || d[&result_rev.chars().nth(r-1).unwrap()] != 0); + } + let r_char = result_rev.chars().nth(ri).unwrap(); + if wi == n { + let dv = d[&r_char]; + if dv != -1 { + if dv != rem % 10 { + return false; + } else { + return rec(0, ri + 1, rem / 10, words_rev, result_rev, d, zeroes, visited, r, n); + } + } else if visited.contains(&(rem % 10)) { + let val = rem % 10; + visited.remove(&val); + d.insert(r_char, val); + let ret = rec(wi, ri, rem, words_rev, result_rev, d, zeroes, visited, r, n); + d.insert(r_char, -1); + visited.insert(val); + if ret { + return true; + } + } + return false; + } + if words_rev[wi].len() <= ri { + return rec(wi + 1, ri, rem, words_rev, result_rev, d, zeroes, visited, r, n); + } + let w_char = words_rev[wi].chars().nth(ri).unwrap(); + let dw = d[&w_char]; + if dw != -1 { + return rec(wi + 1, ri, rem + dw, words_rev, result_rev, d, zeroes, visited, r, n); + } + for val in 0..10 { + if visited.contains(&val) && (val != 0 || !zeroes.contains(&w_char)) { + visited.remove(&val); + d.insert(w_char, val); + let ret = rec(wi + 1, ri, rem + val, words_rev, result_rev, d, zeroes, visited, r, n); + d.insert(w_char, -1); + visited.insert(val); + if ret { + return true; + } + } + } + false + } + + rec(0, 0, 0, &words_rev, &result_rev, &mut d, &zeroes, &mut visited, r, n) + } +} diff --git a/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.swift b/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.swift new file mode 100644 index 00000000..2d617be2 --- /dev/null +++ b/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.swift @@ -0,0 +1,67 @@ +class Solution { + func isSolvable(_ words: [String], _ result: String) -> Bool { + var zeroes = Set() + var m = 0 + for word in words { + if word.count > 1 { + zeroes.insert(word.first!) + } + m = max(m, word.count) + } + if m > result.count { return false } + + var d = [Character: Int]() + for word in words + [result] { + for c in word { + d[c] = -1 + } + } + let wordsRev = words.map { String($0.reversed()) } + let resultRev = String(result.reversed()) + let R = resultRev.count + let N = wordsRev.count + var visited: Set = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + + func rec(_ wi: Int, _ ri: Int, _ rem: Int) -> Bool { + if ri == R { + return rem == 0 && (result.count == 1 || d[resultRev[resultRev.index(resultRev.startIndex, offsetBy: R-1)]] != 0) + } + let rChar = resultRev[resultRev.index(resultRev.startIndex, offsetBy: ri)] + if wi == N { + if d[rChar] != -1 { + if d[rChar] != rem % 10 { return false } + return rec(0, ri+1, rem/10) + } else if visited.contains(rem % 10) { + let val = rem % 10 + visited.remove(val) + d[rChar] = val + let ret = rec(wi, ri, rem) + d[rChar] = -1 + visited.insert(val) + if ret { return true } + } + return false + } + if wordsRev[wi].count <= ri { + return rec(wi+1, ri, rem) + } + let wChar = wordsRev[wi][wordsRev[wi].index(wordsRev[wi].startIndex, offsetBy: ri)] + if d[wChar] != -1 { + return rec(wi+1, ri, rem + d[wChar]!) + } + for val in 0...9 { + if visited.contains(val) && (val != 0 || !zeroes.contains(wChar)) { + visited.remove(val) + d[wChar] = val + let ret = rec(wi+1, ri, rem + val) + d[wChar] = -1 + visited.insert(val) + if ret { return true } + } + } + return false + } + + return rec(0, 0, 0) + } +} diff --git a/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.ts b/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.ts new file mode 100644 index 00000000..41beafbf --- /dev/null +++ b/tests/1001-1500/1307. verbal-arithmetic-puzzle/sol.ts @@ -0,0 +1,65 @@ +function isSolvable(words: string[], result: string): boolean { + const zeroes = new Set(); + let m = 0; + for (const word of words) { + if (word.length > 1) { + zeroes.add(word[0]); + } + m = Math.max(m, word.length); + } + if (m > result.length) return false; + + const d = new Map(); + for (const word of [...words, result]) { + for (const c of word) { + d.set(c, -1); + } + } + const wordsRev = words.map((w) => w.split("").reverse().join("")); + const resultRev = result.split("").reverse().join(""); + const R = resultRev.length; + const N = wordsRev.length; + const visited = new Set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); + + const rec = (wi: number, ri: number, rem: number): boolean => { + if (ri === R) { + return ( + rem === 0 && (result.length === 1 || d.get(resultRev[R - 1]) !== 0) + ); + } + if (wi === N) { + if (d.get(resultRev[ri]) !== -1) { + if (d.get(resultRev[ri]) !== rem % 10) return false; + return rec(0, ri + 1, Math.floor(rem / 10)); + } else if (visited.has(rem % 10)) { + const val = rem % 10; + visited.delete(val); + d.set(resultRev[ri], val); + const ret = rec(wi, ri, rem); + d.set(resultRev[ri], -1); + visited.add(val); + if (ret) return true; + } + return false; + } + if (wordsRev[wi].length <= ri) { + return rec(wi + 1, ri, rem); + } + if (d.get(wordsRev[wi][ri]) !== -1) { + return rec(wi + 1, ri, rem + d.get(wordsRev[wi][ri])!); + } + for (let val = 0; val < 10; val++) { + if (visited.has(val) && (val !== 0 || !zeroes.has(wordsRev[wi][ri]))) { + visited.delete(val); + d.set(wordsRev[wi][ri], val); + const ret = rec(wi + 1, ri, rem + val); + d.set(wordsRev[wi][ri], -1); + visited.add(val); + if (ret) return true; + } + } + return false; + }; + + return rec(0, 0, 0); +} diff --git a/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/manifest.yaml b/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/manifest.yaml new file mode 100644 index 00000000..456d9387 --- /dev/null +++ b/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/manifest.yaml @@ -0,0 +1,202 @@ +entry: + id: 1309 + title: "decrypt-string-from-alphabet-to-integer-mapping" + params: + s: + type: string + call: + cpp: "Solution().freqAlphabets({s})" + rust: "Solution::freq_alphabets({s})" + python3: "Solution().freqAlphabets({s})" + python2: "Solution().freqAlphabets({s})" + ruby: "freq_alphabets({s})" + java: "new Solution().freqAlphabets({s})" + csharp: "new Solution().FreqAlphabets({s})" + kotlin: "Solution().freqAlphabets({s})" + go: "freqAlphabets({s})" + dart: "Solution().freqAlphabets({s})" + swift: "Solution().freqAlphabets({s})" + typescript: "freqAlphabets({s})" +judge: + type: "exact" +limits: + time_ms: 500 + memory_mb: 300 +oracle: + python3: + call: "Checker().freqAlphabets(s, {result})" + checker: | + class Checker: + def freqAlphabets(self, s, result): + decoded = [] + index = 0 + while index < len(s): + if index + 2 < len(s) and s[index + 2] == '#': + decoded.append(chr(ord('a') + int(s[index:index + 2]) - 1)) + index += 3 + else: + decoded.append(chr(ord('a') + int(s[index]) - 1)) + index += 1 + return isinstance(result, str) and result == ''.join(decoded) +seed: 1309 +tests: + - name: "example_one" + in: + s: "10#11#12" + out: "jkab" + - name: "example_two" + in: + s: "1326#" + out: "acz" + - name: "single_a" + in: + s: "1" + out: "a" + - name: "single_i" + in: + s: "9" + out: "i" + - name: "single_j" + in: + s: "10#" + out: "j" + - name: "single_z" + in: + s: "26#" + out: "z" + - name: "all_single_digit_letters" + in: + s: "123456789" + out: "abcdefghi" + - name: "all_two_digit_letters" + in: + s: "10#11#12#13#14#15#16#17#18#19#20#21#22#23#24#25#26#" + out: "jklmnopqrstuvwxyz" + - name: "two_digit_starts_input" + in: + s: "10#123456789" + out: "jabcdefghi" + - name: "two_digit_ends_input" + in: + s: "12345678926#" + out: "abcdefghiz" + - name: "two_digit_between_digits" + in: + s: "12310#456" + out: "abcjdef" + - name: "consecutive_two_digit_tokens" + in: + s: "10#11#12#" + out: "jkl" + - name: "consecutive_single_digits" + in: + s: "987654321" + out: "ihgfedcba" + - name: "repeated_single_digit" + in: + s: "1111111111" + out: "aaaaaaaaaa" + - name: "repeated_two_digit_token" + in: + s: "26#26#26#26#" + out: "zzzz" + - name: "alternating_low_tokens" + in: + s: "110#211#312#" + out: "ajbkcl" + - name: "alternating_high_tokens" + in: + s: "920#821#722#623#" + out: "ithugvfw" + - name: "mixed_without_ambiguous_split" + in: + s: "315#" + out: "co" + - name: "mixed_leading_one" + in: + s: "126#" + out: "az" + - name: "mixed_leading_two" + in: + s: "226#" + out: "bz" + - name: "two_digit_tokens_with_digit_gaps" + in: + s: "18#4519#" + out: "rdes" + - name: "ascending_even_two_digit_tokens" + in: + s: "10#12#14#16#18#20#22#24#26#" + out: "jlnprtvxz" + - name: "descending_even_two_digit_tokens" + in: + s: "26#24#22#20#18#16#14#12#10#" + out: "zxvtrpnlj" + - name: "adjacent_hash_boundaries" + in: + s: "910#11#12#13#14#" + out: "ijklmn" + - name: "twenties_and_ones" + in: + s: "20#123" + out: "tabc" + - name: "twenties_at_end" + in: + s: "12320#" + out: "abct" + - name: "fourteen_through_sixteen" + in: + s: "1213#14#15#16#" + out: "abmnop" + - name: "full_alphabet_mixed_encoding" + in: + s: "12345678910#11#12#13#14#15#16#17#18#19#20#21#22#23#24#25#26#" + out: "abcdefghijklmnopqrstuvwxyz" + - name: "multiple_nineteens" + in: + s: "19#19#19#" + out: "sss" + - name: "multiple_twenties" + in: + s: "20#20#20#20#" + out: "tttt" + - name: "interleaved_extremes" + in: + s: "126#910#26#" + out: "azijz" + - name: "long_mixed_phrase" + in: + s: "12310#11#12#45620#21#78926#" + out: "abcjkldeftughiz" + - name: "two_digit_prefix_after_nine" + in: + s: "910#" + out: "ij" + - name: "single_digit_prefix_before_twenty_six" + in: + s: "926#" + out: "iz" + - name: "all_high_letters_descending" + in: + s: "26#25#24#23#22#21#20#19#18#17#16#15#14#13#12#11#10#" + out: "zyxwvutsrqponmlkj" + - name: "repeated_complete_alphabet_prefix" + in: + s: "12345678910#11#12#12345678910#11#12#" + out: "abcdefghijklabcdefghijkl" + - name: "long_single_digit_run" + in: + s: "123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789" + out: "abcdefghiabcdefghiabcdefghiabcdefghiabcdefghiabcdefghiabcdefghiabcdefghiabcdefghiabcdefghi" + - name: "long_two_digit_run" + in: + s: "10#11#12#13#14#15#16#17#18#19#20#21#22#23#24#25#26#10#11#12#13#14#15#16#18#19#20#21#22#23#24#25#26#" + out: "jklmnopqrstuvwxyzjklmnoprstuvwxyz" + - name: "boundary_transition_19_to_20" + in: + s: "19#20#" + out: "st" + - name: "boundary_transition_9_to_10" + in: + s: "910#" + out: "ij" diff --git a/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.cpp b/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.cpp new file mode 100644 index 00000000..53f61c09 --- /dev/null +++ b/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + string freqAlphabets(string s) { + string decoded; + int index = 0; + while (index < s.length()) { + if (index + 2 < s.length() && s[index + 2] == '#') { + int num = stoi(s.substr(index, 2)); + decoded += ('a' + num - 1); + index += 3; + } else { + int num = s[index] - '0'; + decoded += ('a' + num - 1); + index += 1; + } + } + return decoded; + } +}; diff --git a/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.cs b/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.cs new file mode 100644 index 00000000..a892f1e5 --- /dev/null +++ b/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.cs @@ -0,0 +1,18 @@ +public class Solution { + public string FreqAlphabets(string s) { + var decoded = new System.Text.StringBuilder(); + int index = 0; + while (index < s.Length) { + if (index + 2 < s.Length && s[index + 2] == '#') { + int num = int.Parse(s.Substring(index, 2)); + decoded.Append((char)('a' + num - 1)); + index += 3; + } else { + int num = s[index] - '0'; + decoded.Append((char)('a' + num - 1)); + index += 1; + } + } + return decoded.ToString(); + } +} diff --git a/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.dart b/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.dart new file mode 100644 index 00000000..3594c976 --- /dev/null +++ b/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.dart @@ -0,0 +1,18 @@ +class Solution { + String freqAlphabets(String s) { + List decoded = []; + int index = 0; + while (index < s.length) { + if (index + 2 < s.length && s[index + 2] == '#') { + int num = int.parse(s.substring(index, index + 2)); + decoded.add(String.fromCharCode('a'.codeUnitAt(0) + num - 1)); + index += 3; + } else { + int num = int.parse(s[index]); + decoded.add(String.fromCharCode('a'.codeUnitAt(0) + num - 1)); + index += 1; + } + } + return decoded.join(''); + } +} diff --git a/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.go b/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.go new file mode 100644 index 00000000..919ad0bc --- /dev/null +++ b/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.go @@ -0,0 +1,16 @@ +func freqAlphabets(s string) string { + decoded := make([]byte, 0) + index := 0 + for index < len(s) { + if index + 2 < len(s) && s[index + 2] == '#' { + num := (s[index] - '0') * 10 + (s[index + 1] - '0') + decoded = append(decoded, 'a' + num - 1) + index += 3 + } else { + num := s[index] - '0' + decoded = append(decoded, 'a' + num - 1) + index += 1 + } + } + return string(decoded) +} diff --git a/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.java b/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.java new file mode 100644 index 00000000..eff44024 --- /dev/null +++ b/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.java @@ -0,0 +1,18 @@ +class Solution { + public String freqAlphabets(String s) { + StringBuilder decoded = new StringBuilder(); + int index = 0; + while (index < s.length()) { + if (index + 2 < s.length() && s.charAt(index + 2) == '#') { + int num = Integer.parseInt(s.substring(index, index + 2)); + decoded.append((char) ('a' + num - 1)); + index += 3; + } else { + int num = s.charAt(index) - '0'; + decoded.append((char) ('a' + num - 1)); + index += 1; + } + } + return decoded.toString(); + } +} diff --git a/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.kt b/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.kt new file mode 100644 index 00000000..859a0d71 --- /dev/null +++ b/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.kt @@ -0,0 +1,18 @@ +class Solution { + fun freqAlphabets(s: String): String { + val decoded = StringBuilder() + var index = 0 + while (index < s.length) { + if (index + 2 < s.length && s[index + 2] == '#') { + val num = s.substring(index, index + 2).toInt() + decoded.append(('a' + num - 1)) + index += 3 + } else { + val num = s[index] - '0' + decoded.append(('a' + num - 1)) + index += 1 + } + } + return decoded.toString() + } +} diff --git a/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.py b/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.py new file mode 100644 index 00000000..7f96a8eb --- /dev/null +++ b/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.py @@ -0,0 +1,12 @@ +class Solution: + def freqAlphabets(self, s): + decoded = [] + index = 0 + while index < len(s): + if index + 2 < len(s) and s[index + 2] == "#": + decoded.append(chr(ord("a") + int(s[index : index + 2]) - 1)) + index += 3 + else: + decoded.append(chr(ord("a") + int(s[index]) - 1)) + index += 1 + return "".join(decoded) diff --git a/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.py2 b/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.py2 new file mode 100644 index 00000000..f1648a70 --- /dev/null +++ b/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.py2 @@ -0,0 +1,12 @@ +class Solution(object): + def freqAlphabets(self, s): + decoded = [] + index = 0 + while index < len(s): + if index + 2 < len(s) and s[index + 2] == '#': + decoded.append(chr(ord('a') + int(s[index:index + 2]) - 1)) + index += 3 + else: + decoded.append(chr(ord('a') + int(s[index]) - 1)) + index += 1 + return ''.join(decoded) diff --git a/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.rb b/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.rb new file mode 100644 index 00000000..616f0ce7 --- /dev/null +++ b/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.rb @@ -0,0 +1,16 @@ +# @param {String} s +# @return {String} +def freq_alphabets(s) + decoded = [] + index = 0 + while index < s.length + if index + 2 < s.length && s[index + 2] == '#' + decoded << (('a'.ord) + s[index, 2].to_i - 1).chr + index += 3 + else + decoded << (('a'.ord) + s[index].to_i - 1).chr + index += 1 + end + end + decoded.join +end diff --git a/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.rs b/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.rs new file mode 100644 index 00000000..3a952ae4 --- /dev/null +++ b/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.rs @@ -0,0 +1,19 @@ +impl Solution { + pub fn freq_alphabets(s: String) -> String { + let mut decoded = Vec::new(); + let bytes = s.as_bytes(); + let mut index = 0; + while index < bytes.len() { + if index + 2 < bytes.len() && bytes[index + 2] == b'#' { + let num = (bytes[index] - b'0') * 10 + (bytes[index + 1] - b'0'); + decoded.push(b'a' + num - 1); + index += 3; + } else { + let num = bytes[index] - b'0'; + decoded.push(b'a' + num - 1); + index += 1; + } + } + String::from_utf8(decoded).unwrap() + } +} diff --git a/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.swift b/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.swift new file mode 100644 index 00000000..33808cf6 --- /dev/null +++ b/tests/1001-1500/1309. decrypt-string-from-alphabet-to-integer-mapping/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func freqAlphabets(_ s: String) -> String { + var decoded = "" + var index = s.startIndex + while index < s.endIndex { + let third = s.index(index, offsetBy: 2, limitedBy: s.index(before: s.endIndex)) + if let third = third, s[third] == "#" { + let numStr = s[index.. 1000000000 for x in arr): + return False + if not isinstance(result, list): + return False + prefix = [0] + for value in arr: + prefix.append(prefix[-1] ^ value) + expected = [] + for query in queries: + if not isinstance(query, list) or len(query) != 2: + return False + a, b = query + if not isinstance(a, int) or not isinstance(b, int) or a < 0 or b < a or b >= len(arr): + return False + expected.append(prefix[b + 1] ^ prefix[a]) + return result == expected +seed: 1310 +tests: + - name: single_element + in: + arr: [7] + queries: + - [0, 0] + - name: example_one + in: + arr: [1, 3, 4, 8] + queries: + - [0, 1] + - [1, 2] + - [0, 3] + - [3, 3] + - name: all_identical + in: + arr: [1, 1, 1, 1] + queries: + - [0, 3] + - [1, 2] + - name: powers_of_two + in: + arr: [1, 2, 4, 8, 16] + queries: + - [0, 4] + - [1, 3] + - [2, 2] + - name: repeated_values + in: + arr: [5, 5, 5, 5, 5] + queries: + - [0, 4] + - [0, 1] + - [1, 3] + - name: full_ranges + in: + arr: [9, 8, 7, 6, 5, 4] + queries: + - [0, 5] + - [0, 0] + - [5, 5] + - name: overlapping_queries + in: + arr: [10, 20, 30, 40, 50] + queries: + - [0, 2] + - [1, 3] + - [2, 4] + - [0, 4] + - name: adjacent_queries + in: + arr: [3, 1, 4, 1, 5, 9] + queries: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - name: disjoint_queries + in: + arr: [12, 7, 3, 9, 15, 2] + queries: + - [0, 1] + - [2, 3] + - [4, 5] + - name: large_values + in: + arr: [1000000000, 999999999, 536870912, 1] + queries: + - [0, 0] + - [0, 3] + - [1, 2] + - name: palindromic_values + in: + arr: [1, 2, 3, 2, 1] + queries: + - [0, 4] + - [0, 2] + - [2, 4] + - name: cancellation + in: + arr: [6, 6, 12, 12, 3] + queries: + - [0, 1] + - [0, 3] + - [1, 4] + - name: alternating_bits + in: + arr: [255, 1, 255, 1, 255, 1] + queries: + - [0, 5] + - [0, 4] + - [1, 4] + - name: two_elements + in: + arr: [100, 200] + queries: + - [0, 0] + - [1, 1] + - [0, 1] + - name: descending + in: + arr: [15, 14, 13, 12, 11, 10, 9] + queries: + - [1, 5] + - [2, 6] + - name: many_singletons + in: + arr: [4, 8, 15, 16, 23, 42] + queries: + - [0, 0] + - [1, 1] + - [2, 2] + - [3, 3] + - [4, 4] + - [5, 5] + - name: nested_ranges + in: + arr: [2, 4, 6, 8, 10, 12] + queries: + - [0, 5] + - [1, 4] + - [2, 3] + - name: alternating_small_values + in: + arr: [1, 2, 1, 2, 1, 2, 1] + queries: + - [0, 6] + - [1, 5] + - [2, 4] + - name: mixed_small + in: + arr: [17, 23, 4, 31, 8, 12, 29, 2] + queries: + - [0, 7] + - [1, 6] + - [3, 5] + - name: powers_boundary + in: + arr: [1, 3, 7, 15, 31, 63] + queries: + - [0, 5] + - [1, 4] + - [2, 2] + - name: long_static + in: + arr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] + queries: + - [0, 11] + - [0, 5] + - [6, 11] + - [4, 8] + - name: query_ordered_pairs + in: + arr: [21, 34, 55, 89, 144] + queries: + - [0, 4] + - [0, 2] + - [2, 4] + - name: xor_self_inverse + in: + arr: [31, 31, 31, 31] + queries: + - [0, 3] + - [0, 1] + - [1, 2] + - name: high_bit_values + in: + arr: [536870912, 268435456, 134217728, 67108864] + queries: + - [0, 3] + - [1, 3] + - name: alternating_large + in: + arr: [1000000000, 1, 1000000000, 1, 1000000000] + queries: + - [0, 4] + - [1, 3] + - [2, 4] + - name: prefix_suffix + in: + arr: [2, 3, 5, 7, 11, 13, 17] + queries: + - [0, 2] + - [4, 6] + - [0, 6] + - name: adjacent_singletons + in: + arr: [101, 202, 303, 404, 505] + queries: + - [0, 0] + - [1, 1] + - [2, 2] + - [3, 3] + - [4, 4] + - name: nested_long_ranges + in: + arr: [1, 4, 9, 16, 25, 36, 49, 64] + queries: + - [0, 7] + - [1, 6] + - [2, 5] + - [3, 4] + - name: sparse_queries + in: + arr: [8, 16, 32, 64, 128, 256, 512, 1024] + queries: + - [0, 7] + - [0, 1] + - [6, 7] + - name: mixed_repeated_ranges + in: + arr: [1, 9, 1, 9, 1, 9, 1] + queries: + - [0, 6] + - [1, 5] + - [2, 4] + - name: generated_small + seed: 101 + in: + arr: + gen: array + len: 20 + of: + gen: int + min: 1 + max: 1023 + distinct: false + sorted: false + elemType: int + queries: + gen: array + len: 30 + of: + gen: array + len: 2 + of: + gen: int + min: 0 + max: 19 + distinct: false + sorted: true + distinct: false + sorted: false + - name: generated_medium + seed: 202 + in: + arr: + gen: array + len: 100 + of: + gen: int + min: 1 + max: 1000000000 + distinct: false + sorted: false + elemType: int + queries: + gen: array + len: 200 + of: + gen: array + len: 2 + of: + gen: int + min: 0 + max: 99 + distinct: false + sorted: true + distinct: false + sorted: false + - name: generated_binary_values + seed: 303 + in: + arr: + gen: array + len: 500 + of: + gen: int + min: 1 + max: 1 + distinct: false + sorted: false + elemType: int + queries: + gen: array + len: 500 + of: + gen: array + len: 2 + of: + gen: int + min: 0 + max: 499 + distinct: false + sorted: true + distinct: false + sorted: false + - name: generated_large + seed: 404 + in: + arr: + gen: array + len: 5000 + of: + gen: int + min: 1 + max: 1000000000 + distinct: false + sorted: false + elemType: int + queries: + gen: array + len: 5000 + of: + gen: array + len: 2 + of: + gen: int + min: 0 + max: 4999 + distinct: false + sorted: true + distinct: false + sorted: false + - name: stress_maximum + seed: 505 + in: + arr: + gen: array + len: 30000 + of: + gen: int + min: 1 + max: 1000000000 + distinct: false + sorted: false + elemType: int + queries: + gen: array + len: 30000 + of: + gen: array + len: 2 + of: + gen: int + min: 0 + max: 29999 + distinct: false + sorted: true + distinct: false + sorted: false + - name: nonzero_minimum_values + in: + arr: [1, 1, 1, 1, 1, 1, 1] + queries: + - [0, 6] + - [0, 5] + - [1, 6] + - [3, 3] + - name: bit_boundary_values + in: + arr: [1, 1023, 1024, 1048575, 1048576, 1000000000] + queries: + - [0, 5] + - [1, 4] + - [2, 3] + - [5, 5] + - name: repeated_query_intervals + in: + arr: [73, 146, 219, 292, 365, 438, 511] + queries: + - [1, 5] + - [1, 5] + - [0, 6] + - [2, 4] + - [1, 5] + - name: stress_maximum_narrow_values + seed: 606 + in: + arr: + gen: array + len: 30000 + of: + gen: int + min: 1 + max: 3 + distinct: false + sorted: false + elemType: int + queries: + gen: array + len: 30000 + of: + gen: array + len: 2 + of: + gen: int + min: 0 + max: 29999 + distinct: false + sorted: true + distinct: false + sorted: false + - name: stress_maximum_high_values + seed: 707 + in: + arr: + gen: array + len: 30000 + of: + gen: int + min: 999000000 + max: 1000000000 + distinct: false + sorted: false + elemType: int + queries: + gen: array + len: 30000 + of: + gen: array + len: 2 + of: + gen: int + min: 0 + max: 29999 + distinct: false + sorted: true + distinct: false + sorted: false diff --git a/tests/1001-1500/1310. xor-queries-of-a-subarray/sol.cpp b/tests/1001-1500/1310. xor-queries-of-a-subarray/sol.cpp new file mode 100644 index 00000000..18241fda --- /dev/null +++ b/tests/1001-1500/1310. xor-queries-of-a-subarray/sol.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + vector xorQueries(vector& arr, vector>& queries) { + int n = arr.size(); + vector prefix(n + 1, 0); + for (int i = 0; i < n; i++) { + prefix[i + 1] = prefix[i] ^ arr[i]; + } + vector ans; + ans.reserve(queries.size()); + for (auto& q : queries) { + int a = q[0], b = q[1]; + ans.push_back(prefix[b + 1] ^ prefix[a]); + } + return ans; + } +}; diff --git a/tests/1001-1500/1310. xor-queries-of-a-subarray/sol.cs b/tests/1001-1500/1310. xor-queries-of-a-subarray/sol.cs new file mode 100644 index 00000000..8e17c432 --- /dev/null +++ b/tests/1001-1500/1310. xor-queries-of-a-subarray/sol.cs @@ -0,0 +1,15 @@ +public class Solution { + public int[] XorQueries(int[] arr, int[][] queries) { + int n = arr.Length; + int[] prefix = new int[n + 1]; + for (int i = 0; i < n; i++) { + prefix[i + 1] = prefix[i] ^ arr[i]; + } + int[] ans = new int[queries.Length]; + for (int i = 0; i < queries.Length; i++) { + int a = queries[i][0], b = queries[i][1]; + ans[i] = prefix[b + 1] ^ prefix[a]; + } + return ans; + } +} diff --git a/tests/1001-1500/1310. xor-queries-of-a-subarray/sol.dart b/tests/1001-1500/1310. xor-queries-of-a-subarray/sol.dart new file mode 100644 index 00000000..db0445ab --- /dev/null +++ b/tests/1001-1500/1310. xor-queries-of-a-subarray/sol.dart @@ -0,0 +1,10 @@ +class Solution { + List xorQueries(List arr, List> queries) { + int n = arr.length; + List prefix = List.filled(n + 1, 0); + for (int i = 0; i < n; i++) { + prefix[i + 1] = prefix[i] ^ arr[i]; + } + return queries.map((q) => prefix[q[1] + 1] ^ prefix[q[0]]).toList(); + } +} diff --git a/tests/1001-1500/1310. xor-queries-of-a-subarray/sol.go b/tests/1001-1500/1310. xor-queries-of-a-subarray/sol.go new file mode 100644 index 00000000..39ba14cd --- /dev/null +++ b/tests/1001-1500/1310. xor-queries-of-a-subarray/sol.go @@ -0,0 +1,13 @@ +func xorQueries(arr []int, queries [][]int) []int { + n := len(arr) + prefix := make([]int, n+1) + for i := 0; i < n; i++ { + prefix[i+1] = prefix[i] ^ arr[i] + } + ans := make([]int, len(queries)) + for i, q := range queries { + a, b := q[0], q[1] + ans[i] = prefix[b+1] ^ prefix[a] + } + return ans +} diff --git a/tests/1001-1500/1310. xor-queries-of-a-subarray/sol.java b/tests/1001-1500/1310. xor-queries-of-a-subarray/sol.java new file mode 100644 index 00000000..55b59496 --- /dev/null +++ b/tests/1001-1500/1310. xor-queries-of-a-subarray/sol.java @@ -0,0 +1,16 @@ +class Solution { + public int[] xorQueries(int[] arr, int[][] queries) { + int n = arr.length; + int[] prefix = new int[n + 1]; + prefix[0] = 0; + for (int i = 0; i < n; i++) { + prefix[i + 1] = prefix[i] ^ arr[i]; + } + int[] ans = new int[queries.length]; + for (int i = 0; i < queries.length; i++) { + int a = queries[i][0], b = queries[i][1]; + ans[i] = prefix[b + 1] ^ prefix[a]; + } + return ans; + } +} diff --git a/tests/1001-1500/1310. xor-queries-of-a-subarray/sol.kt b/tests/1001-1500/1310. xor-queries-of-a-subarray/sol.kt new file mode 100644 index 00000000..869e76b7 --- /dev/null +++ b/tests/1001-1500/1310. xor-queries-of-a-subarray/sol.kt @@ -0,0 +1,10 @@ +class Solution { + fun xorQueries(arr: IntArray, queries: Array): IntArray { + val n = arr.size + val prefix = IntArray(n + 1) + for (i in 0 until n) { + prefix[i + 1] = prefix[i] xor arr[i] + } + return queries.map { (a, b) -> prefix[b + 1] xor prefix[a] }.toIntArray() + } +} diff --git a/tests/1001-1500/1310. xor-queries-of-a-subarray/sol.py b/tests/1001-1500/1310. xor-queries-of-a-subarray/sol.py new file mode 100644 index 00000000..6ef3739a --- /dev/null +++ b/tests/1001-1500/1310. xor-queries-of-a-subarray/sol.py @@ -0,0 +1,7 @@ +class Solution: + def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]: + prefix = [0] + for num in arr: + prefix.append(prefix[-1] ^ num) + + return [prefix[b + 1] ^ prefix[a] for a, b in queries] diff --git a/tests/1001-1500/1310. xor-queries-of-a-subarray/sol.py2 b/tests/1001-1500/1310. xor-queries-of-a-subarray/sol.py2 new file mode 100644 index 00000000..ffb4ce8c --- /dev/null +++ b/tests/1001-1500/1310. xor-queries-of-a-subarray/sol.py2 @@ -0,0 +1,11 @@ +class Solution(object): + def xorQueries(self, arr, queries): + """ + :type arr: List[int] + :type queries: List[List[int]] + :rtype: List[int] + """ + prefix = [0] + for num in arr: + prefix.append(prefix[-1] ^ num) + return [prefix[b + 1] ^ prefix[a] for a, b in queries] diff --git a/tests/1001-1500/1310. xor-queries-of-a-subarray/sol.rb b/tests/1001-1500/1310. xor-queries-of-a-subarray/sol.rb new file mode 100644 index 00000000..060ca70f --- /dev/null +++ b/tests/1001-1500/1310. xor-queries-of-a-subarray/sol.rb @@ -0,0 +1,10 @@ +# @param {Integer[]} arr +# @param {Integer[][]} queries +# @return {Integer[]} +def xor_queries(arr, queries) + prefix = [0] + arr.each do |num| + prefix << (prefix[-1] ^ num) + end + queries.map { |a, b| prefix[b + 1] ^ prefix[a] } +end diff --git a/tests/1001-1500/1310. xor-queries-of-a-subarray/sol.rs b/tests/1001-1500/1310. xor-queries-of-a-subarray/sol.rs new file mode 100644 index 00000000..15d9c3e3 --- /dev/null +++ b/tests/1001-1500/1310. xor-queries-of-a-subarray/sol.rs @@ -0,0 +1,17 @@ +impl Solution { + pub fn xor_queries(arr: Vec, queries: Vec>) -> Vec { + let n = arr.len(); + let mut prefix = vec![0; n + 1]; + for i in 0..n { + prefix[i + 1] = prefix[i] ^ arr[i]; + } + queries + .iter() + .map(|q| { + let a = q[0] as usize; + let b = q[1] as usize; + prefix[b + 1] ^ prefix[a] + }) + .collect() + } +} diff --git a/tests/1001-1500/1310. xor-queries-of-a-subarray/sol.swift b/tests/1001-1500/1310. xor-queries-of-a-subarray/sol.swift new file mode 100644 index 00000000..5ccc0f47 --- /dev/null +++ b/tests/1001-1500/1310. xor-queries-of-a-subarray/sol.swift @@ -0,0 +1,10 @@ +class Solution { + func xorQueries(_ arr: [Int], _ queries: [[Int]]) -> [Int] { + let n = arr.count + var prefix = [Int](repeating: 0, count: n + 1) + for i in 0.. prefix[b + 1] ^ prefix[a]); +} diff --git a/tests/1001-1500/1311. get-watched-videos-by-your-friends/manifest.yaml b/tests/1001-1500/1311. get-watched-videos-by-your-friends/manifest.yaml new file mode 100644 index 00000000..18c88110 --- /dev/null +++ b/tests/1001-1500/1311. get-watched-videos-by-your-friends/manifest.yaml @@ -0,0 +1,983 @@ +entry: + id: 1311 + title: get-watched-videos-by-your-friends + params: + watchedVideos: + type: array + items: + type: array + items: + type: string + friends: + type: array + items: + type: array + items: + type: int + id: + type: int + level: + type: int + call: + cpp: "Solution().watchedVideosByFriends({watchedVideos}, {friends}, {id}, {level})" + rust: "Solution::watched_videos_by_friends({watchedVideos}, {friends}, {id}, {level})" + python3: "Solution().watchedVideosByFriends({watchedVideos}, {friends}, {id}, {level})" + python2: "Solution().watchedVideosByFriends({watchedVideos}, {friends}, {id}, {level})" + ruby: "watched_videos_by_friends({watchedVideos}, {friends}, {id}, {level})" + java: "new Solution().watchedVideosByFriends({watchedVideos}, {friends}, {id}, {level})" + csharp: "new Solution().WatchedVideosByFriends({watchedVideos}, {friends}, {id}, {level})" + kotlin: "Solution().watchedVideosByFriends({watchedVideos}, {friends}, {id}, {level})" + go: "watchedVideosByFriends({watchedVideos}, {friends}, {id}, {level})" + dart: "Solution().watchedVideosByFriends({watchedVideos}, {friends}, {id}, {level})" + swift: "Solution().watchedVideosByFriends({watchedVideos}, {friends}, {id}, {level})" + typescript: "watchedVideosByFriends({watchedVideos}, {friends}, {id}, {level})" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().watchedVideosByFriends(watchedVideos, friends, id, level, {result})" + checker: | + class Checker: + def watchedVideosByFriends(self, watchedVideos, friends, ident, level, result): + from collections import Counter, deque + seen = {ident} + queue = deque([(ident, 0)]) + people = [] + while queue: + person, distance = queue.popleft() + if distance == level: + people.append(person) + continue + for friend in friends[person]: + if friend not in seen: + seen.add(friend) + queue.append((friend, distance + 1)) + frequencies = Counter( + video for person in people for video in watchedVideos[person] + ) + return result == sorted(frequencies, key=lambda video: (frequencies[video], video)) +seed: 1311 +tests: + - name: example_level_one + in: + watchedVideos: + - ["A", "B"] + - ["C"] + - ["B", "C"] + - ["D"] + friends: + - [1, 2] + - [0, 3] + - [0, 3] + - [1, 2] + id: 0 + level: 1 + out: ["B", "C"] + - name: example_level_two + in: + watchedVideos: + - ["A", "B"] + - ["C"] + - ["B", "C"] + - ["D"] + friends: + - [1, 2] + - [0, 3] + - [0, 3] + - [1, 2] + id: 0 + level: 2 + out: ["D"] + - name: minimum_pair + in: + watchedVideos: + - ["self"] + - ["friend"] + friends: + - [1] + - [0] + id: 0 + level: 1 + out: ["friend"] + - name: pair_unreachable_level + in: + watchedVideos: + - ["self"] + - ["friend"] + friends: + - [1] + - [0] + id: 1 + level: 2 + out: [] + - name: line_distance_three + in: + watchedVideos: + - ["a"] + - ["b"] + - ["c"] + - ["d"] + friends: + - [1] + - [0, 2] + - [1, 3] + - [2] + id: 0 + level: 3 + out: ["d"] + - name: line_middle_two_sides + in: + watchedVideos: + - ["z"] + - ["b"] + - ["m"] + - ["a"] + - ["q"] + friends: + - [1] + - [0, 2] + - [1, 3] + - [2, 4] + - [3] + id: 2 + level: 2 + out: ["q", "z"] + - name: star_frequency_then_alpha + in: + watchedVideos: + - ["root"] + - ["z", "a"] + - ["a", "m"] + - ["m", "m"] + friends: + - [1, 2, 3] + - [0] + - [0] + - [0] + id: 0 + level: 1 + out: ["z", "a", "m"] + - name: duplicate_within_person + in: + watchedVideos: + - ["root"] + - ["x", "x", "b"] + - ["b", "c"] + friends: + - [1, 2] + - [0] + - [0] + id: 0 + level: 1 + out: ["c", "b", "x"] + - name: alphabetic_equal_frequencies + in: + watchedVideos: + - ["root"] + - ["z"] + - ["aa"] + - ["m"] + friends: + - [1, 2, 3] + - [0] + - [0] + - [0] + id: 0 + level: 1 + out: ["aa", "m", "z"] + - name: triangle_exact_shortest_path + in: + watchedVideos: + - ["a"] + - ["b"] + - ["c"] + friends: + - [1, 2] + - [0, 2] + - [0, 1] + id: 0 + level: 2 + out: [] + - name: diamond_shared_destination + in: + watchedVideos: + - ["r"] + - ["b"] + - ["c"] + - ["goal", "goal"] + friends: + - [1, 2] + - [0, 3] + - [0, 3] + - [1, 2] + id: 0 + level: 2 + out: ["goal"] + - name: cycle_opposite_vertex + in: + watchedVideos: + - ["v0"] + - ["v1"] + - ["v2"] + - ["v3"] + - ["v4"] + - ["v5"] + friends: + - [1, 5] + - [0, 2] + - [1, 3] + - [2, 4] + - [3, 5] + - [4, 0] + id: 0 + level: 3 + out: ["v3"] + - name: disconnected_component + in: + watchedVideos: + - ["a"] + - ["b"] + - ["c"] + - ["d"] + - ["e"] + friends: + - [1] + - [0] + - [3, 4] + - [2, 4] + - [2, 3] + id: 0 + level: 2 + out: [] + - name: disconnected_start_component + in: + watchedVideos: + - ["a"] + - ["b"] + - ["c"] + - ["d"] + - ["e"] + friends: + - [1] + - [0] + - [3, 4] + - [2, 4] + - [2, 3] + id: 2 + level: 1 + out: ["d", "e"] + - name: start_not_zero + in: + watchedVideos: + - ["a"] + - ["b", "b"] + - ["c"] + - ["d", "a"] + friends: + - [1] + - [0, 2] + - [1, 3] + - [2] + id: 3 + level: 2 + out: ["b"] + - name: two_layer_branch + in: + watchedVideos: + - ["r"] + - ["p"] + - ["q"] + - ["z", "a"] + - ["a", "b"] + - ["b", "b"] + friends: + - [1, 2] + - [0, 3, 4] + - [0, 5] + - [1] + - [1] + - [2] + id: 0 + level: 2 + out: ["z", "a", "b"] + - name: levels_stop_expansion + in: + watchedVideos: + - ["r"] + - ["one"] + - ["two"] + - ["three"] + friends: + - [1] + - [0, 2] + - [1, 3] + - [2] + id: 0 + level: 1 + out: ["one"] + - name: complete_graph_level_one + in: + watchedVideos: + - ["r"] + - ["d"] + - ["c"] + - ["b"] + - ["a"] + friends: + - [1, 2, 3, 4] + - [0, 2, 3, 4] + - [0, 1, 3, 4] + - [0, 1, 2, 4] + - [0, 1, 2, 3] + id: 0 + level: 1 + out: ["a", "b", "c", "d"] + - name: complete_graph_level_two_empty + in: + watchedVideos: + - ["r"] + - ["d"] + - ["c"] + - ["b"] + - ["a"] + friends: + - [1, 2, 3, 4] + - [0, 2, 3, 4] + - [0, 1, 3, 4] + - [0, 1, 2, 4] + - [0, 1, 2, 3] + id: 4 + level: 2 + out: [] + - name: eight_node_tree_level_three + in: + watchedVideos: + - ["r"] + - ["one"] + - ["two"] + - ["aa"] + - ["zz"] + - ["m"] + - ["aa"] + - ["m"] + friends: + - [1, 2] + - [0, 3, 4] + - [0, 5] + - [1, 6] + - [1] + - [2, 7] + - [3] + - [5] + id: 0 + level: 3 + out: ["aa", "m"] + - name: lexicographic_case_sensitive + in: + watchedVideos: + - ["root"] + - ["a"] + - ["A"] + - ["Z"] + friends: + - [1, 2, 3] + - [0] + - [0] + - [0] + id: 0 + level: 1 + out: ["A", "Z", "a"] + - name: max_name_length + in: + watchedVideos: + - ["root"] + - ["abcdefgh"] + - ["abcdefgz"] + friends: + - [1, 2] + - [0] + - [0] + id: 0 + level: 1 + out: ["abcdefgh", "abcdefgz"] + - name: repeated_across_people + in: + watchedVideos: + - ["r"] + - ["x", "y"] + - ["x", "z"] + - ["x", "y"] + friends: + - [1, 2, 3] + - [0] + - [0] + - [0] + id: 0 + level: 1 + out: ["z", "y", "x"] + - name: multiple_videos_each_target + in: + watchedVideos: + - ["r"] + - ["p", "q", "r"] + - ["q", "s", "t"] + friends: + - [1, 2] + - [0] + - [0] + id: 0 + level: 1 + out: ["p", "r", "s", "t", "q"] + - name: shortcut_changes_level + in: + watchedVideos: + - ["r"] + - ["one"] + - ["two"] + - ["three"] + - ["four"] + friends: + - [1, 4] + - [0, 2] + - [1, 3] + - [2, 4] + - [0, 3] + id: 0 + level: 2 + out: ["three", "two"] + - name: start_leaf_in_tree + in: + watchedVideos: + - ["a"] + - ["b"] + - ["c"] + - ["d"] + - ["e"] + - ["f"] + friends: + - [1] + - [0, 2, 3] + - [1] + - [1, 4, 5] + - [3] + - [3] + id: 4 + level: 3 + out: ["a", "c"] + - name: long_line_unreachable_depth + in: + watchedVideos: + - ["0"] + - ["1"] + - ["2"] + - ["3"] + - ["4"] + - ["5"] + - ["6"] + friends: + - [1] + - [0, 2] + - [1, 3] + - [2, 4] + - [3, 5] + - [4, 6] + - [5] + id: 3 + level: 4 + out: [] + - name: large_line_twenty_level_nineteen + in: + watchedVideos: + - ["n00"] + - ["n01"] + - ["n02"] + - ["n03"] + - ["n04"] + - ["n05"] + - ["n06"] + - ["n07"] + - ["n08"] + - ["n09"] + - ["n10"] + - ["n11"] + - ["n12"] + - ["n13"] + - ["n14"] + - ["n15"] + - ["n16"] + - ["n17"] + - ["n18"] + - ["target"] + friends: + - [1] + - [0, 2] + - [1, 3] + - [2, 4] + - [3, 5] + - [4, 6] + - [5, 7] + - [6, 8] + - [7, 9] + - [8, 10] + - [9, 11] + - [10, 12] + - [11, 13] + - [12, 14] + - [13, 15] + - [14, 16] + - [15, 17] + - [16, 18] + - [17, 19] + - [18] + id: 0 + level: 19 + out: ["target"] + - name: large_star_twenty_four_frequency + in: + watchedVideos: + - ["root"] + - ["b", "shared"] + - ["a", "shared"] + - ["c", "shared"] + - ["d", "shared"] + - ["e", "shared"] + - ["f", "shared"] + - ["g", "shared"] + - ["h", "shared"] + - ["i", "shared"] + - ["j", "shared"] + - ["k", "shared"] + - ["l", "shared"] + - ["m", "shared"] + - ["n", "shared"] + - ["o", "shared"] + - ["p", "shared"] + - ["q", "shared"] + - ["r", "shared"] + - ["s", "shared"] + - ["t", "shared"] + - ["u", "shared"] + - ["v", "shared"] + - ["w", "shared"] + friends: + - [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + ] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + id: 0 + level: 1 + out: + [ + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + "q", + "r", + "s", + "t", + "u", + "v", + "w", + "shared", + ] + - name: large_binary_tree_level_four + in: + watchedVideos: + - ["r"] + - ["x1"] + - ["x2"] + - ["x3"] + - ["x4"] + - ["x5"] + - ["x6"] + - ["x7"] + - ["x8"] + - ["x9"] + - ["x10"] + - ["x11"] + - ["x12"] + - ["x13"] + - ["x14"] + - ["z", "even"] + - ["a", "odd"] + - ["z", "even"] + - ["a", "odd"] + - ["z", "even"] + - ["a", "odd"] + - ["z", "even"] + - ["a", "odd"] + - ["z", "even"] + - ["a", "odd"] + - ["z", "even"] + - ["a", "odd"] + - ["z", "even"] + - ["a", "odd"] + - ["z", "even"] + - ["a", "odd"] + friends: + - [1, 2] + - [0, 3, 4] + - [0, 5, 6] + - [1, 7, 8] + - [1, 9, 10] + - [2, 11, 12] + - [2, 13, 14] + - [3, 15, 16] + - [3, 17, 18] + - [4, 19, 20] + - [4, 21, 22] + - [5, 23, 24] + - [5, 25, 26] + - [6, 27, 28] + - [6, 29, 30] + - [7] + - [7] + - [8] + - [8] + - [9] + - [9] + - [10] + - [10] + - [11] + - [11] + - [12] + - [12] + - [13] + - [13] + - [14] + - [14] + id: 0 + level: 4 + out: ["a", "even", "odd", "z"] + - name: large_ladder_cross_edges + in: + watchedVideos: + - ["r0"] + - ["r1"] + - ["r2"] + - ["r3"] + - ["r4"] + - ["r5"] + - ["r6"] + - ["r7"] + - ["r8"] + - ["r9"] + - ["l0"] + - ["l1"] + - ["l2"] + - ["l3"] + - ["l4"] + - ["l5"] + - ["l6"] + - ["l7"] + - ["l8"] + - ["goal"] + friends: + - [1, 10] + - [0, 2, 11] + - [1, 3, 12] + - [2, 4, 13] + - [3, 5, 14] + - [4, 6, 15] + - [5, 7, 16] + - [6, 8, 17] + - [7, 9, 18] + - [8, 19] + - [0, 11] + - [10, 12, 1] + - [11, 13, 2] + - [12, 14, 3] + - [13, 15, 4] + - [14, 16, 5] + - [15, 17, 6] + - [16, 18, 7] + - [17, 19, 8] + - [18, 9] + id: 0 + level: 10 + out: ["goal"] + - name: large_three_components + in: + watchedVideos: + - ["a0"] + - ["a1"] + - ["a2"] + - ["a3"] + - ["a4"] + - ["a5"] + - ["a6"] + - ["a7"] + - ["b0"] + - ["b1"] + - ["b2"] + - ["b3"] + - ["b4"] + - ["b5"] + - ["b6"] + - ["b7"] + - ["c0"] + - ["c1"] + - ["c2"] + - ["c3"] + - ["c4"] + - ["c5"] + - ["c6"] + - ["c7"] + friends: + - [1, 7] + - [0, 2] + - [1, 3] + - [2, 4] + - [3, 5] + - [4, 6] + - [5, 7] + - [6, 0] + - [9, 15] + - [8, 10] + - [9, 11] + - [10, 12] + - [11, 13] + - [12, 14] + - [13, 15] + - [14, 8] + - [17, 23] + - [16, 18] + - [17, 19] + - [18, 20] + - [19, 21] + - [20, 22] + - [21, 23] + - [22, 16] + id: 8 + level: 4 + out: ["b4"] + - name: large_dense_bipartite_level_two + in: + watchedVideos: + - ["left0"] + - ["left1"] + - ["left2"] + - ["left3"] + - ["left4"] + - ["left5"] + - ["right0"] + - ["right1"] + - ["right2"] + - ["right3"] + - ["right4"] + - ["right5"] + friends: + - [6, 7, 8, 9, 10, 11] + - [6, 7, 8, 9, 10, 11] + - [6, 7, 8, 9, 10, 11] + - [6, 7, 8, 9, 10, 11] + - [6, 7, 8, 9, 10, 11] + - [6, 7, 8, 9, 10, 11] + - [0, 1, 2, 3, 4, 5] + - [0, 1, 2, 3, 4, 5] + - [0, 1, 2, 3, 4, 5] + - [0, 1, 2, 3, 4, 5] + - [0, 1, 2, 3, 4, 5] + - [0, 1, 2, 3, 4, 5] + id: 0 + level: 2 + out: ["left1", "left2", "left3", "left4", "left5"] + - name: ten_node_cycle_level_four + in: + watchedVideos: + - ["v0"] + - ["v1"] + - ["v2"] + - ["v3"] + - ["v4"] + - ["v5"] + - ["v6"] + - ["v7"] + - ["v8"] + - ["v9"] + friends: + - [1, 9] + - [0, 2] + - [1, 3] + - [2, 4] + - [3, 5] + - [4, 6] + - [5, 7] + - [6, 8] + - [7, 9] + - [8, 0] + id: 0 + level: 4 + out: ["v4", "v6"] + - name: nine_node_hub_spokes + in: + watchedVideos: + - ["hub"] + - ["x1"] + - ["x2"] + - ["x3"] + - ["x4"] + - ["x5"] + - ["x6"] + - ["x7"] + - ["x8"] + friends: + - [1, 2, 3, 4] + - [0, 5] + - [0, 6] + - [0, 7] + - [0, 8] + - [1] + - [2] + - [3] + - [4] + id: 0 + level: 2 + out: ["x5", "x6", "x7", "x8"] + - name: levels_from_internal_cycle_vertex + in: + watchedVideos: + - ["a"] + - ["b"] + - ["c"] + - ["d"] + - ["e"] + - ["f"] + - ["g"] + friends: + - [1, 6] + - [0, 2] + - [1, 3] + - [2, 4] + - [3, 5] + - [4, 6] + - [5, 0] + id: 3 + level: 3 + out: ["a", "g"] + - name: four_way_frequency_ties + in: + watchedVideos: + - ["root"] + - ["cc", "bb"] + - ["aa", "bb"] + - ["aa", "dd"] + - ["cc", "dd"] + friends: + - [1, 2, 3, 4] + - [0] + - [0] + - [0] + - [0] + id: 0 + level: 1 + out: ["aa", "bb", "cc", "dd"] + - name: target_people_have_overlapping_lists + in: + watchedVideos: + - ["root"] + - ["bridge"] + - ["bridge"] + - ["u", "v", "v"] + - ["u", "w"] + - ["v", "w"] + friends: + - [1, 2] + - [0, 3, 4] + - [0, 5] + - [1] + - [1] + - [2] + id: 0 + level: 2 + out: ["u", "w", "v"] + - name: exact_distance_with_back_edges + in: + watchedVideos: + - ["r"] + - ["a"] + - ["b"] + - ["c"] + - ["d"] + - ["e"] + friends: + - [1] + - [0, 2, 3] + - [1, 4] + - [1, 4] + - [2, 3, 5] + - [4] + id: 0 + level: 3 + out: ["d"] + - name: single_target_many_distinct + in: + watchedVideos: + - ["r"] + - ["h", "g", "f", "e", "d", "c", "b", "a"] + friends: + - [1] + - [0] + id: 0 + level: 1 + out: ["a", "b", "c", "d", "e", "f", "g", "h"] diff --git a/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.cpp b/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.cpp new file mode 100644 index 00000000..613cf05a --- /dev/null +++ b/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.cpp @@ -0,0 +1,50 @@ +class Solution { +public: + vector watchedVideosByFriends(vector>& watchedVideos, vector>& friends, int id, int level) { + int n = friends.size(); + vector visited(n, false); + queue> q; + q.push({id, 0}); + visited[id] = true; + + vector targetPeople; + + while (!q.empty()) { + auto [person, dist] = q.front(); + q.pop(); + + if (dist == level) { + targetPeople.push_back(person); + continue; + } + + for (int f : friends[person]) { + if (!visited[f]) { + visited[f] = true; + q.push({f, dist + 1}); + } + } + } + + unordered_map freq; + for (int p : targetPeople) { + for (const string& vid : watchedVideos[p]) { + freq[vid]++; + } + } + + vector result; + for (const auto& [vid, _] : freq) { + result.push_back(vid); + } + + sort(result.begin(), result.end(), [&](const string& a, const string& b) { + if (freq[a] != freq[b]) { + return freq[a] < freq[b]; + } + return a < b; + }); + + return result; + } +}; diff --git a/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.cs b/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.cs new file mode 100644 index 00000000..b41194b3 --- /dev/null +++ b/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.cs @@ -0,0 +1,47 @@ +public class Solution { + public IList WatchedVideosByFriends(string[][] watchedVideos, int[][] friends, int id, int level) { + int n = friends.Length; + bool[] visited = new bool[n]; + Queue<(int, int)> q = new Queue<(int, int)>(); + q.Enqueue((id, 0)); + visited[id] = true; + + List targetPeople = new List(); + + while (q.Count > 0) { + var (person, dist) = q.Dequeue(); + + if (dist == level) { + targetPeople.Add(person); + continue; + } + + foreach (int f in friends[person]) { + if (!visited[f]) { + visited[f] = true; + q.Enqueue((f, dist + 1)); + } + } + } + + Dictionary freq = new Dictionary(); + foreach (int p in targetPeople) { + foreach (string vid in watchedVideos[p]) { + if (freq.ContainsKey(vid)) { + freq[vid]++; + } else { + freq[vid] = 1; + } + } + } + + List result = new List(freq.Keys); + result.Sort((a, b) => { + int cmp = freq[a].CompareTo(freq[b]); + if (cmp != 0) return cmp; + return string.CompareOrdinal(a, b); + }); + + return result; + } +} diff --git a/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.dart b/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.dart new file mode 100644 index 00000000..fcee9bfe --- /dev/null +++ b/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.dart @@ -0,0 +1,45 @@ +class Solution { + List watchedVideosByFriends(List> watchedVideos, List> friends, int id, int level) { + int n = friends.length; + List visited = List.filled(n, false); + Queue> q = Queue(); + q.add([id, 0]); + visited[id] = true; + + List targetPeople = []; + + while (q.isNotEmpty) { + List curr = q.removeFirst(); + int person = curr[0]; + int dist = curr[1]; + + if (dist == level) { + targetPeople.add(person); + continue; + } + + for (int f in friends[person]) { + if (!visited[f]) { + visited[f] = true; + q.add([f, dist + 1]); + } + } + } + + Map freq = {}; + for (int p in targetPeople) { + for (String vid in watchedVideos[p]) { + freq[vid] = (freq[vid] ?? 0) + 1; + } + } + + List result = freq.keys.toList(); + result.sort((a, b) { + int cmp = freq[a]!.compareTo(freq[b]!); + if (cmp != 0) return cmp; + return a.compareTo(b); + }); + + return result; + } +} diff --git a/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.go b/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.go new file mode 100644 index 00000000..16130d3c --- /dev/null +++ b/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.go @@ -0,0 +1,47 @@ +func watchedVideosByFriends(watchedVideos [][]string, friends [][]int, id int, level int) []string { + n := len(friends) + visited := make([]bool, n) + q := [][]int{{id, 0}} + visited[id] = true + + targetPeople := []int{} + + for len(q) > 0 { + person := q[0][0] + dist := q[0][1] + q = q[1:] + + if dist == level { + targetPeople = append(targetPeople, person) + continue + } + + for _, f := range friends[person] { + if !visited[f] { + visited[f] = true + q = append(q, []int{f, dist + 1}) + } + } + } + + freq := make(map[string]int) + for _, p := range targetPeople { + for _, vid := range watchedVideos[p] { + freq[vid]++ + } + } + + result := make([]string, 0, len(freq)) + for k := range freq { + result = append(result, k) + } + + sort.Slice(result, func(i, j int) bool { + if freq[result[i]] != freq[result[j]] { + return freq[result[i]] < freq[result[j]] + } + return result[i] < result[j] + }) + + return result +} diff --git a/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.java b/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.java new file mode 100644 index 00000000..2006ad03 --- /dev/null +++ b/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.java @@ -0,0 +1,45 @@ +class Solution { + public List watchedVideosByFriends(String[][] watchedVideos, int[][] friends, int id, int level) { + int n = friends.length; + boolean[] visited = new boolean[n]; + Queue q = new LinkedList<>(); + q.offer(new int[]{id, 0}); + visited[id] = true; + + List targetPeople = new ArrayList<>(); + + while (!q.isEmpty()) { + int[] curr = q.poll(); + int person = curr[0]; + int dist = curr[1]; + + if (dist == level) { + targetPeople.add(person); + continue; + } + + for (int f : friends[person]) { + if (!visited[f]) { + visited[f] = true; + q.offer(new int[]{f, dist + 1}); + } + } + } + + Map freq = new HashMap<>(); + for (int p : targetPeople) { + for (String vid : watchedVideos[p]) { + freq.put(vid, freq.getOrDefault(vid, 0) + 1); + } + } + + List result = new ArrayList<>(freq.keySet()); + result.sort((a, b) -> { + int cmp = freq.get(a).compareTo(freq.get(b)); + if (cmp != 0) return cmp; + return a.compareTo(b); + }); + + return result; + } +} diff --git a/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.kt b/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.kt new file mode 100644 index 00000000..bd63e900 --- /dev/null +++ b/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.kt @@ -0,0 +1,36 @@ +class Solution { + fun watchedVideosByFriends(watchedVideos: Array>, friends: Array, id: Int, level: Int): List { + val n = friends.size + val visited = BooleanArray(n) + val q: java.util.Queue> = java.util.LinkedList() + q.offer(Pair(id, 0)) + visited[id] = true + + val targetPeople = mutableListOf() + + while (q.isNotEmpty()) { + val (person, dist) = q.poll() + + if (dist == level) { + targetPeople.add(person) + continue + } + + for (f in friends[person]) { + if (!visited[f]) { + visited[f] = true + q.offer(Pair(f, dist + 1)) + } + } + } + + val freq = mutableMapOf() + for (p in targetPeople) { + for (vid in watchedVideos[p]) { + freq[vid] = freq.getOrDefault(vid, 0) + 1 + } + } + + return freq.keys.sortedWith(compareBy { freq[it] }.thenBy { it }) + } +} diff --git a/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.py b/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.py new file mode 100644 index 00000000..a5453d24 --- /dev/null +++ b/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.py @@ -0,0 +1,38 @@ +from collections import deque, Counter +from typing import List + + +class Solution: + def watchedVideosByFriends( + self, + watchedVideos: List[List[str]], + friends: List[List[int]], + id: int, + level: int, + ) -> List[str]: + n = len(friends) + + visited = [False] * n + q = deque([(id, 0)]) + visited[id] = True + + target_people = [] + + while q: + person, dist = q.popleft() + + if dist == level: + target_people.append(person) + continue + + for f in friends[person]: + if not visited[f]: + visited[f] = True + q.append((f, dist + 1)) + + freq = Counter() + for p in target_people: + for vid in watchedVideos[p]: + freq[vid] += 1 + + return sorted(freq.keys(), key=lambda x: (freq[x], x)) diff --git a/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.py2 b/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.py2 new file mode 100644 index 00000000..0ffba22e --- /dev/null +++ b/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.py2 @@ -0,0 +1,36 @@ +class Solution(object): + def watchedVideosByFriends(self, watchedVideos, friends, id, level): + """ + :type watchedVideos: List[List[str]] + :type friends: List[List[int]] + :type id: int + :type level: int + :rtype: List[str] + """ + from collections import deque, Counter + + n = len(friends) + visited = [False] * n + q = deque([(id, 0)]) + visited[id] = True + + target_people = [] + + while q: + person, dist = q.popleft() + + if dist == level: + target_people.append(person) + continue + + for f in friends[person]: + if not visited[f]: + visited[f] = True + q.append((f, dist + 1)) + + freq = Counter() + for p in target_people: + for vid in watchedVideos[p]: + freq[vid] += 1 + + return sorted(freq.keys(), key=lambda x: (freq[x], x)) diff --git a/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.rb b/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.rb new file mode 100644 index 00000000..885f5894 --- /dev/null +++ b/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.rb @@ -0,0 +1,38 @@ +# @param {String[][]} watched_videos +# @param {Integer[][]} friends +# @param {Integer} id +# @param {Integer} level +# @return {String[]} +def watched_videos_by_friends(watched_videos, friends, id, level) + n = friends.size + visited = Array.new(n, false) + q = [[id, 0]] + visited[id] = true + + target_people = [] + + until q.empty? + person, dist = q.shift + + if dist == level + target_people << person + next + end + + friends[person].each do |f| + unless visited[f] + visited[f] = true + q << [f, dist + 1] + end + end + end + + freq = Hash.new(0) + target_people.each do |p| + watched_videos[p].each do |vid| + freq[vid] += 1 + end + end + + freq.keys.sort_by { |x| [freq[x], x] } +end diff --git a/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.rs b/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.rs new file mode 100644 index 00000000..889500ba --- /dev/null +++ b/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.rs @@ -0,0 +1,47 @@ +impl Solution { + pub fn watched_videos_by_friends(watched_videos: Vec>, friends: Vec>, id: i32, level: i32) -> Vec { + use std::collections::{VecDeque, HashMap}; + + let n = friends.len(); + let mut visited = vec![false; n]; + let mut q = VecDeque::new(); + q.push_back((id as usize, 0)); + visited[id as usize] = true; + + let mut target_people = Vec::new(); + + while let Some((person, dist)) = q.pop_front() { + if dist == level { + target_people.push(person); + continue; + } + + for &f in &friends[person] { + let f = f as usize; + if !visited[f] { + visited[f] = true; + q.push_back((f, dist + 1)); + } + } + } + + let mut freq: HashMap<&String, i32> = HashMap::new(); + for p in &target_people { + for vid in &watched_videos[*p] { + *freq.entry(vid).or_insert(0) += 1; + } + } + + let mut result: Vec<&String> = freq.keys().cloned().collect(); + result.sort_by(|a, b| { + let cmp = freq[a].cmp(&freq[b]); + if cmp != std::cmp::Ordering::Equal { + cmp + } else { + a.cmp(b) + } + }); + + result.into_iter().cloned().collect() + } +} diff --git a/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.swift b/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.swift new file mode 100644 index 00000000..06e64148 --- /dev/null +++ b/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.swift @@ -0,0 +1,41 @@ +class Solution { + func watchedVideosByFriends(_ watchedVideos: [[String]], _ friends: [[Int]], _ id: Int, _ level: Int) -> [String] { + let n = friends.count + var visited = [Bool](repeating: false, count: n) + var q = [(Int, Int)]() + q.append((id, 0)) + visited[id] = true + + var targetPeople = [Int]() + + while !q.isEmpty { + let (person, dist) = q.removeFirst() + + if dist == level { + targetPeople.append(person) + continue + } + + for f in friends[person] { + if !visited[f] { + visited[f] = true + q.append((f, dist + 1)) + } + } + } + + var freq = [String: Int]() + for p in targetPeople { + for vid in watchedVideos[p] { + freq[vid, default: 0] += 1 + } + } + + return freq.keys.sorted { + if freq[$0]! != freq[$1]! { + return freq[$0]! < freq[$1]! + } + return $0 < $1 + } + } +} diff --git a/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.ts b/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.ts new file mode 100644 index 00000000..2a18524f --- /dev/null +++ b/tests/1001-1500/1311. get-watched-videos-by-your-friends/sol.ts @@ -0,0 +1,43 @@ +function watchedVideosByFriends( + watchedVideos: string[][], + friends: number[][], + id: number, + level: number, +): string[] { + const n = friends.length; + const visited: boolean[] = new Array(n).fill(false); + const q: [number, number][] = [[id, 0]]; + visited[id] = true; + + const targetPeople: number[] = []; + + while (q.length > 0) { + const [person, dist] = q.shift()!; + + if (dist === level) { + targetPeople.push(person); + continue; + } + + for (const f of friends[person]) { + if (!visited[f]) { + visited[f] = true; + q.push([f, dist + 1]); + } + } + } + + const freq: { [key: string]: number } = {}; + for (const p of targetPeople) { + for (const vid of watchedVideos[p]) { + freq[vid] = (freq[vid] || 0) + 1; + } + } + + return Object.keys(freq).sort((a, b) => { + if (freq[a] !== freq[b]) { + return freq[a] - freq[b]; + } + return a < b ? -1 : a > b ? 1 : 0; + }); +} diff --git a/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/manifest.yaml b/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/manifest.yaml new file mode 100644 index 00000000..e40972a2 --- /dev/null +++ b/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/manifest.yaml @@ -0,0 +1,228 @@ +entry: + id: 1312 + title: "minimum-insertion-steps-to-make-a-string-palindrome" + 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: 1000 + memory_mb: 300 + +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 + dp = [0] * len(s) + for left in range(len(s) - 2, -1, -1): + diagonal = 0 + for right in range(left + 1, len(s)): + previous = dp[right] + if s[left] == s[right]: + dp[right] = diagonal + else: + dp[right] = min(dp[right], dp[right - 1]) + 1 + diagonal = previous + return result == dp[-1] + +seed: 131200 + +tests: + - name: "example_zzazz" + in: + s: "zzazz" + out: 0 + - name: "example_mbadm" + in: + s: "mbadm" + out: 2 + - name: "example_leetcode" + in: + s: "leetcode" + out: 5 + - name: "single_character" + in: + s: "a" + out: 0 + - name: "two_equal" + in: + s: "aa" + out: 0 + - name: "two_distinct" + in: + s: "ab" + out: 1 + - name: "three_palindrome" + in: + s: "aba" + out: 0 + - name: "three_distinct" + in: + s: "abc" + out: 2 + - name: "all_same" + in: + s: "aaaaaa" + out: 0 + - name: "all_distinct_four" + in: + s: "abcd" + out: 3 + - name: "even_palindrome" + in: + s: "abccba" + out: 0 + - name: "alternating_even" + in: + s: "ababab" + out: 1 + - name: "alternating_odd" + in: + s: "ababa" + out: 0 + - name: "near_palindrome" + in: + s: "abca" + out: 1 + - name: "cbbd_two_insertions" + in: + s: "cbbd" + out: 2 + - name: "bbbab_one_insertion" + in: + s: "bbbab" + out: 1 + - name: "embedded_palindrome" + in: + s: "agbdba" + out: 1 + - name: "banana" + in: + s: "banana" + out: 1 + - name: "google" + in: + s: "google" + out: 2 + - name: "aabb" + in: + s: "aabb" + out: 2 + - name: "paired_blocks" + in: + s: "aabbcc" + out: 4 + - name: "four_paired_blocks" + in: + s: "aabbccdd" + out: 6 + - name: "asymmetric_suffix" + in: + s: "abcdcbaq" + out: 1 + - name: "asymmetric_prefix" + in: + s: "qabcdcba" + out: 1 + - name: "abac" + in: + s: "abac" + out: 1 + - name: "cabba" + in: + s: "cabba" + out: 1 + - name: "caac_embedded" + in: + s: "bcaac" + out: 1 + - name: "double_center" + in: + s: "abcddc" + out: 2 + - name: "one_trailing_outlier" + in: + s: "aaaaab" + out: 1 + - name: "one_leading_outlier" + in: + s: "baaaaa" + out: 1 + - name: "long_odd_palindrome" + in: + s: "abcdedcba" + out: 0 + - name: "long_even_palindrome" + in: + s: "abcdefedcba" + out: 0 + - name: "interior_mismatch" + in: + s: "abxyba" + out: 1 + - name: "distinct_eight" + in: + s: "azbycxdw" + out: 7 + - name: "generated_large_binary" + seed: 131201 + in: + s: + gen: "str" + len: 80 + alphabet: "ab" + - name: "generated_large_ternary" + seed: 131202 + in: + s: + gen: "str" + len: 160 + alphabet: "abc" + - name: "generated_large_quaternary" + seed: 131203 + in: + s: + gen: "str" + len: 250 + alphabet: "abcd" + - name: "generated_large_alphabet" + seed: 131204 + in: + s: + gen: "str" + len: 400 + alphabet: "abcdefghij" + - name: "generated_near_maximum" + seed: 131205 + in: + s: + gen: "str" + len: 499 + alphabet: "abcde" + - name: "generated_maximum" + seed: 131206 + in: + s: + gen: "str" + len: 500 + alphabet: "abcdefghijklmnopqrstuvwxyz" diff --git a/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.cpp b/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.cpp new file mode 100644 index 00000000..35fa99e6 --- /dev/null +++ b/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int minInsertions(string s) { + int n = s.length(); + string s2 = s; + reverse(s2.begin(), s2.end()); + vector> dp(n + 1, vector(n + 1, 0)); + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= n; j++) { + if (s[i - 1] == s2[j - 1]) { + dp[i][j] = 1 + dp[i - 1][j - 1]; + } else { + dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); + } + } + } + return n - dp[n][n]; + } +}; diff --git a/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.cs b/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.cs new file mode 100644 index 00000000..21b3c99c --- /dev/null +++ b/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.cs @@ -0,0 +1,19 @@ +public class Solution { + public int MinInsertions(string s) { + int n = s.Length; + char[] arr = s.ToCharArray(); + Array.Reverse(arr); + string s2 = new string(arr); + int[,] dp = new int[n + 1, n + 1]; + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= n; j++) { + if (s[i - 1] == s2[j - 1]) { + dp[i, j] = 1 + dp[i - 1, j - 1]; + } else { + dp[i, j] = Math.Max(dp[i - 1, j], dp[i, j - 1]); + } + } + } + return n - dp[n, n]; + } +} diff --git a/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.dart b/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.dart new file mode 100644 index 00000000..c7681f4c --- /dev/null +++ b/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.dart @@ -0,0 +1,17 @@ +class Solution { + int minInsertions(String s) { + int n = s.length; + String s2 = s.split('').reversed.join(''); + List> dp = List.generate(n + 1, (_) => List.filled(n + 1, 0)); + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= n; j++) { + if (s[i - 1] == s2[j - 1]) { + dp[i][j] = 1 + dp[i - 1][j - 1]; + } else { + dp[i][j] = dp[i - 1][j] > dp[i][j - 1] ? dp[i - 1][j] : dp[i][j - 1]; + } + } + } + return n - dp[n][n]; + } +} diff --git a/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.go b/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.go new file mode 100644 index 00000000..1942588e --- /dev/null +++ b/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.go @@ -0,0 +1,26 @@ +func minInsertions(s string) int { + n := len(s) + s2 := reverse(s) + dp := make([][]int, n+1) + for i := range dp { + dp[i] = make([]int, n+1) + } + for i := 1; i <= n; i++ { + for j := 1; j <= n; j++ { + if s[i-1] == s2[j-1] { + dp[i][j] = 1 + dp[i-1][j-1] + } else { + dp[i][j] = max(dp[i-1][j], dp[i][j-1]) + } + } + } + return n - dp[n][n] +} + +func reverse(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) +} diff --git a/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.java b/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.java new file mode 100644 index 00000000..d694b86f --- /dev/null +++ b/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.java @@ -0,0 +1,17 @@ +class Solution { + public int minInsertions(String s) { + int n = s.length(); + String s2 = new StringBuilder(s).reverse().toString(); + int[][] dp = new int[n + 1][n + 1]; + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= n; j++) { + if (s.charAt(i - 1) == s2.charAt(j - 1)) { + dp[i][j] = 1 + dp[i - 1][j - 1]; + } else { + dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); + } + } + } + return n - dp[n][n]; + } +} diff --git a/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.kt b/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.kt new file mode 100644 index 00000000..dcfb471b --- /dev/null +++ b/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.kt @@ -0,0 +1,17 @@ +class Solution { + fun minInsertions(s: String): Int { + val n = s.length + val s2 = s.reversed() + val dp = Array(n + 1) { IntArray(n + 1) } + for (i in 1..n) { + for (j in 1..n) { + if (s[i - 1] == s2[j - 1]) { + dp[i][j] = 1 + dp[i - 1][j - 1] + } else { + dp[i][j] = maxOf(dp[i - 1][j], dp[i][j - 1]) + } + } + } + return n - dp[n][n] + } +} diff --git a/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.py b/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.py new file mode 100644 index 00000000..c4caf418 --- /dev/null +++ b/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.py @@ -0,0 +1,19 @@ +class Solution: + def minInsertions(self, s: str) -> int: + n = len(s) + s2 = s[::-1] # The exact reverse of the string + + # DP table to find the Longest Common Subsequence (LCS) + dp = [[0] * (n + 1) for _ in range(n + 1)] + + for i in range(1, n + 1): + for j in range(1, n + 1): + # If characters match, add 1 to the previous diagonal state + if s[i - 1] == s2[j - 1]: + dp[i][j] = 1 + dp[i - 1][j - 1] + # Otherwise, carry forward the best maximum state + else: + dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) + + # Total length minus the already symmetrical portion + return n - dp[n][n] diff --git a/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.py2 b/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.py2 new file mode 100644 index 00000000..993d761b --- /dev/null +++ b/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def minInsertions(self, s): + """ + :type s: str + :rtype: int + """ + n = len(s) + s2 = s[::-1] + dp = [[0] * (n + 1) for _ in range(n + 1)] + for i in range(1, n + 1): + for j in range(1, n + 1): + if s[i - 1] == s2[j - 1]: + dp[i][j] = 1 + dp[i - 1][j - 1] + else: + dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) + return n - dp[n][n] diff --git a/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.rb b/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.rb new file mode 100644 index 00000000..a063af10 --- /dev/null +++ b/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.rb @@ -0,0 +1,17 @@ +# @param {String} s +# @return {Integer} +def min_insertions(s) + n = s.length + s2 = s.reverse + dp = Array.new(n + 1) { Array.new(n + 1, 0) } + (1..n).each do |i| + (1..n).each do |j| + if s[i - 1] == s2[j - 1] + dp[i][j] = 1 + dp[i - 1][j - 1] + else + dp[i][j] = [dp[i - 1][j], dp[i][j - 1]].max + end + end + end + n - dp[n][n] +end diff --git a/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.rs b/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.rs new file mode 100644 index 00000000..1465d9ed --- /dev/null +++ b/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.rs @@ -0,0 +1,19 @@ +impl Solution { + pub fn min_insertions(s: String) -> i32 { + let n = s.len(); + let s2: String = s.chars().rev().collect(); + let s_bytes = s.as_bytes(); + let s2_bytes = s2.as_bytes(); + let mut dp = vec![vec![0; n + 1]; n + 1]; + for i in 1..=n { + for j in 1..=n { + if s_bytes[i - 1] == s2_bytes[j - 1] { + dp[i][j] = 1 + dp[i - 1][j - 1]; + } else { + dp[i][j] = dp[i - 1][j].max(dp[i][j - 1]); + } + } + } + (n - dp[n][n]) as i32 + } +} diff --git a/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.swift b/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.swift new file mode 100644 index 00000000..d581a588 --- /dev/null +++ b/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.swift @@ -0,0 +1,19 @@ +class Solution { + func minInsertions(_ s: String) -> Int { + let n = s.count + let s2 = String(s.reversed()) + let sArr = Array(s) + let s2Arr = Array(s2) + var dp = Array(repeating: Array(repeating: 0, count: n + 1), count: n + 1) + for i in 1...n { + for j in 1...n { + if sArr[i - 1] == s2Arr[j - 1] { + dp[i][j] = 1 + dp[i - 1][j - 1] + } else { + dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) + } + } + } + return n - dp[n][n] + } +} diff --git a/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.ts b/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.ts new file mode 100644 index 00000000..e78dbd41 --- /dev/null +++ b/tests/1001-1500/1312. minimum-insertion-steps-to-make-a-string-palindrome/sol.ts @@ -0,0 +1,17 @@ +function minInsertions(s: string): number { + const n = s.length; + const s2 = s.split("").reverse().join(""); + const dp: number[][] = Array.from({ length: n + 1 }, () => + Array(n + 1).fill(0), + ); + for (let i = 1; i <= n; i++) { + for (let j = 1; j <= n; j++) { + if (s[i - 1] === s2[j - 1]) { + dp[i][j] = 1 + dp[i - 1][j - 1]; + } else { + dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); + } + } + } + return n - dp[n][n]; +} diff --git a/tests/1001-1500/1313. decompress-run-length-encoded-list/manifest.yaml b/tests/1001-1500/1313. decompress-run-length-encoded-list/manifest.yaml new file mode 100644 index 00000000..9161f764 --- /dev/null +++ b/tests/1001-1500/1313. decompress-run-length-encoded-list/manifest.yaml @@ -0,0 +1,1101 @@ +entry: + id: 1313 + title: decompress-run-length-encoded-list + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().decompressRLElist({nums})" + rust: "Solution::decompress_rl_elist({nums})" + python3: "Solution().decompressRLElist({nums})" + python2: "Solution().decompressRLElist({nums})" + ruby: "decompress_rl_elist({nums})" + java: "new Solution().decompressRLElist({nums})" + csharp: "new Solution().DecompressRLElist({nums})" + kotlin: "Solution().decompressRLElist({nums})" + go: "decompressRLElist({nums})" + dart: "Solution().decompressRLElist({nums})" + swift: "Solution().decompressRLElist({nums})" + typescript: "decompressRLElist({nums})" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().decompressRLElist(nums, {result})" + checker: | + class Checker: + def decompressRLElist(self, nums, result): + if not isinstance(result, list): + return False + expected = [] + for index in range(0, len(nums), 2): + expected.extend([nums[index + 1]] * nums[index]) + return result == expected +seed: 1313 +tests: + - name: example-one + in: + nums: [1, 2, 3, 4] + out: [2, 4, 4, 4] + - name: example-two + in: + nums: [1, 1, 2, 3] + out: [1, 3, 3] + - name: minimum-length-minimum-values + in: + nums: [1, 1] + out: [1] + - name: minimum-length-maximum-value + in: + nums: [1, 100] + out: [100] + - name: maximum-frequency-maximum-value + in: + nums: [100, 100] + out: + [ + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + ] + - name: same-value-adjacent-runs + in: + nums: [2, 5, 3, 5] + out: [5, 5, 5, 5, 5] + - name: distinct-adjacent-runs + in: + nums: [2, 5, 3, 6] + out: [5, 5, 6, 6, 6] + - name: frequency-one-sequence + in: + nums: [1, 7, 1, 8, 1, 9, 1, 10] + out: [7, 8, 9, 10] + - name: increasing-frequencies + in: + nums: [1, 4, 2, 5, 3, 6, 4, 7] + out: [4, 5, 5, 6, 6, 6, 7, 7, 7, 7] + - name: decreasing-frequencies + in: + nums: [4, 7, 3, 6, 2, 5, 1, 4] + out: [7, 7, 7, 7, 6, 6, 6, 5, 5, 4] + - name: alternating-values + in: + nums: [3, 1, 1, 2, 3, 1, 1, 2] + out: [1, 1, 1, 2, 1, 1, 1, 2] + - name: alternating-frequencies + in: + nums: [1, 9, 5, 8, 1, 7, 5, 6] + out: [9, 8, 8, 8, 8, 8, 7, 6, 6, 6, 6, 6] + - name: values-near-lower-bound + in: + nums: [2, 1, 3, 2, 4, 3] + out: [1, 1, 2, 2, 2, 3, 3, 3, 3] + - name: values-near-upper-bound + in: + nums: [2, 100, 3, 99, 4, 98] + out: [100, 100, 99, 99, 99, 98, 98, 98, 98] + - name: one-heavy-leading-run + in: + nums: [10, 9, 1, 8, 1, 7] + out: [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 7] + - name: one-heavy-trailing-run + in: + nums: [1, 7, 1, 8, 10, 9] + out: [7, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9] + - name: middle-heavy-run + in: + nums: [1, 3, 10, 4, 1, 5] + out: [3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5] + - name: prime-frequencies + in: + nums: [2, 11, 3, 13, 5, 17, 7, 19] + out: [11, 11, 13, 13, 13, 17, 17, 17, 17, 17, 19, 19, 19, 19, 19, 19, 19] + - name: repeated-pair-pattern + in: + nums: [2, 4, 2, 4, 2, 4, 2, 4] + out: [4, 4, 4, 4, 4, 4, 4, 4] + - name: ten-pairs-singletons + in: + nums: [1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 1, 6, 1, 7, 1, 8, 1, 9, 1, 10] + out: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + - name: ten-pairs-mixed + in: + nums: + [2, 10, 1, 20, 3, 30, 1, 40, 2, 50, 4, 60, 1, 70, 3, 80, 2, 90, 1, 100] + out: + [ + 10, + 10, + 20, + 30, + 30, + 30, + 40, + 50, + 50, + 60, + 60, + 60, + 60, + 70, + 80, + 80, + 80, + 90, + 90, + 100, + ] + - name: all-pairs-same-frequency + in: + nums: [4, 1, 4, 2, 4, 3, 4, 4] + out: [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4] + - name: all-pairs-same-value + in: + nums: [1, 42, 2, 42, 3, 42, 4, 42] + out: [42, 42, 42, 42, 42, 42, 42, 42, 42, 42] + - name: boundary-value-switches + in: + nums: [1, 1, 2, 100, 3, 1, 4, 100] + out: [1, 100, 100, 1, 1, 1, 100, 100, 100, 100] + - name: uneven-run-lengths + in: + nums: [6, 12, 2, 24, 8, 36, 3, 48] + out: + [ + 12, + 12, + 12, + 12, + 12, + 12, + 24, + 24, + 36, + 36, + 36, + 36, + 36, + 36, + 36, + 36, + 48, + 48, + 48, + ] + - name: two-large-runs + in: + nums: [25, 10, 25, 20] + out: + [ + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + ] + - name: high-values-many-runs + in: + nums: [1, 100, 2, 99, 3, 98, 4, 97, 5, 96] + out: [100, 99, 99, 98, 98, 98, 97, 97, 97, 97, 96, 96, 96, 96, 96] + - name: low-values-many-runs + in: + nums: [5, 1, 4, 2, 3, 3, 2, 4, 1, 5] + out: [1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5] + - name: fifty-pairs-singletons-maximum-length + in: + nums: + [ + 1, + 1, + 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, + 1, + 21, + 1, + 22, + 1, + 23, + 1, + 24, + 1, + 25, + 1, + 26, + 1, + 27, + 1, + 28, + 1, + 29, + 1, + 30, + 1, + 31, + 1, + 32, + 1, + 33, + 1, + 34, + 1, + 35, + 1, + 36, + 1, + 37, + 1, + 38, + 1, + 39, + 1, + 40, + 1, + 41, + 1, + 42, + 1, + 43, + 1, + 44, + 1, + 45, + 1, + 46, + 1, + 47, + 1, + 48, + 1, + 49, + 1, + 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, + ] + - name: fifty-pairs-maximum-length-mixed + in: + nums: + [ + 2, + 1, + 2, + 2, + 2, + 3, + 2, + 4, + 2, + 5, + 2, + 6, + 2, + 7, + 2, + 8, + 2, + 9, + 2, + 10, + 2, + 11, + 2, + 12, + 2, + 13, + 2, + 14, + 2, + 15, + 2, + 16, + 2, + 17, + 2, + 18, + 2, + 19, + 2, + 20, + 2, + 21, + 2, + 22, + 2, + 23, + 2, + 24, + 2, + 25, + 2, + 26, + 2, + 27, + 2, + 28, + 2, + 29, + 2, + 30, + 2, + 31, + 2, + 32, + 2, + 33, + 2, + 34, + 2, + 35, + 2, + 36, + 2, + 37, + 2, + 38, + 2, + 39, + 2, + 40, + 2, + 41, + 2, + 42, + 2, + 43, + 2, + 44, + 2, + 45, + 2, + 46, + 2, + 47, + 2, + 48, + 2, + 49, + 2, + 50, + ] + out: + [ + 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, + 50, + 50, + ] + - name: five-runs-total-hundred-elements + in: + nums: [20, 1, 20, 2, 20, 3, 20, 4, 20, 5] + out: + [ + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + ] + - name: irregular-ten-runs + in: + nums: [9, 3, 2, 6, 7, 9, 1, 12, 5, 15, 3, 18, 8, 21, 4, 24, 6, 27, 2, 30] + out: + [ + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 6, + 6, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 12, + 15, + 15, + 15, + 15, + 15, + 18, + 18, + 18, + 21, + 21, + 21, + 21, + 21, + 21, + 21, + 21, + 24, + 24, + 24, + 24, + 27, + 27, + 27, + 27, + 27, + 27, + 30, + 30, + ] + - name: value-order-is-preserved + in: + nums: [3, 50, 2, 1, 4, 100, 1, 25] + out: [50, 50, 50, 1, 1, 100, 100, 100, 100, 25] + - name: all-frequencies-two + in: + nums: [2, 1, 2, 3, 2, 5, 2, 7, 2, 9, 2, 11] + out: [1, 1, 3, 3, 5, 5, 7, 7, 9, 9, 11, 11] + - name: all-frequencies-three + in: + nums: [3, 2, 3, 4, 3, 6, 3, 8, 3, 10] + out: [2, 2, 2, 4, 4, 4, 6, 6, 6, 8, 8, 8, 10, 10, 10] + - name: high-frequency-interleaving + in: + nums: [12, 1, 1, 100, 12, 2, 1, 99] + out: + [ + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 100, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 99, + ] + - name: nonmonotonic-values + in: + nums: [4, 60, 1, 10, 2, 90, 3, 20, 5, 80] + out: [60, 60, 60, 60, 10, 90, 90, 20, 20, 20, 80, 80, 80, 80, 80] + - name: twenty-pairs-singletons + in: + nums: + [ + 1, + 81, + 1, + 82, + 1, + 83, + 1, + 84, + 1, + 85, + 1, + 86, + 1, + 87, + 1, + 88, + 1, + 89, + 1, + 90, + 1, + 91, + 1, + 92, + 1, + 93, + 1, + 94, + 1, + 95, + 1, + 96, + 1, + 97, + 1, + 98, + 1, + 99, + 1, + 100, + ] + out: + [ + 81, + 82, + 83, + 84, + 85, + 86, + 87, + 88, + 89, + 90, + 91, + 92, + 93, + 94, + 95, + 96, + 97, + 98, + 99, + 100, + ] + - name: symmetric-run-sizes + in: + nums: [1, 10, 2, 20, 3, 30, 4, 40, 3, 50, 2, 60, 1, 70] + out: [10, 20, 20, 30, 30, 30, 40, 40, 40, 40, 50, 50, 50, 60, 60, 70] + - name: maximum-value-frequency-as-data + in: + nums: [99, 100, 1, 1] + out: + [ + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 1, + ] diff --git a/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.cpp b/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.cpp new file mode 100644 index 00000000..4be957e7 --- /dev/null +++ b/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + vector decompressRLElist(vector& nums) { + vector a; + for (int i = 0; i < nums.size(); i += 2) { + int freq = nums[i]; + int val = nums[i + 1]; + a.insert(a.end(), freq, val); + } + return a; + } +}; diff --git a/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.cs b/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.cs new file mode 100644 index 00000000..fecbd3eb --- /dev/null +++ b/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.cs @@ -0,0 +1,18 @@ +public class Solution { + public int[] DecompressRLElist(int[] nums) { + int size = 0; + for (int i = 0; i < nums.Length; i += 2) { + size += nums[i]; + } + int[] a = new int[size]; + int idx = 0; + for (int i = 0; i < nums.Length; i += 2) { + int freq = nums[i]; + int val = nums[i + 1]; + for (int j = 0; j < freq; j++) { + a[idx++] = val; + } + } + return a; + } +} diff --git a/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.dart b/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.dart new file mode 100644 index 00000000..a907a09a --- /dev/null +++ b/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.dart @@ -0,0 +1,11 @@ +class Solution { + List decompressRLElist(List nums) { + List a = []; + for (int i = 0; i < nums.length; i += 2) { + int freq = nums[i]; + int val = nums[i + 1]; + a.addAll(List.filled(freq, val)); + } + return a; + } +} diff --git a/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.go b/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.go new file mode 100644 index 00000000..e1ef65ec --- /dev/null +++ b/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.go @@ -0,0 +1,11 @@ +func decompressRLElist(nums []int) []int { + a := []int{} + for i := 0; i < len(nums); i += 2 { + freq := nums[i] + val := nums[i+1] + for j := 0; j < freq; j++ { + a = append(a, val) + } + } + return a +} diff --git a/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.java b/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.java new file mode 100644 index 00000000..a7b3105e --- /dev/null +++ b/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.java @@ -0,0 +1,18 @@ +class Solution { + public int[] decompressRLElist(int[] nums) { + int size = 0; + for (int i = 0; i < nums.length; i += 2) { + size += nums[i]; + } + int[] a = new int[size]; + int idx = 0; + for (int i = 0; i < nums.length; i += 2) { + int freq = nums[i]; + int val = nums[i + 1]; + for (int j = 0; j < freq; j++) { + a[idx++] = val; + } + } + return a; + } +} diff --git a/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.kt b/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.kt new file mode 100644 index 00000000..082869c9 --- /dev/null +++ b/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.kt @@ -0,0 +1,18 @@ +class Solution { + fun decompressRLElist(nums: IntArray): IntArray { + var size = 0 + for (i in nums.indices step 2) { + size += nums[i] + } + val a = IntArray(size) + var idx = 0 + for (i in nums.indices step 2) { + val freq = nums[i] + val value = nums[i + 1] + repeat(freq) { + a[idx++] = value + } + } + return a + } +} diff --git a/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.py b/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.py new file mode 100644 index 00000000..0e12b5db --- /dev/null +++ b/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.py @@ -0,0 +1,7 @@ +class Solution(object): + def decompressRLElist(self, nums): + a = [] + for i in range(0, len(nums), 2): + a1 = [nums[i + 1]] * nums[i] + a += a1 + return a diff --git a/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.py2 b/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.py2 new file mode 100644 index 00000000..7bb229c5 --- /dev/null +++ b/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.py2 @@ -0,0 +1,7 @@ +class Solution(object): + def decompressRLElist(self, nums): + a=[] + for i in range(0,len(nums),2): + a1=[nums[i+1]]*nums[i] + a+=a1 + return a diff --git a/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.rb b/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.rb new file mode 100644 index 00000000..54495949 --- /dev/null +++ b/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.rb @@ -0,0 +1,9 @@ +# @param {Integer[]} nums +# @return {Integer[]} +def decompress_rl_elist(nums) + a = [] + (0...nums.length).step(2) do |i| + a.concat([nums[i + 1]] * nums[i]) + end + a +end diff --git a/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.rs b/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.rs new file mode 100644 index 00000000..13df0418 --- /dev/null +++ b/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.rs @@ -0,0 +1,13 @@ +impl Solution { + pub fn decompress_rl_elist(nums: Vec) -> Vec { + let mut a = Vec::new(); + let mut i = 0; + while i < nums.len() { + let freq = nums[i] as usize; + let val = nums[i + 1]; + a.extend(std::iter::repeat(val).take(freq)); + i += 2; + } + a + } +} diff --git a/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.swift b/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.swift new file mode 100644 index 00000000..83fbc740 --- /dev/null +++ b/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.swift @@ -0,0 +1,13 @@ +class Solution { + func decompressRLElist(_ nums: [Int]) -> [Int] { + var a: [Int] = [] + var i = 0 + while i < nums.count { + let freq = nums[i] + let val = nums[i + 1] + a.append(contentsOf: Array(repeating: val, count: freq)) + i += 2 + } + return a + } +} diff --git a/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.ts b/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.ts new file mode 100644 index 00000000..7c629fb3 --- /dev/null +++ b/tests/1001-1500/1313. decompress-run-length-encoded-list/sol.ts @@ -0,0 +1,9 @@ +function decompressRLElist(nums: number[]): number[] { + const a: number[] = []; + for (let i = 0; i < nums.length; i += 2) { + const freq = nums[i]; + const val = nums[i + 1]; + a.push(...Array(freq).fill(val)); + } + return a; +} diff --git a/tests/1001-1500/1314. matrix-block-sum/manifest.yaml b/tests/1001-1500/1314. matrix-block-sum/manifest.yaml new file mode 100644 index 00000000..c17cdce7 --- /dev/null +++ b/tests/1001-1500/1314. matrix-block-sum/manifest.yaml @@ -0,0 +1,534 @@ +entry: + id: 1314 + title: "matrix-block-sum" + params: + mat: + type: array + items: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().matrixBlockSum({mat}, {k})" + rust: "Solution::matrix_block_sum({mat}, {k})" + python3: "Solution().matrixBlockSum({mat}, {k})" + python2: "Solution().matrixBlockSum({mat}, {k})" + ruby: "matrix_block_sum({mat}, {k})" + java: "new Solution().matrixBlockSum({mat}, {k})" + csharp: "new Solution().MatrixBlockSum({mat}, {k})" + kotlin: "Solution().matrixBlockSum({mat}, {k})" + go: "matrixBlockSum({mat}, {k})" + dart: "Solution().matrixBlockSum({mat}, {k})" + swift: "Solution().matrixBlockSum({mat}, {k})" + typescript: "matrixBlockSum({mat}, {k})" +judge: + type: "exact" +limits: + time_ms: 1000 + memory_mb: 300 +oracle: + python3: + call: "Checker().matrixBlockSum(mat, k, {result})" + checker: | + class Checker: + def matrixBlockSum(self, mat, k, result): + rows, cols = len(mat), len(mat[0]) + if not isinstance(result, list) or len(result) != rows: + return False + if any(not isinstance(row, list) or len(row) != cols for row in result): + return False + prefix = [[0] * (cols + 1) for _ in range(rows + 1)] + for i in range(rows): + for j in range(cols): + prefix[i + 1][j + 1] = mat[i][j] + prefix[i][j + 1] + prefix[i + 1][j] - prefix[i][j] + for i in range(rows): + for j in range(cols): + top, left = max(0, i - k), max(0, j - k) + bottom, right = min(rows, i + k + 1), min(cols, j + k + 1) + expected = prefix[bottom][right] - prefix[top][right] - prefix[bottom][left] + prefix[top][left] + if result[i][j] != expected: + return False + return True +seed: 131400 +tests: + - name: "example_one" + in: + mat: + - [1, 2, 3] + - [4, 5, 6] + - [7, 8, 9] + k: 1 + out: + - [12, 21, 16] + - [27, 45, 33] + - [24, 39, 28] + - name: "example_two" + in: + mat: + - [1, 2, 3] + - [4, 5, 6] + - [7, 8, 9] + k: 2 + out: + - [45, 45, 45] + - [45, 45, 45] + - [45, 45, 45] + - name: "single_cell_minimum_value" + in: + mat: + - [1] + k: 1 + out: + - [1] + - name: "single_cell_maximum_value_and_k" + in: + mat: + - [100] + k: 100 + out: + - [100] + - name: "single_row_local_window" + in: + mat: + - [1, 2, 3, 4, 5] + k: 1 + out: + - [3, 6, 9, 12, 9] + - name: "single_row_window_exceeds_width" + in: + mat: + - [1, 2, 3, 4, 5] + k: 5 + out: + - [15, 15, 15, 15, 15] + - name: "single_column_local_window" + in: + mat: + - [1] + - [2] + - [3] + - [4] + k: 1 + out: + - [3] + - [6] + - [9] + - [7] + - name: "single_column_window_exceeds_height" + in: + mat: + - [1] + - [2] + - [3] + - [4] + k: 4 + out: + - [10] + - [10] + - [10] + - [10] + - name: "two_by_two_full_neighborhood" + in: + mat: + - [1, 2] + - [3, 4] + k: 1 + out: + - [10, 10] + - [10, 10] + - name: "two_by_three_rectangular" + in: + mat: + - [1, 2, 3] + - [4, 5, 6] + k: 1 + out: + - [12, 21, 16] + - [12, 21, 16] + - name: "three_by_two_rectangular" + in: + mat: + - [1, 2] + - [3, 4] + - [5, 6] + k: 1 + out: + - [10, 10] + - [21, 21] + - [18, 18] + - name: "uniform_three_by_three" + in: + mat: + - [3, 3, 3] + - [3, 3, 3] + - [3, 3, 3] + k: 1 + out: + - [12, 18, 12] + - [18, 27, 18] + - [12, 18, 12] + - name: "uniform_small_matrix_large_k" + in: + mat: + - [2, 2, 2] + - [2, 2, 2] + k: 10 + out: + - [12, 12, 12] + - [12, 12, 12] + - name: "wide_matrix_k_two" + in: + mat: + - [1, 2, 3, 4, 5, 6] + - [7, 8, 9, 10, 11, 12] + k: 2 + out: + - [30, 44, 60, 70, 60, 48] + - [30, 44, 60, 70, 60, 48] + - name: "tall_matrix_k_two" + in: + mat: + - [1, 2] + - [3, 4] + - [5, 6] + - [7, 8] + - [9, 10] + k: 2 + out: + - [21, 21] + - [36, 36] + - [55, 55] + - [52, 52] + - [45, 45] + - name: "heavy_opposite_corners" + in: + mat: + - [100, 1, 1] + - [1, 1, 1] + - [1, 1, 100] + k: 1 + out: + - [103, 105, 4] + - [105, 207, 105] + - [4, 105, 103] + - name: "alternating_values" + in: + mat: + - [1, 10, 1, 10] + - [10, 1, 10, 1] + - [1, 10, 1, 10] + k: 1 + out: + - [22, 33, 33, 22] + - [33, 45, 54, 33] + - [22, 33, 33, 22] + - name: "four_by_four_k_one" + in: + mat: + - [1, 2, 3, 4] + - [5, 6, 7, 8] + - [9, 10, 11, 12] + - [13, 14, 15, 16] + k: 1 + out: + - [14, 24, 30, 22] + - [33, 54, 63, 45] + - [57, 90, 99, 69] + - [46, 72, 78, 54] + - name: "four_by_four_nearly_global_window" + in: + mat: + - [1, 2, 3, 4] + - [5, 6, 7, 8] + - [9, 10, 11, 12] + - [13, 14, 15, 16] + k: 3 + out: + - [136, 136, 136, 136] + - [136, 136, 136, 136] + - [136, 136, 136, 136] + - [136, 136, 136, 136] + - name: "single_high_center" + in: + mat: + - [1, 1, 1] + - [1, 100, 1] + - [1, 1, 1] + k: 1 + out: + - [103, 105, 103] + - [105, 108, 105] + - [103, 105, 103] + - name: "two_by_four_different_row_patterns" + in: + mat: + - [2, 4, 6, 8] + - [1, 3, 5, 7] + k: 1 + out: + - [10, 21, 33, 26] + - [10, 21, 33, 26] + - name: "four_by_two_k_two" + in: + mat: + - [2, 1] + - [4, 3] + - [6, 5] + - [8, 7] + k: 2 + out: + - [21, 21] + - [36, 36] + - [36, 36] + - [33, 33] + - name: "five_by_five_edge_and_center" + in: + mat: + - [1, 1, 1, 1, 1] + - [1, 2, 2, 2, 1] + - [1, 2, 9, 2, 1] + - [1, 2, 2, 2, 1] + - [1, 1, 1, 1, 1] + k: 1 + out: + - [5, 8, 9, 8, 5] + - [8, 20, 22, 20, 8] + - [9, 22, 25, 22, 9] + - [8, 20, 22, 20, 8] + - [5, 8, 9, 8, 5] + - name: "five_by_five_global_window" + in: + mat: + - [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: + - [325, 325, 325, 325, 325] + - [325, 325, 325, 325, 325] + - [325, 325, 325, 325, 325] + - [325, 325, 325, 325, 325] + - [325, 325, 325, 325, 325] + - name: "six_by_three_horizontal_invariance" + in: + mat: + - [1, 1, 1] + - [2, 2, 2] + - [3, 3, 3] + - [4, 4, 4] + - [5, 5, 5] + - [6, 6, 6] + k: 2 + out: + - [18, 18, 18] + - [30, 30, 30] + - [45, 45, 45] + - [60, 60, 60] + - [54, 54, 54] + - [45, 45, 45] + - name: "diagonal_maximum_values" + in: + mat: + - [1, 100] + - [100, 1] + k: 1 + out: + - [202, 202] + - [202, 202] + - name: "seven_by_one_k_three" + in: + mat: + - [1] + - [2] + - [3] + - [4] + - [5] + - [6] + - [7] + k: 3 + out: + - [10] + - [15] + - [21] + - [28] + - [27] + - [25] + - [22] + - name: "one_by_seven_k_three" + in: + mat: + - [1, 2, 3, 4, 5, 6, 7] + k: 3 + out: + - [10, 15, 21, 28, 27, 25, 22] + - name: "all_maximum_entries" + in: + mat: + - [100, 100, 100] + - [100, 100, 100] + - [100, 100, 100] + k: 1 + out: + - [400, 600, 400] + - [600, 900, 600] + - [400, 600, 400] + - name: "three_by_four_k_two" + in: + mat: + - [1, 2, 3, 4] + - [5, 6, 7, 8] + - [9, 10, 11, 12] + k: 2 + out: + - [54, 78, 78, 63] + - [54, 78, 78, 63] + - [54, 78, 78, 63] + - name: "four_by_three_k_two" + in: + mat: + - [1, 2, 3] + - [4, 5, 6] + - [7, 8, 9] + - [10, 11, 12] + k: 2 + out: + - [45, 45, 45] + - [78, 78, 78] + - [78, 78, 78] + - [72, 72, 72] + - name: "large_k_nonuniform_rows" + in: + mat: + - [100, 1, 100, 1] + - [100, 1, 100, 1] + - [100, 1, 100, 1] + k: 100 + out: + - [606, 606, 606, 606] + - [606, 606, 606, 606] + - [606, 606, 606, 606] + - name: "corner_outlier_with_k_two" + in: + mat: + - [100, 1, 1, 1] + - [1, 1, 1, 1] + - [1, 1, 1, 1] + - [1, 1, 1, 1] + k: 2 + out: + - [108, 111, 111, 9] + - [111, 115, 115, 12] + - [111, 115, 115, 12] + - [9, 12, 12, 9] + - name: "column_endpoints_are_maximum" + in: + mat: + - [100] + - [1] + - [1] + - [1] + - [100] + k: 1 + out: + - [101] + - [102] + - [3] + - [102] + - [101] + - name: "generated_twenty_by_twenty" + seed: 131401 + in: + mat: + gen: "array" + len: 20 + of: + gen: "array" + len: 20 + of: + gen: "int" + min: 1 + max: 100 + k: + gen: "int" + min: 1 + max: 100 + - name: "generated_wide_thirty_five_by_seventy" + seed: 131402 + in: + mat: + gen: "array" + len: 35 + of: + gen: "array" + len: 70 + of: + gen: "int" + min: 1 + max: 100 + k: + gen: "int" + min: 1 + max: 100 + - name: "generated_tall_seventy_by_thirty_five" + seed: 131403 + in: + mat: + gen: "array" + len: 70 + of: + gen: "array" + len: 35 + of: + gen: "int" + min: 1 + max: 100 + k: + gen: "int" + min: 1 + max: 100 + - name: "generated_maximum_k_one" + seed: 131404 + in: + mat: + gen: "array" + len: 100 + of: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 100 + k: 1 + - name: "generated_maximum_midrange_k" + seed: 131405 + in: + mat: + gen: "array" + len: 100 + of: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 100 + k: 50 + - name: "generated_maximum_global_k" + seed: 131406 + in: + mat: + gen: "array" + len: 100 + of: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 100 + k: 100 diff --git a/tests/1001-1500/1314. matrix-block-sum/sol.cpp b/tests/1001-1500/1314. matrix-block-sum/sol.cpp new file mode 100644 index 00000000..7b21f6fa --- /dev/null +++ b/tests/1001-1500/1314. matrix-block-sum/sol.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + vector> matrixBlockSum(vector>& mat, int k) { + int n = mat.size(), m = mat[0].size(); + vector> pre(n, vector(m, 0)); + vector> ans(n, vector(m, 0)); + + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + int sum = mat[i][j]; + if (i - 1 >= 0) sum += pre[i-1][j]; + if (j - 1 >= 0) sum += pre[i][j-1]; + if (i - 1 >= 0 && j - 1 >= 0) sum -= pre[i-1][j-1]; + pre[i][j] = sum; + } + } + + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + int i1 = max(0, i - k); + int i2 = min(n - 1, i + k); + int j1 = max(0, j - k); + int j2 = min(m - 1, j + k); + int sum = pre[i2][j2]; + if (i1 - 1 >= 0) sum -= pre[i1-1][j2]; + if (j1 - 1 >= 0) sum -= pre[i2][j1-1]; + if (i1 - 1 >= 0 && j1 - 1 >= 0) sum += pre[i1-1][j1-1]; + ans[i][j] = sum; + } + } + return ans; + } +}; diff --git a/tests/1001-1500/1314. matrix-block-sum/sol.cs b/tests/1001-1500/1314. matrix-block-sum/sol.cs new file mode 100644 index 00000000..d35bc0b1 --- /dev/null +++ b/tests/1001-1500/1314. matrix-block-sum/sol.cs @@ -0,0 +1,36 @@ +public class Solution { + public int[][] MatrixBlockSum(int[][] mat, int k) { + int n = mat.Length, m = mat[0].Length; + int[][] pre = new int[n][]; + int[][] ans = new int[n][]; + for (int i = 0; i < n; i++) { + pre[i] = new int[m]; + ans[i] = new int[m]; + } + + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + int sum = mat[i][j]; + if (i - 1 >= 0) sum += pre[i-1][j]; + if (j - 1 >= 0) sum += pre[i][j-1]; + if (i - 1 >= 0 && j - 1 >= 0) sum -= pre[i-1][j-1]; + pre[i][j] = sum; + } + } + + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + int i1 = Math.Max(0, i - k); + int i2 = Math.Min(n - 1, i + k); + int j1 = Math.Max(0, j - k); + int j2 = Math.Min(m - 1, j + k); + int sum = pre[i2][j2]; + if (i1 - 1 >= 0) sum -= pre[i1-1][j2]; + if (j1 - 1 >= 0) sum -= pre[i2][j1-1]; + if (i1 - 1 >= 0 && j1 - 1 >= 0) sum += pre[i1-1][j1-1]; + ans[i][j] = sum; + } + } + return ans; + } +} diff --git a/tests/1001-1500/1314. matrix-block-sum/sol.dart b/tests/1001-1500/1314. matrix-block-sum/sol.dart new file mode 100644 index 00000000..82782db1 --- /dev/null +++ b/tests/1001-1500/1314. matrix-block-sum/sol.dart @@ -0,0 +1,32 @@ +class Solution { + List> matrixBlockSum(List> mat, int k) { + int n = mat.length, m = mat[0].length; + List> pre = List.generate(n, (_) => List.filled(m, 0)); + List> ans = List.generate(n, (_) => List.filled(m, 0)); + + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + int sum = mat[i][j]; + if (i - 1 >= 0) sum += pre[i-1][j]; + if (j - 1 >= 0) sum += pre[i][j-1]; + if (i - 1 >= 0 && j - 1 >= 0) sum -= pre[i-1][j-1]; + pre[i][j] = sum; + } + } + + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + int i1 = (0 > (i - k) ? 0 : (i - k)); + int i2 = (n - 1 < (i + k) ? n - 1 : (i + k)); + int j1 = (0 > (j - k) ? 0 : (j - k)); + int j2 = (m - 1 < (j + k) ? m - 1 : (j + k)); + int sum = pre[i2][j2]; + if (i1 - 1 >= 0) sum -= pre[i1-1][j2]; + if (j1 - 1 >= 0) sum -= pre[i2][j1-1]; + if (i1 - 1 >= 0 && j1 - 1 >= 0) sum += pre[i1-1][j1-1]; + ans[i][j] = sum; + } + } + return ans; + } +} diff --git a/tests/1001-1500/1314. matrix-block-sum/sol.go b/tests/1001-1500/1314. matrix-block-sum/sol.go new file mode 100644 index 00000000..352609bb --- /dev/null +++ b/tests/1001-1500/1314. matrix-block-sum/sol.go @@ -0,0 +1,46 @@ +func matrixBlockSum(mat [][]int, k int) [][]int { + n, m := len(mat), len(mat[0]) + pre := make([][]int, n) + ans := make([][]int, n) + for i := 0; i < n; i++ { + pre[i] = make([]int, m) + ans[i] = make([]int, m) + } + + for i := 0; i < n; i++ { + for j := 0; j < m; j++ { + sum := mat[i][j] + if i-1 >= 0 { + sum += pre[i-1][j] + } + if j-1 >= 0 { + sum += pre[i][j-1] + } + if i-1 >= 0 && j-1 >= 0 { + sum -= pre[i-1][j-1] + } + pre[i][j] = sum + } + } + + for i := 0; i < n; i++ { + for j := 0; j < m; j++ { + i1 := max(0, i-k) + i2 := min(n-1, i+k) + j1 := max(0, j-k) + j2 := min(m-1, j+k) + sum := pre[i2][j2] + if i1-1 >= 0 { + sum -= pre[i1-1][j2] + } + if j1-1 >= 0 { + sum -= pre[i2][j1-1] + } + if i1-1 >= 0 && j1-1 >= 0 { + sum += pre[i1-1][j1-1] + } + ans[i][j] = sum + } + } + return ans +} diff --git a/tests/1001-1500/1314. matrix-block-sum/sol.java b/tests/1001-1500/1314. matrix-block-sum/sol.java new file mode 100644 index 00000000..0e4887cc --- /dev/null +++ b/tests/1001-1500/1314. matrix-block-sum/sol.java @@ -0,0 +1,32 @@ +class Solution { + public int[][] matrixBlockSum(int[][] mat, int k) { + int n = mat.length, m = mat[0].length; + int[][] pre = new int[n][m]; + int[][] ans = new int[n][m]; + + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + int sum = mat[i][j]; + if (i - 1 >= 0) sum += pre[i-1][j]; + if (j - 1 >= 0) sum += pre[i][j-1]; + if (i - 1 >= 0 && j - 1 >= 0) sum -= pre[i-1][j-1]; + pre[i][j] = sum; + } + } + + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + int i1 = Math.max(0, i - k); + int i2 = Math.min(n - 1, i + k); + int j1 = Math.max(0, j - k); + int j2 = Math.min(m - 1, j + k); + int sum = pre[i2][j2]; + if (i1 - 1 >= 0) sum -= pre[i1-1][j2]; + if (j1 - 1 >= 0) sum -= pre[i2][j1-1]; + if (i1 - 1 >= 0 && j1 - 1 >= 0) sum += pre[i1-1][j1-1]; + ans[i][j] = sum; + } + } + return ans; + } +} diff --git a/tests/1001-1500/1314. matrix-block-sum/sol.kt b/tests/1001-1500/1314. matrix-block-sum/sol.kt new file mode 100644 index 00000000..1aa56fce --- /dev/null +++ b/tests/1001-1500/1314. matrix-block-sum/sol.kt @@ -0,0 +1,33 @@ +class Solution { + fun matrixBlockSum(mat: Array, k: Int): Array { + val n = mat.size + val m = mat[0].size + val pre = Array(n) { IntArray(m) } + val ans = Array(n) { IntArray(m) } + + for (i in 0 until n) { + for (j in 0 until m) { + var sum = mat[i][j] + if (i - 1 >= 0) sum += pre[i-1][j] + if (j - 1 >= 0) sum += pre[i][j-1] + if (i - 1 >= 0 && j - 1 >= 0) sum -= pre[i-1][j-1] + pre[i][j] = sum + } + } + + for (i in 0 until n) { + for (j in 0 until m) { + val i1 = maxOf(0, i - k) + val i2 = minOf(n - 1, i + k) + val j1 = maxOf(0, j - k) + val j2 = minOf(m - 1, j + k) + var sum = pre[i2][j2] + if (i1 - 1 >= 0) sum -= pre[i1-1][j2] + if (j1 - 1 >= 0) sum -= pre[i2][j1-1] + if (i1 - 1 >= 0 && j1 - 1 >= 0) sum += pre[i1-1][j1-1] + ans[i][j] = sum + } + } + return ans + } +} diff --git a/tests/1001-1500/1314. matrix-block-sum/sol.py b/tests/1001-1500/1314. matrix-block-sum/sol.py new file mode 100644 index 00000000..dd81c9b5 --- /dev/null +++ b/tests/1001-1500/1314. matrix-block-sum/sol.py @@ -0,0 +1,31 @@ +class Solution: + def matrixBlockSum(self, mat: List[List[int]], k: int) -> List[List[int]]: + n, m = len(mat), len(mat[0]) + pre = [[0 for _ in range(m)] for _ in range(n)] + ans = [[0 for _ in range(m)] for _ in range(n)] + for i in range(n): + for j in range(m): + _sum = mat[i][j] + if i - 1 >= 0: + _sum += pre[i - 1][j] + if j - 1 >= 0: + _sum += pre[i][j - 1] + if i - 1 >= 0 and j - 1 >= 0: + _sum -= pre[i - 1][j - 1] + pre[i][j] = _sum + + for i in range(n): + for j in range(m): + i1 = max(0, i - k) + i2 = min(n - 1, i + k) + j1 = max(0, j - k) + j2 = min(m - 1, j + k) + _sum = pre[i2][j2] + if i1 - 1 >= 0: + _sum -= pre[i1 - 1][j2] + if j1 - 1 >= 0: + _sum -= pre[i2][j1 - 1] + if i1 - 1 >= 0 and j1 - 1 >= 0: + _sum += pre[i1 - 1][j1 - 1] + ans[i][j] = _sum + return ans diff --git a/tests/1001-1500/1314. matrix-block-sum/sol.py2 b/tests/1001-1500/1314. matrix-block-sum/sol.py2 new file mode 100644 index 00000000..d94ec483 --- /dev/null +++ b/tests/1001-1500/1314. matrix-block-sum/sol.py2 @@ -0,0 +1,36 @@ +class Solution(object): + def matrixBlockSum(self, mat, k): + """ + :type mat: List[List[int]] + :type k: int + :rtype: List[List[int]] + """ + n, m = len(mat), len(mat[0]) + pre = [[0 for _ in range(m)] for _ in range(n)] + ans = [[0 for _ in range(m)] for _ in range(n)] + for i in range(n): + for j in range(m): + _sum = mat[i][j] + if i-1 >= 0: + _sum += pre[i-1][j] + if j-1 >= 0: + _sum += pre[i][j-1] + if i-1 >= 0 and j-1 >= 0: + _sum -= pre[i-1][j-1] + pre[i][j] = _sum + + for i in range(n): + for j in range(m): + i1 = max(0, i-k) + i2 = min(n-1, i+k) + j1 = max(0, j-k) + j2 = min(m-1, j+k) + _sum = pre[i2][j2] + if i1 - 1 >= 0: + _sum -= pre[i1-1][j2] + if j1 - 1 >= 0: + _sum -= pre[i2][j1-1] + if i1 - 1 >= 0 and j1 - 1 >= 0: + _sum += pre[i1-1][j1-1] + ans[i][j] = _sum + return ans diff --git a/tests/1001-1500/1314. matrix-block-sum/sol.rb b/tests/1001-1500/1314. matrix-block-sum/sol.rb new file mode 100644 index 00000000..c363b2f2 --- /dev/null +++ b/tests/1001-1500/1314. matrix-block-sum/sol.rb @@ -0,0 +1,33 @@ +# @param {Integer[][]} mat +# @param {Integer} k +# @return {Integer[][]} +def matrix_block_sum(mat, k) + n, m = mat.length, mat[0].length + pre = Array.new(n) { Array.new(m, 0) } + ans = Array.new(n) { Array.new(m, 0) } + + (0...n).each do |i| + (0...m).each do |j| + _sum = mat[i][j] + _sum += pre[i-1][j] if i-1 >= 0 + _sum += pre[i][j-1] if j-1 >= 0 + _sum -= pre[i-1][j-1] if i-1 >= 0 && j-1 >= 0 + pre[i][j] = _sum + end + end + + (0...n).each do |i| + (0...m).each do |j| + i1 = [0, i-k].max + i2 = [n-1, i+k].min + j1 = [0, j-k].max + j2 = [m-1, j+k].min + _sum = pre[i2][j2] + _sum -= pre[i1-1][j2] if i1 - 1 >= 0 + _sum -= pre[i2][j1-1] if j1 - 1 >= 0 + _sum += pre[i1-1][j1-1] if i1 - 1 >= 0 && j1 - 1 >= 0 + ans[i][j] = _sum + end + end + ans +end diff --git a/tests/1001-1500/1314. matrix-block-sum/sol.rs b/tests/1001-1500/1314. matrix-block-sum/sol.rs new file mode 100644 index 00000000..f1fc9848 --- /dev/null +++ b/tests/1001-1500/1314. matrix-block-sum/sol.rs @@ -0,0 +1,34 @@ +impl Solution { + pub fn matrix_block_sum(mat: Vec>, k: i32) -> Vec> { + let n = mat.len(); + let m = mat[0].len(); + let mut pre = vec![vec![0; m]; n]; + let mut ans = vec![vec![0; m]; n]; + let k = k as usize; + + for i in 0..n { + for j in 0..m { + let mut sum = mat[i][j]; + if i >= 1 { sum += pre[i-1][j]; } + if j >= 1 { sum += pre[i][j-1]; } + if i >= 1 && j >= 1 { sum -= pre[i-1][j-1]; } + pre[i][j] = sum; + } + } + + for i in 0..n { + for j in 0..m { + let i1 = if i < k { 0 } else { i - k }; + let i2 = if i + k >= n { n - 1 } else { i + k }; + let j1 = if j < k { 0 } else { j - k }; + let j2 = if j + k >= m { m - 1 } else { j + k }; + let mut sum = pre[i2][j2]; + if i1 >= 1 { sum -= pre[i1-1][j2]; } + if j1 >= 1 { sum -= pre[i2][j1-1]; } + if i1 >= 1 && j1 >= 1 { sum += pre[i1-1][j1-1]; } + ans[i][j] = sum; + } + } + ans + } +} diff --git a/tests/1001-1500/1314. matrix-block-sum/sol.swift b/tests/1001-1500/1314. matrix-block-sum/sol.swift new file mode 100644 index 00000000..f03d361f --- /dev/null +++ b/tests/1001-1500/1314. matrix-block-sum/sol.swift @@ -0,0 +1,32 @@ +class Solution { + func matrixBlockSum(_ mat: [[Int]], _ k: Int) -> [[Int]] { + let n = mat.count, m = mat[0].count + var pre = Array(repeating: Array(repeating: 0, count: m), count: n) + var ans = Array(repeating: Array(repeating: 0, count: m), count: n) + + for i in 0..= 0 { sum += pre[i-1][j] } + if j - 1 >= 0 { sum += pre[i][j-1] } + if i - 1 >= 0 && j - 1 >= 0 { sum -= pre[i-1][j-1] } + pre[i][j] = sum + } + } + + for i in 0..= 0 { sum -= pre[i1-1][j2] } + if j1 - 1 >= 0 { sum -= pre[i2][j1-1] } + if i1 - 1 >= 0 && j1 - 1 >= 0 { sum += pre[i1-1][j1-1] } + ans[i][j] = sum + } + } + return ans + } +} diff --git a/tests/1001-1500/1314. matrix-block-sum/sol.ts b/tests/1001-1500/1314. matrix-block-sum/sol.ts new file mode 100644 index 00000000..b9bda80f --- /dev/null +++ b/tests/1001-1500/1314. matrix-block-sum/sol.ts @@ -0,0 +1,31 @@ +function matrixBlockSum(mat: number[][], k: number): number[][] { + const n = mat.length, + m = mat[0].length; + const pre: number[][] = Array.from({ length: n }, () => Array(m).fill(0)); + const ans: number[][] = Array.from({ length: n }, () => Array(m).fill(0)); + + for (let i = 0; i < n; i++) { + for (let j = 0; j < m; j++) { + let sum = mat[i][j]; + if (i - 1 >= 0) sum += pre[i - 1][j]; + if (j - 1 >= 0) sum += pre[i][j - 1]; + if (i - 1 >= 0 && j - 1 >= 0) sum -= pre[i - 1][j - 1]; + pre[i][j] = sum; + } + } + + for (let i = 0; i < n; i++) { + for (let j = 0; j < m; j++) { + const i1 = Math.max(0, i - k); + const i2 = Math.min(n - 1, i + k); + const j1 = Math.max(0, j - k); + const j2 = Math.min(m - 1, j + k); + let sum = pre[i2][j2]; + if (i1 - 1 >= 0) sum -= pre[i1 - 1][j2]; + if (j1 - 1 >= 0) sum -= pre[i2][j1 - 1]; + if (i1 - 1 >= 0 && j1 - 1 >= 0) sum += pre[i1 - 1][j1 - 1]; + ans[i][j] = sum; + } + } + return ans; +} diff --git a/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/manifest.yaml b/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/manifest.yaml new file mode 100644 index 00000000..0eceec49 --- /dev/null +++ b/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/manifest.yaml @@ -0,0 +1,421 @@ +entry: + id: 1315 + title: "sum-of-nodes-with-even-valued-grandparent" + params: + root: + type: tree_node + call: + cpp: "Solution().sumEvenGrandparent({root})" + rust: "Solution::sum_even_grandparent({root})" + python3: "Solution().sumEvenGrandparent({root})" + python2: "Solution().sumEvenGrandparent({root})" + ruby: "sum_even_grandparent({root})" + java: "new Solution().sumEvenGrandparent({root})" + csharp: "new Solution().SumEvenGrandparent({root})" + kotlin: "Solution().sumEvenGrandparent({root})" + go: "sumEvenGrandparent({root})" + dart: "Solution().sumEvenGrandparent({root})" + swift: "Solution().sumEvenGrandparent({root})" + typescript: "sumEvenGrandparent({root})" +judge: + type: exact +limits: + time_ms: 400 + memory_mb: 300 +oracle: + python3: + call: "Checker().sumEvenGrandparent(root, {result})" + checker: | + from collections import deque + + class Checker: + def sumEvenGrandparent(self, root, result): + if isinstance(result, bool) or not isinstance(result, int): + return False + if isinstance(root, list): + if not root: + return result == 0 + queue = deque([(root[0], None, None)]) + index = 1 + total = 0 + while queue: + value, parent, grandparent = queue.popleft() + if grandparent is not None and grandparent % 2 == 0: + total += value + for _ in range(2): + if index >= len(root): + break + child = root[index] + index += 1 + if child is not None: + queue.append((child, value, parent)) + return result == total + queue = deque([(root, None, None)]) + total = 0 + while queue: + node, parent, grandparent = queue.popleft() + if node is None: + continue + if grandparent is not None and grandparent % 2 == 0: + total += node.val + queue.append((node.left, node.val, parent)) + queue.append((node.right, node.val, parent)) + return result == total +seed: 1315 +tests: + - name: official_example + in: + root: [6, 7, 8, 2, 7, 1, 3, 9, null, 1, 4, null, null, null, 5] + out: 18 + - name: official_single_node + in: + root: [1] + out: 0 + - name: maximum_value_single_node + in: + root: [100] + out: 0 + - name: two_levels_have_no_grandchildren + in: + root: [2, 1, 3] + out: 0 + - name: even_root_counts_all_depth_two_nodes + in: + root: [2, 1, 3, 4, 5, 6, 7] + out: 22 + - name: odd_root_excludes_all_depth_two_nodes + in: + root: [1, 2, 4, 4, 5, 6, 7] + out: 0 + - name: all_odd_values + in: + root: [1, 3, 5, 7, 9, 11, 13] + out: 0 + - name: odd_root_and_odd_children + in: + root: [9, 7, 5, 2, 4, 6, 8] + out: 0 + - name: left_only_parent_with_two_children + in: + root: [2, 1, null, 3, 4] + out: 7 + - name: right_then_left_zigzag + in: + root: [1, null, 2, 3, null, 4] + out: 4 + - name: right_chain_even_root + in: + root: [2, null, 1, null, 3, null, 4, null, 5] + out: 3 + - name: right_chain_odd_root + in: + root: [3, null, 1, null, 2, null, 4, null, 6] + out: 6 + - name: left_subtree_deeper_than_right + in: + root: [2, 3, null, 4, 5, 6] + out: 9 + - name: odd_root_excludes_even_left_parent + in: + root: [5, 2, 7, 1, 3, 4, 6] + out: 0 + - name: even_root_with_sparse_depth_three + in: + root: [6, 3, 5, null, 8, 7, null, 9] + out: 15 + - name: odd_root_excludes_both_even_children + in: + root: [7, 2, 4, 8, 9, 10, 11] + out: 0 + - name: minimum_values + in: + root: [1, 1, 1, 1, 1, 1, 1] + out: 0 + - name: maximum_values + in: + root: [100, 100, 100, 100, 100, 100, 100] + out: 400 + - name: repeated_even_values_four_levels + in: + root: [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] + out: 24 + - name: alternating_parity_full_four_levels + in: + root: [2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2] + out: 12 + - name: compressed_bfs_missing_left_child + in: + root: [4, 1, 3, null, 5, 7, null, 8, 9] + out: 12 + - name: compressed_bfs_missing_right_child + in: + root: [8, 5, null, 2, 4, null, 6, 7] + out: 6 + - name: even_grandparent_at_depth_one_only + in: + root: [9, 4, 7, 10, 20, 30, 40, 1, 2, 3, 4] + out: 10 + - name: even_grandparent_at_depth_two_only + in: + root: + [ + 9, + 5, + 7, + 2, + 3, + 4, + 5, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + ] + out: 52 + - name: even_root_with_one_grandchild + in: + root: [10, 9, null, 99] + out: 99 + - name: odd_root_with_one_grandchild + in: + root: [9, 10, null, 99] + out: 0 + - name: values_near_parity_boundary + in: + root: [98, 99, 100, 1, 2, 99, 100] + out: 202 + - name: nonuniform_full_tree + in: + root: [12, 7, 18, 1, 100, 2, 99, 50, 51, 52, 53, 54, 55, 56, 57] + out: 424 + - name: left_chain_depth_six + in: + root: [2, 3, null, 4, null, 5, null, 6, null, 7] + out: 10 + - name: right_chain_depth_six + in: + root: [1, null, 2, null, 3, null, 4, null, 5, null, 6] + out: 10 + - name: alternating_zigzag_depth_seven + in: + root: [2, 1, null, null, 3, 4, null, null, 5, 6] + out: 9 + - name: root_even_with_odd_descendant_grandparents + in: + root: [2, 1, 1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100] + out: 100 + - name: root_odd_with_even_descendant_grandparents + in: + root: [1, 2, 2, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100] + out: 450 + - name: unbalanced_even_right_subtree + in: + root: [3, 5, 8, null, null, 1, 2, 9, 10, 11] + out: 30 + - name: unbalanced_even_left_subtree + in: + root: [3, 8, 5, 1, 2, null, null, 9, 10, 11] + out: 30 + - name: dense_five_levels_all_even + in: + root: + [ + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 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: 2800 + - name: dense_six_levels_even_root_odd_descendants + in: + root: + [ + 100, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + ] + out: 396 + - name: dense_six_levels_even_everywhere + in: + root: + [ + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + ] + out: 120 + - name: sparse_both_sides_with_late_nodes + in: + root: [14, 3, 5, null, 7, null, 9, 11, null, 13, null, 15] + out: 16 + - name: mixed_values_deep_branching + in: + root: [11, 6, 9, 4, 7, 8, 3, 20, 21, 22, 23, 24, 25, 26, 27] + out: 86 diff --git a/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.cpp b/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.cpp new file mode 100644 index 00000000..57fad0f8 --- /dev/null +++ b/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/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: + int sumEvenGrandparent(TreeNode* root) { + queue> q; + q.push({root, -1, -1}); + int res = 0; + while (!q.empty()) { + auto [node, parent, grandparent] = q.front(); + q.pop(); + if (!node) continue; + if (grandparent % 2 == 0) { + res += node->val; + } + if (node->left) { + q.push({node->left, node->val, parent}); + } + if (node->right) { + q.push({node->right, node->val, parent}); + } + } + return res; + } +}; diff --git a/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.cs b/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.cs new file mode 100644 index 00000000..faa9942a --- /dev/null +++ b/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.cs @@ -0,0 +1,34 @@ +/** + * 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 SumEvenGrandparent(TreeNode root) { + var queue = new Queue<(TreeNode node, int parent, int grandparent)>(); + queue.Enqueue((root, -1, -1)); + int res = 0; + while (queue.Count > 0) { + var (node, parent, grandparent) = queue.Dequeue(); + if (node == null) continue; + if (grandparent % 2 == 0) { + res += node.val; + } + if (node.left != null) { + queue.Enqueue((node.left, node.val, parent)); + } + if (node.right != null) { + queue.Enqueue((node.right, node.val, parent)); + } + } + return res; + } +} diff --git a/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.dart b/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.dart new file mode 100644 index 00000000..d63e67d5 --- /dev/null +++ b/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.dart @@ -0,0 +1,33 @@ +/** + * 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 sumEvenGrandparent(TreeNode? root) { + var queue = Queue>(); + queue.add([root, -1, -1]); + int res = 0; + while (queue.isNotEmpty) { + final state = queue.removeFirst(); + final TreeNode? node = state[0] as TreeNode?; + final int parent = state[1] as int; + final int grandparent = state[2] as int; + if (node == null) continue; + if (grandparent % 2 == 0) { + res += node.val; + } + if (node.left != null) { + queue.add([node.left, node.val, parent]); + } + if (node.right != null) { + queue.add([node.right, node.val, parent]); + } + } + return res; + } +} diff --git a/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.go b/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.go new file mode 100644 index 00000000..0600b854 --- /dev/null +++ b/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.go @@ -0,0 +1,34 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func sumEvenGrandparent(root *TreeNode) int { + type item struct { + node *TreeNode + parent int + grandparent int + } + queue := []item{{root, -1, -1}} + res := 0 + for len(queue) > 0 { + curr := queue[0] + queue = queue[1:] + if curr.node == nil { + continue + } + if curr.grandparent % 2 == 0 { + res += curr.node.Val + } + if curr.node.Left != nil { + queue = append(queue, item{curr.node.Left, curr.node.Val, curr.parent}) + } + if curr.node.Right != nil { + queue = append(queue, item{curr.node.Right, curr.node.Val, curr.parent}) + } + } + return res +} diff --git a/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.java b/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.java new file mode 100644 index 00000000..63aaecc4 --- /dev/null +++ b/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/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 int sumEvenGrandparent(TreeNode root) { + Queue queue = new LinkedList<>(); + queue.offer(new Object[]{root, -1, -1}); + int res = 0; + while (!queue.isEmpty()) { + Object[] curr = queue.poll(); + TreeNode node = (TreeNode) curr[0]; + int parent = (int) curr[1]; + int grandparent = (int) curr[2]; + if (node == null) continue; + if (grandparent % 2 == 0) { + res += node.val; + } + if (node.left != null) { + queue.offer(new Object[]{node.left, node.val, parent}); + } + if (node.right != null) { + queue.offer(new Object[]{node.right, node.val, parent}); + } + } + return res; + } +} diff --git a/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.kt b/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.kt new file mode 100644 index 00000000..ef8d548b --- /dev/null +++ b/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.kt @@ -0,0 +1,31 @@ +/** + * 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 sumEvenGrandparent(root: TreeNode?): Int { + val queue: java.util.ArrayDeque> = java.util.ArrayDeque() + queue.add(Triple(root, -1, -1)) + var res = 0 + while (queue.isNotEmpty()) { + val (node, parent, grandparent) = queue.removeFirst() + if (node == null) continue + if (grandparent % 2 == 0) { + res += node.`val` + } + if (node.left != null) { + queue.add(Triple(node.left, node.`val`, parent)) + } + if (node.right != null) { + queue.add(Triple(node.right, node.`val`, parent)) + } + } + return res + } +} diff --git a/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.py b/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.py new file mode 100644 index 00000000..51dfc067 --- /dev/null +++ b/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.py @@ -0,0 +1,24 @@ +from collections import deque + + +# 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 sumEvenGrandparent(self, root: Optional[TreeNode]) -> int: + queue = deque([(root, -1, -1)]) + res = 0 + while queue: + node, parent, grandparent = queue.popleft() + if node is None: + continue + if grandparent % 2 == 0: + res += node.val + if node.left: + queue.append((node.left, node.val, parent)) + if node.right: + queue.append((node.right, node.val, parent)) + return res diff --git a/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.py2 b/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.py2 new file mode 100644 index 00000000..1bcc0085 --- /dev/null +++ b/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.py2 @@ -0,0 +1,25 @@ +# 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 sumEvenGrandparent(self, root): + """ + :type root: Optional[TreeNode] + :rtype: int + """ + queue = deque([(root, -1, -1)]) + res = 0 + while queue: + node, parent, grandparent = queue.popleft() + if node is None: + continue + if grandparent % 2 == 0: + res += node.val + if node.left: + queue.append((node.left, node.val, parent)) + if node.right: + queue.append((node.right, node.val, parent)) + return res diff --git a/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.rb b/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.rb new file mode 100644 index 00000000..f3a24e36 --- /dev/null +++ b/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.rb @@ -0,0 +1,23 @@ +# 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 {Integer} +def sum_even_grandparent(root) + queue = [[root, -1, -1]] + res = 0 + while queue.any? + node, parent, grandparent = queue.shift + next if node.nil? + res += node.val if grandparent % 2 == 0 + queue.push([node.left, node.val, parent]) if node.left + queue.push([node.right, node.val, parent]) if node.right + end + res +end diff --git a/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.rs b/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.rs new file mode 100644 index 00000000..2b059a15 --- /dev/null +++ b/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.rs @@ -0,0 +1,40 @@ +// 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 sum_even_grandparent(root: Option>>) -> i32 { + let mut queue = std::collections::VecDeque::new(); + queue.push_back((root, -1, -1)); + let mut res = 0; + while let Some((node_opt, parent, grandparent)) = queue.pop_front() { + if let Some(node_rc) = node_opt { + let node = node_rc.borrow(); + if grandparent % 2 == 0 { + res += node.val; + } + if node.left.is_some() { + queue.push_back((node.left.clone(), node.val, parent)); + } + if node.right.is_some() { + queue.push_back((node.right.clone(), node.val, parent)); + } + } + } + res + } +} diff --git a/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.swift b/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.swift new file mode 100644 index 00000000..938e052c --- /dev/null +++ b/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.swift @@ -0,0 +1,35 @@ +/** + * 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 sumEvenGrandparent(_ root: TreeNode?) -> Int { + var queue: [(node: TreeNode?, parent: Int, grandparent: Int)] = [(root, -1, -1)] + var res = 0 + while !queue.isEmpty { + let (node, parent, grandparent) = queue.removeFirst() + guard let node = node else { continue } + if grandparent % 2 == 0 { + res += node.val + } + if node.left != nil { + queue.append((node.left, node.val, parent)) + } + if node.right != nil { + queue.append((node.right, node.val, parent)) + } + } + return res + } +} diff --git a/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.ts b/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.ts new file mode 100644 index 00000000..24cdc85e --- /dev/null +++ b/tests/1001-1500/1315. sum-of-nodes-with-even-valued-grandparent/sol.ts @@ -0,0 +1,32 @@ +/** + * 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 sumEvenGrandparent(root: TreeNode | null): number { + const queue: [TreeNode | null, number, number][] = [[root, -1, -1]]; + let res = 0; + while (queue.length > 0) { + const [node, parent, grandparent] = queue.shift()!; + if (node === null) continue; + if (grandparent % 2 === 0) { + res += node.val; + } + if (node.left !== null) { + queue.push([node.left, node.val, parent]); + } + if (node.right !== null) { + queue.push([node.right, node.val, parent]); + } + } + return res; +} diff --git a/tests/1001-1500/1316. distinct-echo-substrings/manifest.yaml b/tests/1001-1500/1316. distinct-echo-substrings/manifest.yaml new file mode 100644 index 00000000..9bcf5b4a --- /dev/null +++ b/tests/1001-1500/1316. distinct-echo-substrings/manifest.yaml @@ -0,0 +1,280 @@ +entry: + id: 1316 + title: "distinct-echo-substrings" + params: + text: + type: string + call: + cpp: "Solution().distinctEchoSubstrings({text})" + rust: "Solution::distinct_echo_substrings({text})" + python3: "Solution().distinctEchoSubstrings({text})" + python2: "Solution().distinctEchoSubstrings({text})" + ruby: "distinct_echo_substrings({text})" + java: "new Solution().distinctEchoSubstrings({text})" + csharp: "new Solution().DistinctEchoSubstrings({text})" + kotlin: "Solution().distinctEchoSubstrings({text})" + go: "distinctEchoSubstrings({text})" + dart: "Solution().distinctEchoSubstrings({text})" + swift: "Solution().distinctEchoSubstrings({text})" + typescript: "distinctEchoSubstrings({text})" + +judge: + type: "exact" + +limits: + time_ms: 10000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().distinctEchoSubstrings(text, {result})" + checker: | + class Checker: + def distinctEchoSubstrings(self, text, result): + if type(result) is not int: + return False + n = len(text) + suffixes = list(range(n)) + ranks = [ord(char) for char in text] + width = 1 + while width < n: + suffixes.sort(key=lambda index: (ranks[index], ranks[index + width] if index + width < n else -1)) + next_ranks = [0] * n + for position in range(1, n): + previous, current = suffixes[position - 1], suffixes[position] + previous_key = (ranks[previous], ranks[previous + width] if previous + width < n else -1) + current_key = (ranks[current], ranks[current + width] if current + width < n else -1) + next_ranks[current] = next_ranks[previous] + (current_key != previous_key) + ranks = next_ranks + if ranks[suffixes[-1]] == n - 1: + break + width *= 2 + positions = [0] * n + for position, start in enumerate(suffixes): + positions[start] = position + lcp = [0] * n + common = 0 + for start in range(n): + position = positions[start] + if position == 0: + common = 0 + continue + previous = suffixes[position - 1] + while start + common < n and previous + common < n and text[start + common] == text[previous + common]: + common += 1 + lcp[position] = common + if common: + common -= 1 + logs = [0] * (n + 1) + for length in range(2, n + 1): + logs[length] = logs[length // 2] + 1 + minimums = [lcp] + size = 1 + while size * 2 <= n: + previous = minimums[-1] + minimums.append([min(previous[index], previous[index + size]) for index in range(n - size * 2 + 1)]) + size *= 2 + def common_prefix(first, second): + if first == second: + return n - first + left, right = positions[first], positions[second] + if left > right: + left, right = right, left + left += 1 + level = logs[right - left + 1] + return min(minimums[level][left], minimums[level][right - (1 << level) + 1]) + echoes = set() + for half in range(1, n // 2 + 1): + full = 2 * half + components = [0] * n + component = 0 + for position in range(1, n): + if lcp[position] < full: + component += 1 + components[position] = component + for start in range(n - full + 1): + if common_prefix(start, start + half) >= half: + echoes.add((full, components[positions[start]])) + return result == len(echoes) + +seed: 1316 + +tests: + - name: "example_abcabcabc" + in: + text: "abcabcabc" + out: 3 + - name: "example_leetcode" + in: + text: "leetcodeleetcode" + out: 2 + - name: "minimum_single_character" + in: + text: "a" + out: 0 + - name: "two_equal_characters" + in: + text: "aa" + out: 1 + - name: "two_distinct_characters" + in: + text: "ab" + out: 0 + - name: "three_uniform_characters" + in: + text: "aaa" + out: 1 + - name: "four_uniform_characters" + in: + text: "aaaa" + out: 2 + - name: "all_distinct" + in: + text: "abcdef" + out: 0 + - name: "alternating_pair" + in: + text: "abab" + out: 1 + - name: "overlapping_alternation" + in: + text: "ababa" + out: 2 + - name: "single_triplet_repeat" + in: + text: "abcabc" + out: 1 + - name: "short_nonuniform_repeat" + in: + text: "aabaaa" + out: 1 + - name: "two_separate_blocks" + in: + text: "abcabcxyzxyz" + out: 2 + - name: "uniform_eight" + in: + text: "zzzzzzzz" + out: 4 + - name: "palindrome_without_echo" + in: + text: "racecar" + out: 0 + - name: "repeated_vowel_block" + in: + text: "aeiouaeiou" + out: 1 + - name: "repeated_consonant_block" + in: + text: "bcdbcd" + out: 1 + - name: "two_repeated_words" + in: + text: "thethequickquick" + out: 2 + - name: "echo_at_end" + in: + text: "xabcabc" + out: 1 + - name: "echo_at_start" + in: + text: "abcabcy" + out: 1 + - name: "uniform_seven" + in: + text: "aaaaaaa" + out: 3 + - name: "alternating_odd_length" + in: + text: "abababa" + out: 2 + - name: "three_triplet_copies" + in: + text: "xyzxyzxyz" + out: 3 + - name: "separated_equal_blocks" + in: + text: "abcxabc" + out: 0 + - name: "long_unique_period" + in: + text: "abcdefghabcdefgh" + out: 1 + - name: "near_period_with_mismatch" + in: + text: "abcdefghabcxefgh" + out: 0 + - name: "repeated_sentence" + in: + text: "thequickbrownfoxthequickbrownfox" + out: 1 + - name: "paired_runs_and_full_repeat" + in: + text: "aabbaabb" + out: 3 + - name: "four_triplet_copies" + in: + text: "abcabcabcabc" + out: 4 + - name: "periodic_prefix_with_break" + in: + text: "abababac" + out: 2 + - name: "uniform_sixteen" + in: + text: "aaaaaaaaaaaaaaaa" + out: 8 + - name: "alternating_sixteen" + in: + text: "abababababababab" + out: 7 + - name: "repeated_asymmetric_word" + in: + text: "mississimississi" + out: 4 + - name: "nonperiodic_with_inner_unique_letters" + in: + text: "abcdefghijklabcxefgh" + out: 0 + - name: "stress_uniform_max" + seed: 131601 + in: + text: + gen: "str" + len: 2000 + alphabet: "a" + - name: "stress_binary_max" + seed: 131602 + in: + text: + gen: "str" + len: 2000 + alphabet: "ab" + - name: "stress_ternary_max" + seed: 131603 + in: + text: + gen: "str" + len: 2000 + alphabet: "abc" + - name: "stress_quaternary_max" + seed: 131604 + in: + text: + gen: "str" + len: 2000 + alphabet: "abcd" + - name: "stress_half_alphabet_max" + seed: 131605 + in: + text: + gen: "str" + len: 2000 + alphabet: "abcdefghijklm" + - name: "stress_full_alphabet_max" + seed: 131606 + in: + text: + gen: "str" + len: 2000 + alphabet: "abcdefghijklmnopqrstuvwxyz" diff --git a/tests/1001-1500/1316. distinct-echo-substrings/sol.cpp b/tests/1001-1500/1316. distinct-echo-substrings/sol.cpp new file mode 100644 index 00000000..c9b00b2f --- /dev/null +++ b/tests/1001-1500/1316. distinct-echo-substrings/sol.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + int distinctEchoSubstrings(string text) { + int n = text.size(); + using ll = long long; + ll b1 = 911382323, b2 = 972663749; + ll m1 = 1000000007, m2 = 1000000009; + vector p1(n + 1, 1), p2(n + 1, 1); + vector h1(n + 1, 0), h2(n + 1, 0); + int a = 'a'; + for (int i = 1; i <= n; i++) { + int v = text[i - 1] - a; + p1[i] = (p1[i - 1] * b1) % m1; + p2[i] = (p2[i - 1] * b2) % m2; + h1[i] = (h1[i - 1] * b1 + v) % m1; + h2[i] = (h2[i - 1] * b2 + v) % m2; + } + auto get = [&](int l, int r) -> pair { + ll v1 = (h1[r] - h1[l] * p1[r - l]) % m1; + ll v2 = (h2[r] - h2[l] * p2[r - l]) % m2; + if (v1 < 0) v1 += m1; + if (v2 < 0) v2 += m2; + return {v1, v2}; + }; + set>> st; + for (int i = 0; i < n; i++) { + int maxLen = (n - i) / 2; + for (int L = 1; L <= maxLen; L++) { + if (get(i, i + L) == get(i + L, i + 2 * L)) { + st.insert({2 * L, get(i, i + 2 * L)}); + } + } + } + return st.size(); + } +}; diff --git a/tests/1001-1500/1316. distinct-echo-substrings/sol.cs b/tests/1001-1500/1316. distinct-echo-substrings/sol.cs new file mode 100644 index 00000000..9c5b649b --- /dev/null +++ b/tests/1001-1500/1316. distinct-echo-substrings/sol.cs @@ -0,0 +1,38 @@ +public class Solution { + public int DistinctEchoSubstrings(string text) { + int n = text.Length; + long b1 = 911382323, b2 = 972663749; + long m1 = 1000000007, m2 = 1000000009; + long[] p1 = new long[n + 1]; + long[] p2 = new long[n + 1]; + long[] h1 = new long[n + 1]; + long[] h2 = new long[n + 1]; + p1[0] = p2[0] = 1; + int a = 'a'; + for (int i = 1; i <= n; i++) { + int v = text[i - 1] - a; + p1[i] = (p1[i - 1] * b1) % m1; + p2[i] = (p2[i - 1] * b2) % m2; + h1[i] = (h1[i - 1] * b1 + v) % m1; + h2[i] = (h2[i - 1] * b2 + v) % m2; + } + Func get = (l, r) => { + long v1 = (h1[r] - h1[l] * p1[r - l]) % m1; + long v2 = (h2[r] - h2[l] * p2[r - l]) % m2; + if (v1 < 0) v1 += m1; + if (v2 < 0) v2 += m2; + return (v1, v2); + }; + var st = new HashSet<(int, long, long)>(); + for (int i = 0; i < n; i++) { + int maxLen = (n - i) / 2; + for (int L = 1; L <= maxLen; L++) { + if (get(i, i + L) == get(i + L, i + 2 * L)) { + var h = get(i, i + 2 * L); + st.Add((2 * L, h.Item1, h.Item2)); + } + } + } + return st.Count; + } +} diff --git a/tests/1001-1500/1316. distinct-echo-substrings/sol.dart b/tests/1001-1500/1316. distinct-echo-substrings/sol.dart new file mode 100644 index 00000000..37dc7025 --- /dev/null +++ b/tests/1001-1500/1316. distinct-echo-substrings/sol.dart @@ -0,0 +1,40 @@ +class Solution { + int distinctEchoSubstrings(String text) { + int n = text.length; + const b1 = 911382323; + const b2 = 972663749; + const m1 = 1000000007; + const m2 = 1000000009; + var p1 = List.filled(n + 1, 1); + var p2 = List.filled(n + 1, 1); + var h1 = List.filled(n + 1, 0); + var h2 = List.filled(n + 1, 0); + const a = 97; + for (int i = 1; i <= n; i++) { + int v = text.codeUnitAt(i - 1) - a; + p1[i] = (p1[i - 1] * b1) % m1; + p2[i] = (p2[i - 1] * b2) % m2; + h1[i] = (h1[i - 1] * b1 + v) % m1; + h2[i] = (h2[i - 1] * b2 + v) % m2; + } + List get(int l, int r) { + int v1 = (h1[r] - h1[l] * p1[r - l]) % m1; + int v2 = (h2[r] - h2[l] * p2[r - l]) % m2; + if (v1 < 0) v1 += m1; + if (v2 < 0) v2 += m2; + return [v1, v2]; + } + var st = {}; + for (int i = 0; i < n; i++) { + int maxLen = (n - i) ~/ 2; + for (int L = 1; L <= maxLen; L++) { + if (get(i, i + L)[0] == get(i + L, i + 2 * L)[0] && + get(i, i + L)[1] == get(i + L, i + 2 * L)[1]) { + var h = get(i, i + 2 * L); + st.add("${2 * L},${h[0]},${h[1]}"); + } + } + } + return st.length; + } +} diff --git a/tests/1001-1500/1316. distinct-echo-substrings/sol.go b/tests/1001-1500/1316. distinct-echo-substrings/sol.go new file mode 100644 index 00000000..b404819a --- /dev/null +++ b/tests/1001-1500/1316. distinct-echo-substrings/sol.go @@ -0,0 +1,45 @@ +func distinctEchoSubstrings(text string) int { + n := len(text) + b1, b2 := int64(911382323), int64(972663749) + m1, m2 := int64(1000000007), int64(1000000009) + p1 := make([]int64, n+1) + p2 := make([]int64, n+1) + h1 := make([]int64, n+1) + h2 := make([]int64, n+1) + p1[0], p2[0] = 1, 1 + a := int64('a') + for i := 1; i <= n; i++ { + v := int64(text[i-1]) - a + p1[i] = (p1[i-1] * b1) % m1 + p2[i] = (p2[i-1] * b2) % m2 + h1[i] = (h1[i-1]*b1 + v) % m1 + h2[i] = (h2[i-1]*b2 + v) % m2 + } + get := func(l, r int) [2]int64 { + v1 := (h1[r] - h1[l]*p1[r-l]) % m1 + v2 := (h2[r] - h2[l]*p2[r-l]) % m2 + if v1 < 0 { + v1 += m1 + } + if v2 < 0 { + v2 += m2 + } + return [2]int64{v1, v2} + } + type entry struct { + len int + h1 int64 + h2 int64 + } + st := make(map[entry]bool) + for i := 0; i < n; i++ { + maxLen := (n - i) / 2 + for L := 1; L <= maxLen; L++ { + if get(i, i+L) == get(i+L, i+2*L) { + h := get(i, i+2*L) + st[entry{2 * L, h[0], h[1]}] = true + } + } + } + return len(st) +} diff --git a/tests/1001-1500/1316. distinct-echo-substrings/sol.java b/tests/1001-1500/1316. distinct-echo-substrings/sol.java new file mode 100644 index 00000000..bba28bad --- /dev/null +++ b/tests/1001-1500/1316. distinct-echo-substrings/sol.java @@ -0,0 +1,42 @@ +class Solution { + public int distinctEchoSubstrings(String text) { + int n = text.length(); + long b1 = 911382323, b2 = 972663749; + long m1 = 1000000007, m2 = 1000000009; + long[] p1 = new long[n + 1]; + long[] p2 = new long[n + 1]; + long[] h1 = new long[n + 1]; + long[] h2 = new long[n + 1]; + p1[0] = p2[0] = 1; + int a = 'a'; + for (int i = 1; i <= n; i++) { + int v = text.charAt(i - 1) - a; + p1[i] = (p1[i - 1] * b1) % m1; + p2[i] = (p2[i - 1] * b2) % m2; + h1[i] = (h1[i - 1] * b1 + v) % m1; + h2[i] = (h2[i - 1] * b2 + v) % m2; + } + java.util.HashSet st = new java.util.HashSet<>(); + for (int i = 0; i < n; i++) { + int maxLen = (n - i) / 2; + for (int L = 1; L <= maxLen; L++) { + long[] left = get(i, i + L, h1, h2, p1, p2, m1, m2); + long[] right = get(i + L, i + 2 * L, h1, h2, p1, p2, m1, m2); + if (left[0] == right[0] && left[1] == right[1]) { + long[] whole = get(i, i + 2 * L, h1, h2, p1, p2, m1, m2); + long hash = (whole[0] << 32) | (whole[1] & 0xffffffffL); + st.add((((long) 2 * L) << 32) | (hash & 0xffffffffL)); + } + } + } + return st.size(); + } + + private long[] get(int l, int r, long[] h1, long[] h2, long[] p1, long[] p2, long m1, long m2) { + long v1 = (h1[r] - h1[l] * p1[r - l]) % m1; + long v2 = (h2[r] - h2[l] * p2[r - l]) % m2; + if (v1 < 0) v1 += m1; + if (v2 < 0) v2 += m2; + return new long[]{v1, v2}; + } +} diff --git a/tests/1001-1500/1316. distinct-echo-substrings/sol.kt b/tests/1001-1500/1316. distinct-echo-substrings/sol.kt new file mode 100644 index 00000000..17a29f5f --- /dev/null +++ b/tests/1001-1500/1316. distinct-echo-substrings/sol.kt @@ -0,0 +1,36 @@ +class Solution { + fun distinctEchoSubstrings(text: String): Int { + val n = text.length + val b1 = 911382323L + val b2 = 972663749L + val m1 = 1000000007L + val m2 = 1000000009L + val p1 = LongArray(n + 1) { 1 } + val p2 = LongArray(n + 1) { 1 } + val h1 = LongArray(n + 1) + val h2 = LongArray(n + 1) + val a = 'a'.code + for (i in 1..n) { + val v = (text[i - 1].code - a).toLong() + p1[i] = (p1[i - 1] * b1) % m1 + p2[i] = (p2[i - 1] * b2) % m2 + h1[i] = (h1[i - 1] * b1 + v) % m1 + h2[i] = (h2[i - 1] * b2 + v) % m2 + } + fun get(l: Int, r: Int): Pair { + val v1 = (h1[r] - h1[l] * p1[r - l]) % m1 + val v2 = (h2[r] - h2[l] * p2[r - l]) % m2 + return Pair(if (v1 < 0) v1 + m1 else v1, if (v2 < 0) v2 + m2 else v2) + } + val st = HashSet>>() + for (i in 0 until n) { + val maxLen = (n - i) / 2 + for (L in 1..maxLen) { + if (get(i, i + L) == get(i + L, i + 2 * L)) { + st.add(Pair(2 * L, get(i, i + 2 * L))) + } + } + } + return st.size + } +} diff --git a/tests/1001-1500/1316. distinct-echo-substrings/sol.py b/tests/1001-1500/1316. distinct-echo-substrings/sol.py new file mode 100644 index 00000000..ee0608a5 --- /dev/null +++ b/tests/1001-1500/1316. distinct-echo-substrings/sol.py @@ -0,0 +1,24 @@ +class Solution: + def distinctEchoSubstrings(self, text: str) -> int: + def get(l, r): + return (h1[r] - h1[l] * p1[r - l]) % m1, (h2[r] - h2[l] * p2[r - l]) % m2 + + n = len(text) + b1, b2 = 911382323, 972663749 + m1, m2 = 10**9 + 7, 10**9 + 9 + p1, p2 = [1] * (n + 1), [1] * (n + 1) + h1, h2 = [0] * (n + 1), [0] * (n + 1) + a = ord("a") + for i, ch in enumerate(text, 1): + v = ord(ch) - a + p1[i] = (p1[i - 1] * b1) % m1 + p2[i] = (p2[i - 1] * b2) % m2 + h1[i] = (h1[i - 1] * b1 + v) % m1 + h2[i] = (h2[i - 1] * b2 + v) % m2 + st = set() + for i in range(n): + m = (n - i) // 2 + for L in range(1, m + 1): + if get(i, i + L) == get(i + L, i + 2 * L): + st.add((2 * L, get(i, i + 2 * L))) + return len(st) diff --git a/tests/1001-1500/1316. distinct-echo-substrings/sol.py2 b/tests/1001-1500/1316. distinct-echo-substrings/sol.py2 new file mode 100644 index 00000000..56b1f09f --- /dev/null +++ b/tests/1001-1500/1316. distinct-echo-substrings/sol.py2 @@ -0,0 +1,28 @@ +class Solution(object): + def distinctEchoSubstrings(self, text): + """ + :type text: str + :rtype: int + """ + def get(l, r): + return (h1[r] - h1[l] * p1[r - l]) % m1, (h2[r] - h2[l] * p2[r - l]) % m2 + + n = len(text) + b1, b2 = 911382323, 972663749 + m1, m2 = 10**9 + 7, 10**9 + 9 + p1, p2 = [1] * (n + 1), [1] * (n + 1) + h1, h2 = [0] * (n + 1), [0] * (n + 1) + a = ord('a') + for i, ch in enumerate(text, 1): + v = ord(ch) - a + p1[i] = (p1[i - 1] * b1) % m1 + p2[i] = (p2[i - 1] * b2) % m2 + h1[i] = (h1[i - 1] * b1 + v) % m1 + h2[i] = (h2[i - 1] * b2 + v) % m2 + st = set() + for i in range(n): + m = (n - i) // 2 + for L in range(1, m + 1): + if get(i, i + L) == get(i + L, i + 2 * L): + st.add((2 * L, get(i, i + 2 * L))) + return len(st) diff --git a/tests/1001-1500/1316. distinct-echo-substrings/sol.rb b/tests/1001-1500/1316. distinct-echo-substrings/sol.rb new file mode 100644 index 00000000..c895f473 --- /dev/null +++ b/tests/1001-1500/1316. distinct-echo-substrings/sol.rb @@ -0,0 +1,33 @@ +# @param {String} text +# @return {Integer} +def distinct_echo_substrings(text) + def get(l, r) + [( @h1[r] - @h1[l] * @p1[r - l] ) % @m1, ( @h2[r] - @h2[l] * @p2[r - l] ) % @m2] + end + + n = text.length + b1, b2 = 911382323, 972663749 + @m1, @m2 = 10**9 + 7, 10**9 + 9 + @p1 = [1] * (n + 1) + @p2 = [1] * (n + 1) + @h1 = [0] * (n + 1) + @h2 = [0] * (n + 1) + a = 'a'.ord + text.each_char.with_index(1) do |ch, i| + v = ch.ord - a + @p1[i] = (@p1[i - 1] * b1) % @m1 + @p2[i] = (@p2[i - 1] * b2) % @m2 + @h1[i] = (@h1[i - 1] * b1 + v) % @m1 + @h2[i] = (@h2[i - 1] * b2 + v) % @m2 + end + st = Set.new + (0...n).each do |i| + m = (n - i) / 2 + (1..m).each do |l| + if get(i, i + l) == get(i + l, i + 2 * l) + st.add([2 * l, get(i, i + 2 * l)]) + end + end + end + st.size +end diff --git a/tests/1001-1500/1316. distinct-echo-substrings/sol.rs b/tests/1001-1500/1316. distinct-echo-substrings/sol.rs new file mode 100644 index 00000000..e441dec9 --- /dev/null +++ b/tests/1001-1500/1316. distinct-echo-substrings/sol.rs @@ -0,0 +1,38 @@ +impl Solution { + pub fn distinct_echo_substrings(text: String) -> i32 { + let n = text.len(); + let b1: i64 = 911382323; + let b2: i64 = 972663749; + let m1: i64 = 1000000007; + let m2: i64 = 1000000009; + let mut p1 = vec![1i64; n + 1]; + let mut p2 = vec![1i64; n + 1]; + let mut h1 = vec![0i64; n + 1]; + let mut h2 = vec![0i64; n + 1]; + let a = 'a' as i64; + let bytes = text.as_bytes(); + for i in 1..=n { + let v = bytes[i - 1] as i64 - a; + p1[i] = (p1[i - 1] * b1) % m1; + p2[i] = (p2[i - 1] * b2) % m2; + h1[i] = (h1[i - 1] * b1 + v) % m1; + h2[i] = (h2[i - 1] * b2 + v) % m2; + } + let get = |l: usize, r: usize| -> (i64, i64) { + let v1 = (h1[r] - h1[l] * p1[r - l]) % m1; + let v2 = (h2[r] - h2[l] * p2[r - l]) % m2; + (if v1 < 0 { v1 + m1 } else { v1 }, if v2 < 0 { v2 + m2 } else { v2 }) + }; + let mut st = std::collections::HashSet::new(); + for i in 0..n { + let max_len = (n - i) / 2; + for l in 1..=max_len { + if get(i, i + l) == get(i + l, i + 2 * l) { + let h = get(i, i + 2 * l); + st.insert((2 * l, h)); + } + } + } + st.len() as i32 + } +} diff --git a/tests/1001-1500/1316. distinct-echo-substrings/sol.swift b/tests/1001-1500/1316. distinct-echo-substrings/sol.swift new file mode 100644 index 00000000..5c35b4ff --- /dev/null +++ b/tests/1001-1500/1316. distinct-echo-substrings/sol.swift @@ -0,0 +1,42 @@ +class Solution { + func distinctEchoSubstrings(_ text: String) -> Int { + let n = text.count + let b1 = 31 + let b2 = 37 + let m1 = 1000000007 + let m2 = 1000000009 + var p1 = [Int](repeating: 1, count: n + 1) + var p2 = [Int](repeating: 1, count: n + 1) + var h1 = [Int](repeating: 0, count: n + 1) + var h2 = [Int](repeating: 0, count: n + 1) + let a = Int("a".unicodeScalars.first!.value) + let chars = Array(text) + for i in 1...n { + let v = Int(chars[i - 1].unicodeScalars.first!.value) - a + p1[i] = (p1[i - 1] * b1) % m1 + p2[i] = (p2[i - 1] * b2) % m2 + h1[i] = (h1[i - 1] * b1 + v) % m1 + h2[i] = (h2[i - 1] * b2 + v) % m2 + } + func get(_ l: Int, _ r: Int) -> (Int, Int) { + var v1 = (h1[r] - h1[l] * p1[r - l]) % m1 + var v2 = (h2[r] - h2[l] * p2[r - l]) % m2 + if v1 < 0 { v1 += m1 } + if v2 < 0 { v2 += m2 } + return (v1, v2) + } + var st = Set() + for i in 0.. 0 { + for L in 1...maxLen { + if get(i, i + L) == get(i + L, i + 2 * L) { + let h = get(i, i + 2 * L) + st.insert("\(2 * L),\(h.0),\(h.1)") + } + } + } + } + return st.count + } +} diff --git a/tests/1001-1500/1316. distinct-echo-substrings/sol.ts b/tests/1001-1500/1316. distinct-echo-substrings/sol.ts new file mode 100644 index 00000000..b9c07f3d --- /dev/null +++ b/tests/1001-1500/1316. distinct-echo-substrings/sol.ts @@ -0,0 +1,13 @@ +function distinctEchoSubstrings(text: string): number { + const found = new Set(); + const n = text.length; + for (let start = 0; start < n; start++) { + for (let length = 1; start + 2 * length <= n; length++) { + const first = text.slice(start, start + length); + if (first === text.slice(start + length, start + 2 * length)) { + found.add(first); + } + } + } + return found.size; +} diff --git a/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/manifest.yaml b/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/manifest.yaml new file mode 100644 index 00000000..3e3d9f08 --- /dev/null +++ b/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/manifest.yaml @@ -0,0 +1,183 @@ +entry: + id: 1317 + title: "convert-integer-to-the-sum-of-two-no-zero-integers" + params: + n: + type: int + call: + cpp: "Solution().getNoZeroIntegers({n})" + rust: "Solution::get_no_zero_integers({n})" + python3: "Solution().getNoZeroIntegers({n})" + python2: "Solution().getNoZeroIntegers({n})" + ruby: "get_no_zero_integers({n})" + java: "new Solution().getNoZeroIntegers({n})" + csharp: "new Solution().GetNoZeroIntegers({n})" + kotlin: "Solution().getNoZeroIntegers({n})" + go: "getNoZeroIntegers({n})" + dart: "Solution().getNoZeroIntegers({n})" + swift: "Solution().getNoZeroIntegers({n})" + typescript: "getNoZeroIntegers({n})" + +judge: + type: "exact" + +limits: + time_ms: 500 + memory_mb: 300 + +oracle: + python3: + call: "Checker().getNoZeroIntegers(n, {result})" + checker: | + class Checker: + def getNoZeroIntegers(self, n, result): + if not isinstance(result, list) or len(result) != 2: + return False + a, b = result + if not isinstance(a, int) or not isinstance(b, int) or a <= 0 or b <= 0: + return False + return a + b == n and '0' not in str(a) and '0' not in str(b) + +seed: 131700 + +tests: + - name: "example_two" + in: + n: 2 + - name: "example_eleven" + in: + n: 11 + - name: "small_three" + in: + n: 3 + - name: "small_four" + in: + n: 4 + - name: "single_digit_five" + in: + n: 5 + - name: "single_digit_nine" + in: + n: 9 + - name: "ten" + in: + n: 10 + - name: "twenty" + in: + n: 20 + - name: "twenty_one" + in: + n: 21 + - name: "all_nines_boundary" + in: + n: 99 + - name: "one_hundred" + in: + n: 100 + - name: "one_hundred_one" + in: + n: 101 + - name: "one_hundred_ten" + in: + n: 110 + - name: "one_hundred_eleven" + in: + n: 111 + - name: "two_hundred" + in: + n: 200 + - name: "two_hundred_two" + in: + n: 202 + - name: "three_digit_nines" + in: + n: 999 + - name: "one_thousand" + in: + n: 1000 + - name: "one_thousand_one" + in: + n: 1001 + - name: "one_thousand_ten" + in: + n: 1010 + - name: "one_thousand_one_hundred" + in: + n: 1100 + - name: "one_thousand_one_hundred_one" + in: + n: 1101 + - name: "two_thousand_two" + in: + n: 2002 + - name: "three_thousand_three" + in: + n: 3003 + - name: "four_thousand_four" + in: + n: 4004 + - name: "five_thousand_five" + in: + n: 5005 + - name: "six_thousand_six" + in: + n: 6006 + - name: "seven_thousand_seven" + in: + n: 7007 + - name: "eight_thousand_eight" + in: + n: 8008 + - name: "nine_thousand_nine" + in: + n: 9009 + - name: "near_maximum" + in: + n: 9998 + - name: "maximum" + in: + n: 10000 + - name: "mixed_digits" + in: + n: 4321 + - name: "palindromic_digits" + in: + n: 4554 + - name: "alternating_digits" + in: + n: 9099 + - name: "generated_small" + seed: 131701 + in: + n: + gen: "int" + min: 2 + max: 99 + - name: "generated_medium" + seed: 131702 + in: + n: + gen: "int" + min: 100 + max: 999 + - name: "generated_large" + seed: 131703 + in: + n: + gen: "int" + min: 1000 + max: 9999 + - name: "generated_boundary" + seed: 131704 + in: + n: + gen: "int" + min: 9900 + max: 10000 + - name: "generated_full_range" + seed: 131705 + in: + n: + gen: "int" + min: 2 + max: 10000 diff --git a/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.cpp b/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.cpp new file mode 100644 index 00000000..d9ffddeb --- /dev/null +++ b/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + vector getNoZeroIntegers(int n) { + for (int i = 1; i < n; i++) { + if (to_string(i).find('0') == string::npos && + to_string(n - i).find('0') == string::npos) { + return {i, n - i}; + } + } + return {}; + } +}; diff --git a/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.cs b/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.cs new file mode 100644 index 00000000..37c69a6e --- /dev/null +++ b/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.cs @@ -0,0 +1,10 @@ +public class Solution { + public int[] GetNoZeroIntegers(int n) { + for (int i = 1; i < n; i++) { + if (!i.ToString().Contains('0') && !(n - i).ToString().Contains('0')) { + return new int[] { i, n - i }; + } + } + return new int[] {}; + } +} diff --git a/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.dart b/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.dart new file mode 100644 index 00000000..32bcb737 --- /dev/null +++ b/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.dart @@ -0,0 +1,10 @@ +class Solution { + List getNoZeroIntegers(int n) { + for (int i = 1; i < n; i++) { + if (!i.toString().contains('0') && !(n - i).toString().contains('0')) { + return [i, n - i]; + } + } + return []; + } +} diff --git a/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.go b/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.go new file mode 100644 index 00000000..cd886bac --- /dev/null +++ b/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.go @@ -0,0 +1,18 @@ +func getNoZeroIntegers(n int) []int { + for i := 1; i < n; i++ { + if !containsZero(i) && !containsZero(n - i) { + return []int{i, n - i} + } + } + return []int{} +} + +func containsZero(num int) bool { + for num > 0 { + if num%10 == 0 { + return true + } + num /= 10 + } + return false +} diff --git a/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.java b/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.java new file mode 100644 index 00000000..1aa54332 --- /dev/null +++ b/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.java @@ -0,0 +1,10 @@ +class Solution { + public int[] getNoZeroIntegers(int n) { + for (int i = 1; i < n; i++) { + if (!String.valueOf(i).contains("0") && !String.valueOf(n - i).contains("0")) { + return new int[]{i, n - i}; + } + } + return new int[]{}; + } +} diff --git a/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.kt b/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.kt new file mode 100644 index 00000000..5227ecbc --- /dev/null +++ b/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.kt @@ -0,0 +1,10 @@ +class Solution { + fun getNoZeroIntegers(n: Int): IntArray { + for (i in 1 until n) { + if (!i.toString().contains('0') && !(n - i).toString().contains('0')) { + return intArrayOf(i, n - i) + } + } + return intArrayOf() + } +} diff --git a/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.py b/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.py new file mode 100644 index 00000000..a071c31c --- /dev/null +++ b/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.py @@ -0,0 +1,7 @@ +class Solution: + def getNoZeroIntegers(self, n: int) -> List[int]: + return next( + [i, n - i] + for i in range(1, n) + if "0" not in str(i) and "0" not in str(n - i) + ) diff --git a/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.py2 b/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.py2 new file mode 100644 index 00000000..22202fd5 --- /dev/null +++ b/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.py2 @@ -0,0 +1,9 @@ +class Solution(object): + def getNoZeroIntegers(self, n): + """ + :type n: int + :rtype: List[int] + """ + for i in range(1, n): + if '0' not in str(i) and '0' not in str(n - i): + return [i, n - i] diff --git a/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.rb b/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.rb new file mode 100644 index 00000000..502ebb96 --- /dev/null +++ b/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.rb @@ -0,0 +1,9 @@ +# @param {Integer} n +# @return {Integer[]} +def get_no_zero_integers(n) + (1...n).each do |i| + if !i.to_s.include?('0') && !(n - i).to_s.include?('0') + return [i, n - i] + end + end +end diff --git a/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.rs b/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.rs new file mode 100644 index 00000000..2a9a1a42 --- /dev/null +++ b/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.rs @@ -0,0 +1,10 @@ +impl Solution { + pub fn get_no_zero_integers(n: i32) -> Vec { + for i in 1..n { + if !i.to_string().contains('0') && !(n - i).to_string().contains('0') { + return vec![i, n - i]; + } + } + vec![] + } +} diff --git a/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.swift b/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.swift new file mode 100644 index 00000000..bfd8b735 --- /dev/null +++ b/tests/1001-1500/1317. convert-integer-to-the-sum-of-two-no-zero-integers/sol.swift @@ -0,0 +1,10 @@ +class Solution { + func getNoZeroIntegers(_ n: Int) -> [Int] { + for i in 1..>= 1 + b >>= 1 + c >>= 1 + return result == flips +seed: 1318 +tests: + - name: example-one + in: + a: 2 + b: 6 + c: 5 + out: 3 + - name: example-two + in: + a: 4 + b: 2 + c: 7 + out: 1 + - name: example-three + in: + a: 1 + b: 2 + c: 3 + out: 0 + - name: minimum-values-already-match + in: + a: 1 + b: 1 + c: 1 + out: 0 + - name: minimum-values-clear-one + in: + a: 1 + b: 1 + c: 2 + out: 3 + - name: minimum-values-create-bit + in: + a: 1 + b: 2 + c: 4 + out: 3 + - name: single-bit-clear-a + in: + a: 8 + b: 1 + c: 1 + out: 1 + - name: single-bit-clear-b + in: + a: 1 + b: 8 + c: 1 + out: 1 + - name: single-bit-create-high + in: + a: 1 + b: 1 + c: 1025 + out: 1 + - name: target-is-or + in: + a: 42 + b: 21 + c: 63 + out: 0 + - name: overlapping-ones-must-clear-twice + in: + a: 7 + b: 7 + c: 1 + out: 4 + - name: target-subset-of-a + in: + a: 63 + b: 1 + c: 21 + out: 3 + - name: target-superset-needs-three-bits + in: + a: 21 + b: 1 + c: 63 + out: 3 + - name: disjoint-operands-mixed-target + in: + a: 10 + b: 5 + c: 3 + out: 2 + - name: mixed-small-pattern + in: + a: 12 + b: 10 + c: 9 + out: 3 + - name: mixed-medium-pattern + in: + a: 37 + b: 58 + c: 19 + out: 4 + - name: same-operands-clear-all + in: + a: 42 + b: 42 + c: 1 + out: 7 + - name: alternating-eight-bit-clear + in: + a: 85 + b: 170 + c: 1 + out: 7 + - name: alternating-eight-bit-create + in: + a: 85 + b: 170 + c: 255 + out: 0 + - name: nonoverlapping-power-bits + in: + a: 1024 + b: 2048 + c: 3072 + out: 0 + - name: clear-two-power-bits + in: + a: 1024 + b: 2048 + c: 1 + out: 3 + - name: create-two-power-bits + in: + a: 1 + b: 1 + c: 3073 + out: 2 + - name: twelve-bit-overlap + in: + a: 4095 + b: 3855 + c: 240 + out: 16 + - name: high-bit-preserved + in: + a: 536870912 + b: 1 + c: 536870913 + out: 0 + - name: high-bit-created + in: + a: 1 + b: 1 + c: 536870913 + out: 1 + - name: high-bit-cleared-from-both + in: + a: 536870913 + b: 536870913 + c: 1 + out: 2 + - name: thirty-bit-all-ones-clear + in: + a: 1073741823 + b: 1 + c: 1 + out: 29 + - name: thirty-bit-all-ones-create + in: + a: 1 + b: 1 + c: 1073741823 + out: 29 + - name: alternating-thirty-bit-complementary + in: + a: 715827882 + b: 357913941 + c: 1073741823 + out: 0 + - name: alternating-thirty-bit-clear + in: + a: 715827882 + b: 715827882 + c: 1 + out: 31 + - name: alternating-thirty-bit-create + in: + a: 1 + b: 1 + c: 715827883 + out: 15 + - name: near-maximum-already-match + in: + a: 999999999 + b: 1 + c: 999999999 + out: 0 + - name: near-maximum-clear-overlapping + in: + a: 1000000000 + b: 1000000000 + c: 1 + out: 27 + - name: near-maximum-create-missing + in: + a: 1 + b: 1 + c: 1000000000 + out: 15 + - name: decimal-large-mixed-one + in: + a: 123456789 + b: 987654321 + c: 555555555 + out: 23 + - name: decimal-large-mixed-two + in: + a: 314159265 + b: 271828182 + c: 161803398 + out: 18 + - name: sparse-bits-across-range + in: + a: 536870913 + b: 268435458 + c: 805306371 + out: 0 + - name: dense-target-with-sparse-operands + in: + a: 536870913 + b: 268435458 + c: 1073741823 + out: 26 + - name: sparse-target-with-dense-operands + in: + a: 1073741823 + b: 1073741823 + c: 536870913 + out: 56 + - name: maximum-constraint-mixed + in: + a: 1000000000 + b: 999999999 + c: 536870912 + out: 32 diff --git a/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.cpp b/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.cpp new file mode 100644 index 00000000..90ec128b --- /dev/null +++ b/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int minFlips(int a, int b, int c) { + int count = 0; + while (a != 0 || b != 0 || c != 0) { + int abit = a & 1; + int bbit = b & 1; + int cbit = c & 1; + + if (cbit == 0) { + if (abit == 1) count++; + if (bbit == 1) count++; + } else { + if (abit == 0 && bbit == 0) count++; + } + + a >>= 1; + b >>= 1; + c >>= 1; + } + return count; + } +}; diff --git a/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.cs b/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.cs new file mode 100644 index 00000000..3093fee7 --- /dev/null +++ b/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.cs @@ -0,0 +1,22 @@ +public class Solution { + public int MinFlips(int a, int b, int c) { + int count = 0; + while (a != 0 || b != 0 || c != 0) { + int abit = a & 1; + int bbit = b & 1; + int cbit = c & 1; + + if (cbit == 0) { + if (abit == 1) count++; + if (bbit == 1) count++; + } else { + if (abit == 0 && bbit == 0) count++; + } + + a >>= 1; + b >>= 1; + c >>= 1; + } + return count; + } +} diff --git a/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.dart b/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.dart new file mode 100644 index 00000000..ffa91154 --- /dev/null +++ b/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.dart @@ -0,0 +1,21 @@ +class Solution { + int minFlips(int a, int b, int c) { + int flips = 0; + while (a != 0 || b != 0 || c != 0) { + int abit = a & 1; + int bbit = b & 1; + int cbit = c & 1; + + if (cbit == 0) { + flips += abit + bbit; + } else if ((abit | bbit) == 0) { + flips++; + } + + a >>= 1; + b >>= 1; + c >>= 1; + } + return flips; + } +} diff --git a/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.go b/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.go new file mode 100644 index 00000000..32df59ab --- /dev/null +++ b/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.go @@ -0,0 +1,26 @@ +func minFlips(a int, b int, c int) int { + count := 0 + for a != 0 || b != 0 || c != 0 { + abit := a & 1 + bbit := b & 1 + cbit := c & 1 + + if cbit == 0 { + if abit == 1 { + count++ + } + if bbit == 1 { + count++ + } + } else { + if abit == 0 && bbit == 0 { + count++ + } + } + + a >>= 1 + b >>= 1 + c >>= 1 + } + return count +} diff --git a/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.java b/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.java new file mode 100644 index 00000000..e501dbce --- /dev/null +++ b/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.java @@ -0,0 +1,22 @@ +class Solution { + public int minFlips(int a, int b, int c) { + int count = 0; + while (a != 0 || b != 0 || c != 0) { + int abit = a & 1; + int bbit = b & 1; + int cbit = c & 1; + + if (cbit == 0) { + if (abit == 1) count++; + if (bbit == 1) count++; + } else { + if (abit == 0 && bbit == 0) count++; + } + + a >>= 1; + b >>= 1; + c >>= 1; + } + return count; + } +} diff --git a/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.kt b/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.kt new file mode 100644 index 00000000..df279196 --- /dev/null +++ b/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.kt @@ -0,0 +1,25 @@ +class Solution { + fun minFlips(a: Int, b: Int, c: Int): Int { + var count = 0 + var aa = a + var bb = b + var cc = c + while (aa != 0 || bb != 0 || cc != 0) { + val abit = aa and 1 + val bbit = bb and 1 + val cbit = cc and 1 + + if (cbit == 0) { + if (abit == 1) count++ + if (bbit == 1) count++ + } else { + if (abit == 0 && bbit == 0) count++ + } + + aa = aa shr 1 + bb = bb shr 1 + cc = cc shr 1 + } + return count + } +} diff --git a/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.py b/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.py new file mode 100644 index 00000000..f9f58317 --- /dev/null +++ b/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.py @@ -0,0 +1,22 @@ +class Solution: + def minFlips(self, a: int, b: int, c: int) -> int: + count = 0 + while a != 0 or b != 0 or c != 0: + abit = a & 1 + bbit = b & 1 + cbit = c & 1 + + if cbit == 0: + if abit == 1: + count += 1 + if bbit == 1: + count += 1 + else: + if abit == 0 and bbit == 0: + count += 1 + + a >>= 1 + b >>= 1 + c >>= 1 + + return count diff --git a/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.py2 b/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.py2 new file mode 100644 index 00000000..0fa330e4 --- /dev/null +++ b/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.py2 @@ -0,0 +1,28 @@ +class Solution(object): + def minFlips(self, a, b, c): + """ + :type a: int + :type b: int + :type c: int + :rtype: int + """ + count = 0 + while a != 0 or b != 0 or c != 0: + abit = a & 1 + bbit = b & 1 + cbit = c & 1 + + if cbit == 0: + if abit == 1: + count += 1 + if bbit == 1: + count += 1 + else: + if abit == 0 and bbit == 0: + count += 1 + + a >>= 1 + b >>= 1 + c >>= 1 + + return count diff --git a/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.rb b/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.rb new file mode 100644 index 00000000..c55c7c4a --- /dev/null +++ b/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.rb @@ -0,0 +1,24 @@ +# @param {Integer} a +# @param {Integer} b +# @param {Integer} c +# @return {Integer} +def min_flips(a, b, c) + count = 0 + while a != 0 or b != 0 or c != 0 + abit = a & 1 + bbit = b & 1 + cbit = c & 1 + + if cbit == 0 + count += 1 if abit == 1 + count += 1 if bbit == 1 + else + count += 1 if abit == 0 and bbit == 0 + end + + a >>= 1 + b >>= 1 + c >>= 1 + end + count +end diff --git a/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.rs b/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.rs new file mode 100644 index 00000000..86b2c5bf --- /dev/null +++ b/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.rs @@ -0,0 +1,25 @@ +impl Solution { + pub fn min_flips(a: i32, b: i32, c: i32) -> i32 { + let mut count = 0; + let mut aa = a; + let mut bb = b; + let mut cc = c; + while aa != 0 || bb != 0 || cc != 0 { + let abit = aa & 1; + let bbit = bb & 1; + let cbit = cc & 1; + + if cbit == 0 { + if abit == 1 { count += 1; } + if bbit == 1 { count += 1; } + } else { + if abit == 0 && bbit == 0 { count += 1; } + } + + aa >>= 1; + bb >>= 1; + cc >>= 1; + } + count + } +} diff --git a/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.swift b/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.swift new file mode 100644 index 00000000..9b5b34d5 --- /dev/null +++ b/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.swift @@ -0,0 +1,25 @@ +class Solution { + func minFlips(_ a: Int, _ b: Int, _ c: Int) -> Int { + var count = 0 + var aa = a + var bb = b + var cc = c + while aa != 0 || bb != 0 || cc != 0 { + let abit = aa & 1 + let bbit = bb & 1 + let cbit = cc & 1 + + if cbit == 0 { + if abit == 1 { count += 1 } + if bbit == 1 { count += 1 } + } else { + if abit == 0 && bbit == 0 { count += 1 } + } + + aa >>= 1 + bb >>= 1 + cc >>= 1 + } + return count + } +} diff --git a/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.ts b/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.ts new file mode 100644 index 00000000..70e98f33 --- /dev/null +++ b/tests/1001-1500/1318. minimum-flips-to-make-a-or-b-equal-to-c/sol.ts @@ -0,0 +1,20 @@ +function minFlips(a: number, b: number, c: number): number { + let count = 0; + while (a !== 0 || b !== 0 || c !== 0) { + const abit = a & 1; + const bbit = b & 1; + const cbit = c & 1; + + if (cbit === 0) { + if (abit === 1) count++; + if (bbit === 1) count++; + } else { + if (abit === 0 && bbit === 0) count++; + } + + a >>= 1; + b >>= 1; + c >>= 1; + } + return count; +} diff --git a/tests/1001-1500/1319. number-of-operations-to-make-network-connected/manifest.yaml b/tests/1001-1500/1319. number-of-operations-to-make-network-connected/manifest.yaml new file mode 100644 index 00000000..d0d8face --- /dev/null +++ b/tests/1001-1500/1319. number-of-operations-to-make-network-connected/manifest.yaml @@ -0,0 +1,849 @@ +entry: + id: 1319 + title: "number-of-operations-to-make-network-connected" + params: + n: + type: int + connections: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().makeConnected({n}, {connections})" + rust: "Solution::make_connected({n}, {connections})" + python3: "Solution().makeConnected({n}, {connections})" + python2: "Solution().makeConnected({n}, {connections})" + ruby: "make_connected({n}, {connections})" + java: "new Solution().makeConnected({n}, {connections})" + csharp: "new Solution().MakeConnected({n}, {connections})" + kotlin: "Solution().makeConnected({n}, {connections})" + go: "makeConnected({n}, {connections})" + dart: "Solution().makeConnected({n}, {connections})" + swift: "Solution().makeConnected({n}, {connections})" + typescript: "makeConnected({n}, {connections})" +judge: + type: "exact" +limits: + time_ms: 1000 + memory_mb: 300 +oracle: + python3: + call: "Checker().makeConnected(n, connections, {result})" + checker: | + class Checker: + def makeConnected(self, n, connections, result): + graph = [[] for _ in range(n)] + for a, b in connections: + graph[a].append(b) + graph[b].append(a) + components = 0 + seen = [False] * n + for start in range(n): + if seen[start]: + continue + components += 1 + seen[start] = True + stack = [start] + while stack: + node = stack.pop() + for neighbor in graph[node]: + if not seen[neighbor]: + seen[neighbor] = True + stack.append(neighbor) + expected = -1 if len(connections) < n - 1 else components - 1 + return isinstance(result, int) and not isinstance(result, bool) and result == expected +seed: 1319 +tests: + - name: "official_one" + in: + n: 4 + connections: + - [0, 1] + - [0, 2] + - [1, 2] + out: 1 + - name: "official_two" + in: + n: 6 + connections: + - [0, 1] + - [0, 2] + - [0, 3] + - [1, 2] + - [1, 3] + out: 2 + - name: "official_three" + in: + n: 6 + connections: + - [0, 1] + - [0, 2] + - [0, 3] + - [1, 2] + out: -1 + - name: "single_computer" + in: + n: 1 + connections: [] + out: 0 + - name: "two_connected" + in: + n: 2 + connections: + - [0, 1] + out: 0 + - name: "four_one_cable" + in: + n: 4 + connections: + - [0, 1] + out: -1 + - name: "three_path" + in: + n: 3 + connections: + - [0, 1] + - [1, 2] + out: 0 + - name: "three_triangle" + in: + n: 3 + connections: + - [0, 1] + - [1, 2] + - [0, 2] + out: 0 + - name: "three_insufficient" + in: + n: 3 + connections: + - [0, 1] + out: -1 + - name: "four_cycle_and_isolate" + in: + n: 4 + connections: + - [0, 1] + - [1, 2] + - [0, 2] + out: 1 + - name: "four_two_pairs" + in: + n: 4 + connections: + - [0, 1] + - [2, 3] + out: -1 + - name: "four_complete" + in: + n: 4 + connections: + - [0, 1] + - [0, 2] + - [0, 3] + - [1, 2] + - [1, 3] + - [2, 3] + out: 0 + - name: "five_cycle_two_isolates" + in: + n: 5 + connections: + - [0, 1] + - [1, 2] + - [0, 2] + - [2, 3] + out: 1 + - name: "five_exact_tree" + in: + n: 5 + connections: + - [0, 1] + - [0, 2] + - [2, 3] + - [2, 4] + out: 0 + - name: "five_too_few" + in: + n: 5 + connections: + - [0, 1] + - [2, 3] + - [0, 2] + out: -1 + - name: "six_two_triangles" + in: + n: 6 + connections: + - [0, 1] + - [1, 2] + - [0, 2] + - [3, 4] + - [4, 5] + out: 1 + - name: "six_three_pairs_insufficient" + in: + n: 6 + connections: + - [0, 1] + - [2, 3] + - [4, 5] + out: -1 + - name: "six_complete_component" + in: + n: 6 + connections: + - [0, 1] + - [0, 2] + - [1, 2] + - [0, 3] + - [1, 3] + - [2, 3] + - [4, 5] + out: 1 + - name: "seven_two_cycles" + in: + n: 7 + connections: + - [0, 1] + - [1, 2] + - [2, 3] + - [0, 3] + - [4, 5] + - [5, 6] + - [4, 6] + out: 1 + - name: "seven_single_dense_component" + in: + n: 7 + connections: + - [0, 1] + - [0, 2] + - [0, 3] + - [1, 2] + - [1, 3] + - [2, 3] + out: 3 + - name: "eight_four_pairs" + in: + n: 8 + connections: + - [0, 1] + - [2, 3] + - [4, 5] + - [6, 7] + - [0, 2] + - [0, 4] + - [0, 6] + out: 0 + - name: "eight_two_components" + in: + n: 8 + connections: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 0] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 4] + out: 1 + - name: "nine_two_cycles_and_isolate" + in: + n: 9 + connections: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 0] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 4] + out: 2 + - name: "nine_tree" + in: + n: 9 + connections: + - [0, 1] + - [0, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [2, 6] + - [3, 7] + - [3, 8] + out: 0 + - name: "ten_three_components" + in: + n: 10 + connections: + - [0, 1] + - [1, 2] + - [2, 0] + - [3, 4] + - [4, 5] + - [5, 3] + - [6, 7] + - [7, 8] + - [8, 9] + out: 2 + - name: "ten_underprovisioned" + in: + n: 10 + connections: + - [0, 1] + - [2, 3] + - [4, 5] + - [6, 7] + - [8, 9] + - [0, 2] + - [4, 6] + - [0, 4] + out: -1 + - name: "twelve_ring" + in: + n: 12 + connections: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + - [10, 11] + - [0, 11] + out: 0 + - name: "twelve_four_triangles" + in: + n: 12 + connections: + - [0, 1] + - [1, 2] + - [0, 2] + - [3, 4] + - [4, 5] + - [3, 5] + - [6, 7] + - [7, 8] + - [6, 8] + - [9, 10] + - [10, 11] + - [9, 11] + out: 3 + - name: "fifteen_connected_tree" + in: + n: 15 + connections: + - [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] + out: 0 + - name: "fifteen_two_dense_components" + in: + n: 15 + connections: + - [0, 1] + - [0, 2] + - [0, 3] + - [1, 2] + - [1, 3] + - [2, 3] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + - [10, 11] + - [11, 12] + - [12, 13] + - [13, 14] + out: 1 + - name: "twenty_four_clusters" + in: + n: 24 + connections: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [0, 5] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + - [10, 11] + - [6, 11] + - [12, 13] + - [13, 14] + - [14, 15] + - [15, 16] + - [16, 17] + - [12, 17] + - [18, 19] + - [19, 20] + - [20, 21] + - [21, 22] + - [22, 23] + - [18, 23] + out: 3 + - name: "twenty_five_star" + in: + n: 25 + connections: + - [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] + - [0, 20] + - [0, 21] + - [0, 22] + - [0, 23] + - [0, 24] + out: 0 + - name: "thirty_two_cycles" + in: + n: 32 + connections: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 0] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 4] + - [8, 9] + - [9, 10] + - [10, 11] + - [11, 8] + - [12, 13] + - [13, 14] + - [14, 15] + - [15, 12] + - [16, 17] + - [17, 18] + - [18, 19] + - [19, 16] + - [20, 21] + - [21, 22] + - [22, 23] + - [23, 20] + - [24, 25] + - [25, 26] + - [26, 27] + - [27, 24] + - [28, 29] + - [29, 30] + - [30, 31] + - [31, 28] + out: 7 + - name: "fifty_path" + in: + n: 50 + connections: + - [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] + out: 0 + - name: "fifty_isolated_with_dense_core" + in: + n: 50 + connections: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [0, 5] + - [0, 6] + - [0, 7] + - [0, 8] + - [0, 9] + - [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] + - [3, 4] + - [3, 5] + - [3, 6] + - [3, 7] + - [3, 8] + - [3, 9] + - [4, 5] + - [4, 6] + - [4, 7] + - [4, 8] + - [4, 9] + - [5, 6] + - [5, 7] + - [5, 8] + - [5, 9] + - [6, 7] + - [6, 8] + - [6, 9] + - [7, 8] + - [7, 9] + - [8, 9] + out: -1 + - name: "sixty_two_cycle_components" + in: + n: 62 + connections: + - [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, 0] + - [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, 50] + - [50, 51] + - [51, 52] + - [52, 53] + - [53, 54] + - [54, 55] + - [55, 56] + - [56, 57] + - [57, 58] + - [58, 59] + - [59, 60] + - [60, 61] + - [61, 31] + - name: "hundred_long_path" + in: + n: 100 + connections: + - [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] + - [49, 50] + - [50, 51] + - [51, 52] + - [52, 53] + - [53, 54] + - [54, 55] + - [55, 56] + - [56, 57] + - [57, 58] + - [58, 59] + - [59, 60] + - [60, 61] + - [61, 62] + - [62, 63] + - [63, 64] + - [64, 65] + - [65, 66] + - [66, 67] + - [67, 68] + - [68, 69] + - [69, 70] + - [70, 71] + - [71, 72] + - [72, 73] + - [73, 74] + - [74, 75] + - [75, 76] + - [76, 77] + - [77, 78] + - [78, 79] + - [79, 80] + - [80, 81] + - [81, 82] + - [82, 83] + - [83, 84] + - [84, 85] + - [85, 86] + - [86, 87] + - [87, 88] + - [88, 89] + - [89, 90] + - [90, 91] + - [91, 92] + - [92, 93] + - [93, 94] + - [94, 95] + - [95, 96] + - [96, 97] + - [97, 98] + - [98, 99] + - name: "twenty_one_component_and_isolates" + in: + n: 21 + connections: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [1, 2] + - [1, 3] + - [1, 4] + - [2, 3] + - [2, 4] + - [3, 4] + - [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] + out: 1 + - name: "thirty_two_connected_ladder" + in: + n: 32 + connections: + - [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] + - [0, 16] + - [4, 20] + - [8, 24] + - [12, 28] + out: 0 + - name: "thirty_disconnected_insufficient" + in: + n: 30 + connections: + - [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] + - [0, 2] + - [4, 6] + - [8, 10] + - [12, 14] + - [16, 18] + - [20, 22] + - [24, 26] + - [0, 4] + - [8, 12] + - [16, 20] + - [24, 28] + out: -1 diff --git a/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.cpp b/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.cpp new file mode 100644 index 00000000..4a0c6450 --- /dev/null +++ b/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.cpp @@ -0,0 +1,54 @@ +class Solution { +public: + int makeConnected(int n, vector>& connections) { + if (connections.size() < n - 1) { + return -1; + } + + vector parent(n); + vector size(n, 1); + for (int i = 0; i < n; i++) { + parent[i] = i; + } + + function find = [&](int node) { + if (parent[node] != node) { + parent[node] = find(parent[node]); + } + return parent[node]; + }; + + auto unionSets = [&](int u, int v) { + int pu = find(u); + int pv = find(v); + if (pu == pv) return; + if (size[pu] < size[pv]) { + parent[pu] = pv; + size[pv] += size[pu]; + } else { + parent[pv] = pu; + size[pu] += size[pv]; + } + }; + + int extra = 0; + for (auto& conn : connections) { + int u = conn[0]; + int v = conn[1]; + if (find(u) == find(v)) { + extra++; + } else { + unionSets(u, v); + } + } + + int components = 0; + for (int i = 0; i < n; i++) { + if (find(i) == i) { + components++; + } + } + + return extra >= components - 1 ? components - 1 : -1; + } +}; diff --git a/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.cs b/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.cs new file mode 100644 index 00000000..21621027 --- /dev/null +++ b/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.cs @@ -0,0 +1,54 @@ +public class Solution { + public int MakeConnected(int n, int[][] connections) { + if (connections.Length < n - 1) { + return -1; + } + + int[] parent = new int[n]; + int[] size = new int[n]; + for (int i = 0; i < n; i++) { + parent[i] = i; + size[i] = 1; + } + + int Find(int node) { + if (parent[node] != node) { + parent[node] = Find(parent[node]); + } + return parent[node]; + } + + void Union(int u, int v) { + int pu = Find(u); + int pv = Find(v); + if (pu == pv) return; + if (size[pu] < size[pv]) { + parent[pu] = pv; + size[pv] += size[pu]; + } else { + parent[pv] = pu; + size[pu] += size[pv]; + } + } + + int extra = 0; + foreach (var conn in connections) { + int u = conn[0]; + int v = conn[1]; + if (Find(u) == Find(v)) { + extra++; + } else { + Union(u, v); + } + } + + int components = 0; + for (int i = 0; i < n; i++) { + if (Find(i) == i) { + components++; + } + } + + return extra >= components - 1 ? components - 1 : -1; + } +} diff --git a/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.dart b/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.dart new file mode 100644 index 00000000..7b40b48c --- /dev/null +++ b/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.dart @@ -0,0 +1,50 @@ +class Solution { + int makeConnected(int n, List> connections) { + if (connections.length < n - 1) { + return -1; + } + + List parent = List.generate(n, (i) => i); + List size = List.filled(n, 1); + + int find(int node) { + if (parent[node] != node) { + parent[node] = find(parent[node]); + } + return parent[node]; + } + + void union(int u, int v) { + int pu = find(u); + int pv = find(v); + if (pu == pv) return; + if (size[pu] < size[pv]) { + parent[pu] = pv; + size[pv] += size[pu]; + } else { + parent[pv] = pu; + size[pu] += size[pv]; + } + } + + int extra = 0; + for (var conn in connections) { + int u = conn[0]; + int v = conn[1]; + if (find(u) == find(v)) { + extra++; + } else { + union(u, v); + } + } + + int components = 0; + for (int i = 0; i < n; i++) { + if (find(i) == i) { + components++; + } + } + + return extra >= components - 1 ? components - 1 : -1; + } +} diff --git a/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.go b/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.go new file mode 100644 index 00000000..5f5ed1f7 --- /dev/null +++ b/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.go @@ -0,0 +1,57 @@ +func makeConnected(n int, connections [][]int) int { + if len(connections) < n-1 { + return -1 + } + + parent := make([]int, n) + size := make([]int, n) + for i := 0; i < n; i++ { + parent[i] = i + size[i] = 1 + } + + var find func(int) int + find = func(node int) int { + if parent[node] != node { + parent[node] = find(parent[node]) + } + return parent[node] + } + + union := func(u, v int) { + pu := find(u) + pv := find(v) + if pu == pv { + return + } + if size[pu] < size[pv] { + parent[pu] = pv + size[pv] += size[pu] + } else { + parent[pv] = pu + size[pu] += size[pv] + } + } + + extra := 0 + for _, conn := range connections { + u, v := conn[0], conn[1] + if find(u) == find(v) { + extra++ + } else { + union(u, v) + } + } + + components := 0 + for i := 0; i < n; i++ { + if find(i) == i { + components++ + } + } + + if extra >= components-1 { + return components - 1 + } + return -1 +} diff --git a/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.java b/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.java new file mode 100644 index 00000000..e5a36814 --- /dev/null +++ b/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.java @@ -0,0 +1,54 @@ +class Solution { + public int makeConnected(int n, int[][] connections) { + if (connections.length < n - 1) { + return -1; + } + + int[] parent = new int[n]; + int[] size = new int[n]; + for (int i = 0; i < n; i++) { + parent[i] = i; + size[i] = 1; + } + + int extra = 0; + for (int[] conn : connections) { + int u = conn[0]; + int v = conn[1]; + if (find(parent, u) == find(parent, v)) { + extra++; + } else { + union(parent, size, u, v); + } + } + + int components = 0; + for (int i = 0; i < n; i++) { + if (find(parent, i) == i) { + components++; + } + } + + return extra >= components - 1 ? components - 1 : -1; + } + + private int find(int[] parent, int node) { + if (parent[node] != node) { + parent[node] = find(parent, parent[node]); + } + return parent[node]; + } + + private void union(int[] parent, int[] size, int u, int v) { + int pu = find(parent, u); + int pv = find(parent, v); + if (pu == pv) return; + if (size[pu] < size[pv]) { + parent[pu] = pv; + size[pv] += size[pu]; + } else { + parent[pv] = pu; + size[pu] += size[pv]; + } + } +} diff --git a/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.kt b/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.kt new file mode 100644 index 00000000..8be36482 --- /dev/null +++ b/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.kt @@ -0,0 +1,40 @@ +class Solution { + fun makeConnected(n: Int, connections: Array): Int { + if (connections.size < n - 1) return -1 + + val parent = IntArray(n) { it } + val size = IntArray(n) { 1 } + + fun find(node: Int): Int { + if (parent[node] != node) { + parent[node] = find(parent[node]) + } + return parent[node] + } + + fun union(u: Int, v: Int) { + val pu = find(u) + val pv = find(v) + if (pu == pv) return + if (size[pu] < size[pv]) { + parent[pu] = pv + size[pv] += size[pu] + } else { + parent[pv] = pu + size[pu] += size[pv] + } + } + + var extra = 0 + for ((u, v) in connections) { + if (find(u) == find(v)) { + extra++ + } else { + union(u, v) + } + } + + val components = (0 until n).count { find(it) == it } + return if (extra >= components - 1) components - 1 else -1 + } +} diff --git a/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.py b/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.py new file mode 100644 index 00000000..54801118 --- /dev/null +++ b/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.py @@ -0,0 +1,43 @@ +class DSU: + def __init__(self, n): + self.parent = list(range(n)) + self.size = [1] * n + + def find(self, node): + if self.parent[node] != node: + self.parent[node] = self.find(self.parent[node]) + return self.parent[node] + + def union(self, u, v): + pu = self.find(u) + pv = self.find(v) + + if pu == pv: + return + + if self.size[pu] < self.size[pv]: + self.parent[pu] = pv + self.size[pv] += self.size[pu] + else: + self.parent[pv] = pu + self.size[pu] += self.size[pv] + + +class Solution: + def makeConnected(self, n: int, connections: List[List[int]]) -> int: + + if len(connections) < n - 1: + return -1 + + ds = DSU(n) + extra = 0 + + for u, v in connections: + if ds.find(u) == ds.find(v): + extra += 1 + else: + ds.union(u, v) + + components = sum(1 for i in range(n) if ds.find(i) == i) + + return components - 1 if extra >= components - 1 else -1 diff --git a/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.py2 b/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.py2 new file mode 100644 index 00000000..0e2dc817 --- /dev/null +++ b/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.py2 @@ -0,0 +1,39 @@ +class Solution(object): + def makeConnected(self, n, connections): + """ + :type n: int + :type connections: List[List[int]] + :rtype: int + """ + if len(connections) < n - 1: + return -1 + + parent = list(range(n)) + size = [1] * n + + def find(node): + if parent[node] != node: + parent[node] = find(parent[node]) + return parent[node] + + def union(u, v): + pu = find(u) + pv = find(v) + if pu == pv: + return + if size[pu] < size[pv]: + parent[pu] = pv + size[pv] += size[pu] + else: + parent[pv] = pu + size[pu] += size[pv] + + extra = 0 + for u, v in connections: + if find(u) == find(v): + extra += 1 + else: + union(u, v) + + components = sum(1 for i in range(n) if find(i) == i) + return components - 1 if extra >= components - 1 else -1 diff --git a/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.rb b/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.rb new file mode 100644 index 00000000..a51cdf3d --- /dev/null +++ b/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.rb @@ -0,0 +1,41 @@ +# @param {Integer} n +# @param {Integer[][]} connections +# @return {Integer} +def make_connected(n, connections) + return -1 if connections.length < n - 1 + + parent = (0...n).to_a + size = Array.new(n, 1) + + find = ->(node) { + if parent[node] != node + parent[node] = find.call(parent[node]) + end + parent[node] + } + + union = ->(u, v) { + pu = find.call(u) + pv = find.call(v) + return if pu == pv + if size[pu] < size[pv] + parent[pu] = pv + size[pv] += size[pu] + else + parent[pv] = pu + size[pu] += size[pv] + end + } + + extra = 0 + connections.each do |u, v| + if find.call(u) == find.call(v) + extra += 1 + else + union.call(u, v) + end + end + + components = (0...n).count { |i| find.call(i) == i } + extra >= components - 1 ? components - 1 : -1 +end diff --git a/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.rs b/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.rs new file mode 100644 index 00000000..24383bb0 --- /dev/null +++ b/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.rs @@ -0,0 +1,52 @@ +impl Solution { + pub fn make_connected(n: i32, connections: Vec>) -> i32 { + let n = n as usize; + if connections.len() < n - 1 { + return -1; + } + + let mut parent: Vec = (0..n).collect(); + let mut size: Vec = vec![1; n]; + + fn find(parent: &mut Vec, node: usize) -> usize { + if parent[node] != node { + parent[node] = find(parent, parent[node]); + } + parent[node] + } + + fn union(parent: &mut Vec, size: &mut Vec, u: usize, v: usize) { + let pu = find(parent, u); + let pv = find(parent, v); + if pu == pv { + return; + } + if size[pu] < size[pv] { + parent[pu] = pv; + size[pv] += size[pu]; + } else { + parent[pv] = pu; + size[pu] += size[pv]; + } + } + + let mut extra = 0; + for conn in &connections { + let u = conn[0] as usize; + let v = conn[1] as usize; + if find(&mut parent, u) == find(&mut parent, v) { + extra += 1; + } else { + union(&mut parent, &mut size, u, v); + } + } + + let components = (0..n).filter(|&i| find(&mut parent, i) == i).count() as i32; + + if extra >= components - 1 { + components - 1 + } else { + -1 + } + } +} diff --git a/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.swift b/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.swift new file mode 100644 index 00000000..5e434445 --- /dev/null +++ b/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.swift @@ -0,0 +1,50 @@ +class Solution { + func makeConnected(_ n: Int, _ connections: [[Int]]) -> Int { + if connections.count < n - 1 { + return -1 + } + + var parent = Array(0.. Int { + if parent[node] != node { + parent[node] = find(parent[node]) + } + return parent[node] + } + + func union(_ u: Int, _ v: Int) { + let pu = find(u) + let pv = find(v) + if pu == pv { return } + if size[pu] < size[pv] { + parent[pu] = pv + size[pv] += size[pu] + } else { + parent[pv] = pu + size[pu] += size[pv] + } + } + + var extra = 0 + for conn in connections { + let u = conn[0] + let v = conn[1] + if find(u) == find(v) { + extra += 1 + } else { + union(u, v) + } + } + + var components = 0 + for i in 0..= components - 1 ? components - 1 : -1 + } +} diff --git a/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.ts b/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.ts new file mode 100644 index 00000000..1dfa70e6 --- /dev/null +++ b/tests/1001-1500/1319. number-of-operations-to-make-network-connected/sol.ts @@ -0,0 +1,46 @@ +function makeConnected(n: number, connections: number[][]): number { + if (connections.length < n - 1) { + return -1; + } + + const parent: number[] = Array.from({ length: n }, (_, i) => i); + const size: number[] = Array(n).fill(1); + + const find = (node: number): number => { + if (parent[node] !== node) { + parent[node] = find(parent[node]); + } + return parent[node]; + }; + + const union = (u: number, v: number): void => { + const pu = find(u); + const pv = find(v); + if (pu === pv) return; + if (size[pu] < size[pv]) { + parent[pu] = pv; + size[pv] += size[pu]; + } else { + parent[pv] = pu; + size[pu] += size[pv]; + } + }; + + let extra = 0; + for (const [u, v] of connections) { + if (find(u) === find(v)) { + extra++; + } else { + union(u, v); + } + } + + let components = 0; + for (let i = 0; i < n; i++) { + if (find(i) === i) { + components++; + } + } + + return extra >= components - 1 ? components - 1 : -1; +} diff --git a/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/manifest.yaml b/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/manifest.yaml new file mode 100644 index 00000000..7cbc37af --- /dev/null +++ b/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/manifest.yaml @@ -0,0 +1,192 @@ +entry: + id: 1320 + title: "minimum-distance-to-type-a-word-using-two-fingers" + params: + word: + type: string + call: + cpp: "Solution().minimumDistance({word})" + rust: "Solution::minimum_distance({word})" + python3: "Solution().minimumDistance({word})" + python2: "Solution().minimumDistance({word})" + ruby: "minimum_distance({word})" + java: "new Solution().minimumDistance({word})" + csharp: "new Solution().MinimumDistance({word})" + kotlin: "Solution().minimumDistance({word})" + go: "minimumDistance({word})" + dart: "Solution().minimumDistance({word})" + swift: "Solution().minimumDistance({word})" + typescript: "minimumDistance({word})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 300 + +oracle: + python3: + call: "Checker().minimumDistance(word, {result})" + checker: | + class Checker: + def minimumDistance(self, word, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + def distance(a, b): + return abs(a // 6 - b // 6) + abs(a % 6 - b % 6) + states = [0] * 26 + for previous, current in zip(word, word[1:]): + previous = ord(previous) - ord('A') + current = ord(current) - ord('A') + updated = [cost + distance(previous, current) for cost in states] + updated[previous] = min( + updated[previous], + min(cost + distance(other, current) for other, cost in enumerate(states)), + ) + states = updated + return result == min(states) + +seed: 132000 + +tests: + - name: "example_cake" + in: + word: "CAKE" + - name: "example_happy" + in: + word: "HAPPY" + - name: "two_adjacent" + in: + word: "AB" + - name: "two_far" + in: + word: "AZ" + - name: "repeated_letter" + in: + word: "AA" + - name: "same_word" + in: + word: "AAAAAA" + - name: "top_row" + in: + word: "ABCDEF" + - name: "row_boundary" + in: + word: "FG" + - name: "bottom_row" + in: + word: "UVWXYZ" + - name: "vertical_transition" + in: + word: "AFKPUZ" + - name: "zigzag_rows" + in: + word: "AZBYCXD" + - name: "alternating_ends" + in: + word: "AZAZAZ" + - name: "alternating_neighbors" + in: + word: "ABABAB" + - name: "generated_large_random_296" + seed: 132001 + in: + word: + gen: "str" + len: 296 + alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + - name: "reverse_alphabet" + in: + word: "ZYXWVUT" + - name: "palindrome_word" + in: + word: "ABCCBA" + - name: "repeated_pair" + in: + word: "AABBCCDDEE" + - name: "far_then_near" + in: + word: "AZBCYD" + - name: "diagonal_pattern" + in: + word: "AGMSYE" + - name: "outer_cycle" + in: + word: "AZZAZZ" + - name: "center_cycle" + in: + word: "MNMNMN" + - name: "generated_large_random_297" + seed: 132002 + in: + word: + gen: "str" + len: 297 + alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + - name: "keyboard_sequence" + in: + word: "QWERTYUIOP" + - name: "home_sequence" + in: + word: "ASDFGHJKL" + - name: "bottom_sequence" + in: + word: "ZXCVBNM" + - name: "row_reversal" + in: + word: "FEDCBA" + - name: "alternating_rows" + in: + word: "AFBJCKDL" + - name: "long_repetition" + in: + word: "ABCABCABCABC" + - name: "long_alternating" + in: + word: "AZBYCXDW" + - name: "all_rows_mixed" + in: + word: "AFKPUZQG" + - name: "wide_jumps" + in: + word: "AMYFLSZ" + - name: "near_full_alphabet" + in: + word: "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + - name: "reverse_full_alphabet" + in: + word: "ZYXWVUTSRQPONMLKJIHGFEDCBA" + - name: "generated_large_random_298" + seed: 132003 + in: + word: + gen: "str" + len: 298 + alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + - name: "generated_large_random_299" + seed: 132004 + in: + word: + gen: "str" + len: 299 + alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + - name: "generated_large_random_300" + seed: 132005 + in: + word: + gen: "str" + len: 300 + alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + - name: "alphabet_cycles_100" + in: + word: "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ" + - name: "reverse_cycles_104" + in: + word: "ZYXWVUTSRQPONMLKJIHGFEDCBAZYXWVUTSRQPONMLKJIHGFEDCBAZYXWVUTSRQPONMLKJIHGFEDCBAZYXWVUTSRQPONMLKJIHGFEDCBA" + - name: "maximum_alphabet_cycles" + in: + word: "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMN" + - name: "maximum_reverse_cycles" + in: + word: "ZYXWVUTSRQPONMLKJIHGFEDCBAZYXWVUTSRQPONMLKJIHGFEDCBAZYXWVUTSRQPONMLKJIHGFEDCBAZYXWVUTSRQPONMLKJIHGFEDCBAZYXWVUTSRQPONMLKJIHGFEDCBAZYXWVUTSRQPONMLKJIHGFEDCBAZYXWVUTSRQPONMLKJIHGFEDCBAZYXWVUTSRQPONMLKJIHGFEDCBAZYXWVUTSRQPONMLKJIHGFEDCBAZYXWVUTSRQPONMLKJIHGFEDCBAZYXWVUTSRQPONMLKJIHGFEDCBAZYXWVUTSRQPONM" diff --git a/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.cpp b/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.cpp new file mode 100644 index 00000000..473b722d --- /dev/null +++ b/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.cpp @@ -0,0 +1,30 @@ +class Solution { +private: + int cal(int a, int b) { + return abs(a / 6 - b / 6) + abs(a % 6 - b % 6); + } + +public: + int minimumDistance(string word) { + int n = word.length(); + vector dp(26, 0); + vector ndp(26, 0); + + for (int i = 1; i < n; i++) { + int p = word[i - 1] - 'A'; + int t = word[i] - 'A'; + + for (int j = 0; j < 26; j++) { + ndp[j] = dp[j] + cal(p, t); + } + + for (int j = 0; j < 26; j++) { + ndp[p] = min(ndp[p], dp[j] + cal(j, t)); + } + + swap(dp, ndp); + } + + return *min_element(dp.begin(), dp.end()); + } +}; diff --git a/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.cs b/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.cs new file mode 100644 index 00000000..d758b961 --- /dev/null +++ b/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.cs @@ -0,0 +1,32 @@ +public class Solution { + private int Cal(int a, int b) { + return Math.Abs(a / 6 - b / 6) + Math.Abs(a % 6 - b % 6); + } + + public int MinimumDistance(string word) { + int n = word.Length; + int[] dp = new int[26]; + int[] ndp = new int[26]; + + for (int i = 1; i < n; i++) { + int p = word[i - 1] - 'A'; + int t = word[i] - 'A'; + + for (int j = 0; j < 26; j++) { + ndp[j] = dp[j] + Cal(p, t); + } + + for (int j = 0; j < 26; j++) { + ndp[p] = Math.Min(ndp[p], dp[j] + Cal(j, t)); + } + + (dp, ndp) = (ndp, dp); + } + + int ans = int.MaxValue; + for (int i = 0; i < 26; i++) { + if (dp[i] < ans) ans = dp[i]; + } + return ans; + } +} diff --git a/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.dart b/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.dart new file mode 100644 index 00000000..3f1d0227 --- /dev/null +++ b/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.dart @@ -0,0 +1,30 @@ +class Solution { + int _cal(int a, int b) { + return (a ~/ 6 - b ~/ 6).abs() + (a % 6 - b % 6).abs(); + } + + int minimumDistance(String word) { + int n = word.length; + List dp = List.filled(26, 0); + List ndp = List.filled(26, 0); + + for (int i = 1; i < n; i++) { + int p = word.codeUnitAt(i - 1) - 'A'.codeUnitAt(0); + int t = word.codeUnitAt(i) - 'A'.codeUnitAt(0); + + for (int j = 0; j < 26; j++) { + ndp[j] = dp[j] + _cal(p, t); + } + + for (int j = 0; j < 26; j++) { + ndp[p] = [ndp[p], dp[j] + _cal(j, t)].reduce((a, b) => a < b ? a : b); + } + + var temp = dp; + dp = ndp; + ndp = temp; + } + + return dp.reduce((a, b) => a < b ? a : b); + } +} diff --git a/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.go b/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.go new file mode 100644 index 00000000..8e8aaab5 --- /dev/null +++ b/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.go @@ -0,0 +1,39 @@ +func minimumDistance(word string) int { + cal := func(a, b int) int { + return abs(a/6-b/6) + abs(a%6-b%6) + } + + n := len(word) + dp := make([]int, 26) + ndp := make([]int, 26) + + for i := 1; i < n; i++ { + p := int(word[i-1] - 'A') + t := int(word[i] - 'A') + + for j := 0; j < 26; j++ { + ndp[j] = dp[j] + cal(p, t) + } + + for j := 0; j < 26; j++ { + ndp[p] = min(ndp[p], dp[j]+cal(j, t)) + } + + dp, ndp = ndp, dp + } + + ans := dp[0] + for _, v := range dp { + if v < ans { + ans = v + } + } + return ans +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} diff --git a/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.java b/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.java new file mode 100644 index 00000000..745fd21e --- /dev/null +++ b/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.java @@ -0,0 +1,32 @@ +class Solution { + private int cal(int a, int b) { + return Math.abs(a / 6 - b / 6) + Math.abs(a % 6 - b % 6); + } + + public int minimumDistance(String word) { + int n = word.length(); + int[] dp = new int[26]; + int[] ndp = new int[26]; + + for (int i = 1; i < n; i++) { + int p = word.charAt(i - 1) - 'A'; + int t = word.charAt(i) - 'A'; + + for (int j = 0; j < 26; j++) { + ndp[j] = dp[j] + cal(p, t); + } + + for (int j = 0; j < 26; j++) { + ndp[p] = Math.min(ndp[p], dp[j] + cal(j, t)); + } + + int[] temp = dp; + dp = ndp; + ndp = temp; + } + + int ans = Integer.MAX_VALUE; + for (int v : dp) ans = Math.min(ans, v); + return ans; + } +} diff --git a/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.kt b/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.kt new file mode 100644 index 00000000..b2164cdf --- /dev/null +++ b/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.kt @@ -0,0 +1,30 @@ +class Solution { + private fun cal(a: Int, b: Int): Int { + return Math.abs(a / 6 - b / 6) + Math.abs(a % 6 - b % 6) + } + + fun minimumDistance(word: String): Int { + val n = word.length + var dp = IntArray(26) { 0 } + var ndp = IntArray(26) { 0 } + + for (i in 1 until n) { + val p = word[i - 1] - 'A' + val t = word[i] - 'A' + + for (j in 0 until 26) { + ndp[j] = dp[j] + cal(p, t) + } + + for (j in 0 until 26) { + ndp[p] = minOf(ndp[p], dp[j] + cal(j, t)) + } + + val temp = dp + dp = ndp + ndp = temp + } + + return dp.min() + } +} diff --git a/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.py b/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.py new file mode 100644 index 00000000..d58c7858 --- /dev/null +++ b/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.py @@ -0,0 +1,22 @@ +class Solution(object): + def cal(self, a, b): + return abs(a // 6 - b // 6) + abs(a % 6 - b % 6) + + def minimumDistance(self, word): + n = len(word) + dp = [0] * 26 + ndp = [0] * 26 + + for i in range(1, n): + p = ord(word[i - 1]) - ord("A") + t = ord(word[i]) - ord("A") + + for j in range(26): + ndp[j] = dp[j] + self.cal(p, t) + + for j in range(26): + ndp[p] = min(ndp[p], dp[j] + self.cal(j, t)) + + dp, ndp = ndp, dp + + return min(dp) diff --git a/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.py2 b/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.py2 new file mode 100644 index 00000000..57fd2dfa --- /dev/null +++ b/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.py2 @@ -0,0 +1,22 @@ +class Solution(object): + def cal(self, a, b): + return abs(a // 6 - b // 6) + abs(a % 6 - b % 6) + + def minimumDistance(self, word): + n = len(word) + dp = [0] * 26 + ndp = [0] * 26 + + for i in range(1, n): + p = ord(word[i - 1]) - ord('A') + t = ord(word[i]) - ord('A') + + for j in range(26): + ndp[j] = dp[j] + self.cal(p, t) + + for j in range(26): + ndp[p] = min(ndp[p], dp[j] + self.cal(j, t)) + + dp, ndp = ndp, dp + + return min(dp) diff --git a/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.rb b/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.rb new file mode 100644 index 00000000..1e1b122f --- /dev/null +++ b/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.rb @@ -0,0 +1,22 @@ +# @param {String} word +# @return {Integer} +def minimum_distance(word) + n = word.length + dp = Array.new(26, 0) + ndp = Array.new(26, 0) + + (1...n).each do |i| + p = word[i - 1].ord - 'A'.ord + t = word[i].ord - 'A'.ord + + (0...26).each { |j| ndp[j] = dp[j] + (p / 6 - t / 6).abs + ((p % 6) - (t % 6)).abs } + + (0...26).each do |j| + ndp[p] = [ndp[p], dp[j] + (j / 6 - t / 6).abs + ((j % 6) - (t % 6)).abs].min + end + + dp, ndp = ndp, dp + end + + dp.min +end diff --git a/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.rs b/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.rs new file mode 100644 index 00000000..7d6f0380 --- /dev/null +++ b/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.rs @@ -0,0 +1,29 @@ +impl Solution { + fn cal(a: i32, b: i32) -> i32 { + (a / 6 - b / 6).abs() + (a % 6 - b % 6).abs() + } + + pub fn minimum_distance(word: String) -> i32 { + let n = word.len(); + let word = word.as_bytes(); + let mut dp = vec![0; 26]; + let mut ndp = vec![0; 26]; + + for i in 1..n { + let p = (word[i - 1] - b'A') as i32; + let t = (word[i] - b'A') as i32; + + for j in 0..26 { + ndp[j] = dp[j] + Self::cal(p, t); + } + + for j in 0..26 { + ndp[p as usize] = ndp[p as usize].min(dp[j] + Self::cal(j as i32, t)); + } + + std::mem::swap(&mut dp, &mut ndp); + } + + *dp.iter().min().unwrap() + } +} diff --git a/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.swift b/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.swift new file mode 100644 index 00000000..35fd1e6d --- /dev/null +++ b/tests/1001-1500/1320. minimum-distance-to-type-a-word-using-two-fingers/sol.swift @@ -0,0 +1,29 @@ +class Solution { + private func cal(_ a: Int, _ b: Int) -> Int { + return abs(a / 6 - b / 6) + abs(a % 6 - b % 6) + } + + func minimumDistance(_ word: String) -> Int { + let n = word.count + let chars = Array(word) + var dp = [Int](repeating: 0, count: 26) + var ndp = [Int](repeating: 0, count: 26) + + for i in 1.. { + return ( + Math.abs(Math.floor(a / 6) - Math.floor(b / 6)) + + Math.abs((a % 6) - (b % 6)) + ); + }; + + const n = word.length; + let dp: number[] = new Array(26).fill(0); + let ndp: number[] = new Array(26).fill(0); + + for (let i = 1; i < n; i++) { + const p = word.charCodeAt(i - 1) - 65; + const t = word.charCodeAt(i) - 65; + + for (let j = 0; j < 26; j++) { + ndp[j] = dp[j] + cal(p, t); + } + + for (let j = 0; j < 26; j++) { + ndp[p] = Math.min(ndp[p], dp[j] + cal(j, t)); + } + + [dp, ndp] = [ndp, dp]; + } + + return Math.min(...dp); +} diff --git a/tests/1001-1500/1323. maximum-69-number/manifest.yaml b/tests/1001-1500/1323. maximum-69-number/manifest.yaml new file mode 100644 index 00000000..8453ba3d --- /dev/null +++ b/tests/1001-1500/1323. maximum-69-number/manifest.yaml @@ -0,0 +1,199 @@ +entry: + id: 1323 + title: maximum-69-number + params: + num: + type: int + call: + cpp: "Solution().maximum69Number({num})" + rust: "Solution::maximum69_number({num})" + python3: "Solution().maximum69Number({num})" + python2: "Solution().maximum69Number({num})" + ruby: "maximum69_number({num})" + java: "new Solution().maximum69Number({num})" + csharp: "new Solution().Maximum69Number({num})" + kotlin: "Solution().maximum69Number({num})" + go: "maximum69Number({num})" + dart: "Solution().maximum69Number({num})" + swift: "Solution().maximum69Number({num})" + typescript: "maximum69Number({num})" +judge: + type: "exact" +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().maximum69Number(num, {result})" + checker: | + class Checker: + def maximum69Number(self, num, result): + digits = str(num) + first_six = digits.find("6") + if first_six >= 0: + expected = int(digits[:first_six] + "9" + digits[first_six + 1:]) + else: + expected = num + return type(result) is int and result == expected +seed: 1323 +tests: + - name: example-first-six + in: + num: 9669 + out: 9969 + - name: example-final-six + in: + num: 9996 + out: 9999 + - name: example-all-nines + in: + num: 9999 + out: 9999 + - name: smallest-six + in: + num: 6 + out: 9 + - name: smallest-nine + in: + num: 9 + out: 9 + - name: two-digit-all-sixes + in: + num: 66 + out: 96 + - name: two-digit-leading-six + in: + num: 69 + out: 99 + - name: two-digit-trailing-six + in: + num: 96 + out: 99 + - name: two-digit-all-nines + in: + num: 99 + out: 99 + - name: three-digit-all-sixes + in: + num: 666 + out: 966 + - name: three-digit-leading-six + in: + num: 669 + out: 969 + - name: three-digit-middle-six + in: + num: 696 + out: 996 + - name: three-digit-final-six + in: + num: 699 + out: 999 + - name: three-digit-leading-after-nine + in: + num: 966 + out: 996 + - name: three-digit-final-after-nine + in: + num: 969 + out: 999 + - name: three-digit-two-leading-nines + in: + num: 996 + out: 999 + - name: three-digit-all-nines + in: + num: 999 + out: 999 + - name: four-digit-all-sixes + in: + num: 6666 + out: 9666 + - name: four-digit-first-of-three-sixes + in: + num: 6669 + out: 9669 + - name: four-digit-first-of-two-sixes + in: + num: 6696 + out: 9696 + - name: four-digit-first-six-before-nine + in: + num: 6699 + out: 9699 + - name: four-digit-second-position-six + in: + num: 6966 + out: 9966 + - name: four-digit-second-position-six-before-nine + in: + num: 6969 + out: 9969 + - name: four-digit-second-position-after-nine + in: + num: 6996 + out: 9996 + - name: four-digit-first-six-after-nine + in: + num: 9666 + out: 9966 + - name: four-digit-first-six-after-nine-with-final-nine + in: + num: 9669 + out: 9969 + - name: four-digit-third-position-six + in: + num: 9696 + out: 9996 + - name: four-digit-third-position-six-before-nine + in: + num: 9699 + out: 9999 + - name: four-digit-final-six-after-two-nines + in: + num: 9966 + out: 9996 + - name: four-digit-final-six + in: + num: 9969 + out: 9999 + - name: four-digit-all-nines + in: + num: 9999 + out: 9999 + - name: regression-single-six + in: + num: 6 + out: 9 + - name: regression-leading-six + in: + num: 6999 + out: 9999 + - name: regression-interior-six + in: + num: 9699 + out: 9999 + - name: regression-last-six + in: + num: 9996 + out: 9999 + - name: regression-choose-leftmost-six + in: + num: 6696 + out: 9696 + - name: regression-skip-change + in: + num: 99 + out: 99 + - name: regression-minimum-four-digit + in: + num: 6666 + out: 9666 + - name: regression-maximum-four-digit + in: + num: 9999 + out: 9999 + - name: regression-two-leading-nines + in: + num: 9969 + out: 9999 diff --git a/tests/1001-1500/1323. maximum-69-number/sol.cpp b/tests/1001-1500/1323. maximum-69-number/sol.cpp new file mode 100644 index 00000000..43fe4ac7 --- /dev/null +++ b/tests/1001-1500/1323. maximum-69-number/sol.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + int maximum69Number (int num) { + string s = std::to_string(num); + size_t pos = s.find('6'); + if (pos != string::npos) { + s[pos] = '9'; + } + return stoi(s); + } +}; diff --git a/tests/1001-1500/1323. maximum-69-number/sol.cs b/tests/1001-1500/1323. maximum-69-number/sol.cs new file mode 100644 index 00000000..15754013 --- /dev/null +++ b/tests/1001-1500/1323. maximum-69-number/sol.cs @@ -0,0 +1,12 @@ +public class Solution { + public int Maximum69Number (int num) { + string s = num.ToString(); + int idx = s.IndexOf('6'); + if (idx != -1) { + char[] arr = s.ToCharArray(); + arr[idx] = '9'; + s = new string(arr); + } + return int.Parse(s); + } +} diff --git a/tests/1001-1500/1323. maximum-69-number/sol.dart b/tests/1001-1500/1323. maximum-69-number/sol.dart new file mode 100644 index 00000000..f2cb8ca1 --- /dev/null +++ b/tests/1001-1500/1323. maximum-69-number/sol.dart @@ -0,0 +1,7 @@ +class Solution { + int maximum69Number (int num) { + String s = num.toString(); + s = s.replaceFirst('6', '9'); + return int.parse(s); + } +} diff --git a/tests/1001-1500/1323. maximum-69-number/sol.go b/tests/1001-1500/1323. maximum-69-number/sol.go new file mode 100644 index 00000000..5ecdedef --- /dev/null +++ b/tests/1001-1500/1323. maximum-69-number/sol.go @@ -0,0 +1,6 @@ +func maximum69Number (num int) int { + s := strconv.Itoa(num) + s = strings.Replace(s, "6", "9", 1) + res, _ := strconv.Atoi(s) + return res +} diff --git a/tests/1001-1500/1323. maximum-69-number/sol.java b/tests/1001-1500/1323. maximum-69-number/sol.java new file mode 100644 index 00000000..9fb24933 --- /dev/null +++ b/tests/1001-1500/1323. maximum-69-number/sol.java @@ -0,0 +1,7 @@ +class Solution { + public int maximum69Number (int num) { + String s = Integer.toString(num); + s = s.replaceFirst("6", "9"); + return Integer.parseInt(s); + } +} diff --git a/tests/1001-1500/1323. maximum-69-number/sol.kt b/tests/1001-1500/1323. maximum-69-number/sol.kt new file mode 100644 index 00000000..866688d2 --- /dev/null +++ b/tests/1001-1500/1323. maximum-69-number/sol.kt @@ -0,0 +1,5 @@ +class Solution { + fun maximum69Number (num: Int): Int { + return num.toString().replaceFirst("6", "9").toInt() + } +} diff --git a/tests/1001-1500/1323. maximum-69-number/sol.py b/tests/1001-1500/1323. maximum-69-number/sol.py new file mode 100644 index 00000000..1db63183 --- /dev/null +++ b/tests/1001-1500/1323. maximum-69-number/sol.py @@ -0,0 +1,4 @@ +# Python +class Solution: + def maximum69Number(self, num: int) -> int: + return int(str(num).replace("6", "9", 1)) diff --git a/tests/1001-1500/1323. maximum-69-number/sol.py2 b/tests/1001-1500/1323. maximum-69-number/sol.py2 new file mode 100644 index 00000000..59d184a7 --- /dev/null +++ b/tests/1001-1500/1323. maximum-69-number/sol.py2 @@ -0,0 +1,7 @@ +class Solution(object): + def maximum69Number (self, num): + """ + :type num: int + :rtype: int + """ + return int(str(num).replace('6', '9', 1)) diff --git a/tests/1001-1500/1323. maximum-69-number/sol.rb b/tests/1001-1500/1323. maximum-69-number/sol.rb new file mode 100644 index 00000000..5d8e8f2c --- /dev/null +++ b/tests/1001-1500/1323. maximum-69-number/sol.rb @@ -0,0 +1,5 @@ +# @param {Integer} num +# @return {Integer} +def maximum69_number (num) + num.to_s.sub('6', '9').to_i +end diff --git a/tests/1001-1500/1323. maximum-69-number/sol.rs b/tests/1001-1500/1323. maximum-69-number/sol.rs new file mode 100644 index 00000000..3fb11602 --- /dev/null +++ b/tests/1001-1500/1323. maximum-69-number/sol.rs @@ -0,0 +1,5 @@ +impl Solution { + pub fn maximum69_number (num: i32) -> i32 { + num.to_string().replacen("6", "9", 1).parse().unwrap() + } +} diff --git a/tests/1001-1500/1323. maximum-69-number/sol.swift b/tests/1001-1500/1323. maximum-69-number/sol.swift new file mode 100644 index 00000000..c596f804 --- /dev/null +++ b/tests/1001-1500/1323. maximum-69-number/sol.swift @@ -0,0 +1,9 @@ +class Solution { + func maximum69Number (_ num: Int) -> Int { + var s = String(num) + if let range = s.range(of: "6") { + s.replaceSubrange(range, with: "9") + } + return Int(s)! + } +} diff --git a/tests/1001-1500/1323. maximum-69-number/sol.ts b/tests/1001-1500/1323. maximum-69-number/sol.ts new file mode 100644 index 00000000..9dfc992a --- /dev/null +++ b/tests/1001-1500/1323. maximum-69-number/sol.ts @@ -0,0 +1,3 @@ +function maximum69Number(num: number): number { + return parseInt(num.toString().replace("6", "9")); +} diff --git a/tests/1001-1500/1324. print-words-vertically/manifest.yaml b/tests/1001-1500/1324. print-words-vertically/manifest.yaml new file mode 100644 index 00000000..3fc05299 --- /dev/null +++ b/tests/1001-1500/1324. print-words-vertically/manifest.yaml @@ -0,0 +1,206 @@ +entry: + id: 1324 + title: "print-words-vertically" + params: + s: + type: string + call: + cpp: "Solution().printVertically({s})" + rust: "Solution::print_vertically({s})" + python3: "Solution().printVertically({s})" + python2: "Solution().printVertically({s})" + ruby: "print_vertically({s})" + java: "new Solution().printVertically({s})" + csharp: "new Solution().PrintVertically({s})" + kotlin: "Solution().printVertically({s})" + go: "printVertically({s})" + dart: "Solution().printVertically({s})" + swift: "Solution().printVertically({s})" + typescript: "printVertically({s})" + +judge: + type: "exact" + +limits: + time_ms: 500 + memory_mb: 300 + +oracle: + python3: + call: "Checker().printVertically(s, {result})" + checker: | + class Checker: + def printVertically(self, s, result): + if not isinstance(result, list) or any(not isinstance(row, str) for row in result): + return False + words = s.split(' ') + expected = [] + for column in range(max(len(word) for word in words)): + row = ''.join(word[column] if column < len(word) else ' ' for word in words) + expected.append(row.rstrip()) + return result == expected + +seed: 132400 + +tests: + - name: "example_how_are_you" + in: + s: "HOW ARE YOU" + out: ["HAY", "ORO", "WEU"] + - name: "example_to_be_or_not" + in: + s: "TO BE OR NOT TO BE" + out: ["TBONTB", "OEROOE", " T"] + - name: "example_contest_is_coming" + in: + s: "CONTEST IS COMING" + out: ["CIC", "OSO", "N M", "T I", "E N", "S G", "T"] + - name: "single_word" + in: + s: "HELLO" + out: ["H", "E", "L", "L", "O"] + - name: "single_letter" + in: + s: "A" + out: ["A"] + - name: "two_equal_words" + in: + s: "AB AB" + out: ["AA", "BB"] + - name: "uneven_two_words" + in: + s: "ABC D" + out: ["AD", "B", "C"] + - name: "long_first_word" + in: + s: "ABCDEFG HI" + out: ["AH", "BI", "C", "D", "E", "F", "G"] + - name: "long_last_word" + in: + s: "HI ABCDEFG" + out: ["HA", "IB", " C", " D", " E", " F", " G"] + - name: "three_short_words" + in: + s: "A BB CCC" + out: ["ABC", " BC", " C"] + - name: "descending_lengths" + in: + s: "ABCDE ABC AB A" + out: ["AAAA", "BBB", "CC", "D", "E"] + - name: "ascending_lengths" + in: + s: "A AB ABC ABCD" + out: ["AAAA", " BBB", " CC", " D"] + - name: "repeated_letters" + in: + s: "AAAA BBBB CCCC" + out: ["ABC", "ABC", "ABC", "ABC"] + - name: "all_one_length" + in: + s: "A B C D E" + out: ["ABCDE"] + - name: "two_long_words" + in: + s: "ABCDEFG HIJKLMN" + out: ["AH", "BI", "CJ", "DK", "EL", "FM", "GN"] + - name: "middle_short_word" + in: + s: "ABCDE F GH" + out: ["AFG", "B H", "C", "D", "E"] + - name: "four_words" + in: + s: "ONE TWO THREE FOUR" + out: ["OTTF", "NWHO", "EORU", " ER", " E"] + - name: "five_words" + in: + s: "A BB CCC DDDD EEEEE" + out: ["ABCDE", " BCDE", " CDE", " DE", " E"] + - name: "same_length_three" + in: + s: "CAT DOG PIG" + out: ["CDP", "AOI", "TGG"] + - name: "same_length_four" + in: + s: "ABCD EFGH IJKL MNOP" + out: ["AEIM", "BFJN", "CGKO", "DHLP"] + - name: "long_sentence" + in: + s: "THE QUICK BROWN FOX" + out: ["TQBF", "HURO", "EIOX", " CW", " KN"] + - name: "short_and_long" + in: + s: "X YZ ABCDE" + out: ["XYA", " ZB", " C", " D", " E"] + - name: "letters_with_spaces" + in: + s: "AA B AAAA" + out: ["ABA", "A A", " A", " A"] + - name: "six_words" + in: + s: "ONE TWO SIX TEN RED BLUE" + out: ["OTSTRB", "NWIEEL", "EOXNDU", " E"] + - name: "palindromic_words" + in: + s: "ABBA RACE CAR" + out: ["ARC", "BAA", "BCR", "AE"] + - name: "word_length_two" + in: + s: "AB CD EF GH" + out: ["ACEG", "BDFH"] + - name: "one_long_center" + in: + s: "A BCDEFGH I" + out: ["ABI", " C", " D", " E", " F", " G", " H"] + - name: "many_single_letters" + in: + s: "A B C D E F G H" + out: ["ABCDEFGH"] + - name: "mixed_word_lengths" + in: + s: "ABCD E FGHI JK" + out: ["AEFJ", "B GK", "C H", "D I"] + - name: "alphabet_chunks" + in: + s: "ABC DEFG HIJKLM" + out: ["ADH", "BEI", "CFJ", " GK", " L", " M"] + - name: "trailing_columns_trimmed" + in: + s: "AB C DE" + out: ["ACD", "B E"] + - name: "gaps_before_late_word" + in: + s: "ABCD E FGH" + out: ["AEF", "B G", "C H", "D"] + - name: "short_prefixes_before_long_word" + in: + s: "A BC D EFGHI" + out: ["ABDE", " C F", " G", " H", " I"] + - name: "four_uneven_words" + in: + s: "ABCD EFG HIJKL MN" + out: ["AEHM", "BFIN", "CGJ", "D K", " L"] + - name: "repeated_zigzag_lengths" + in: + s: "Z ZZZ ZZ ZZZZ" + out: ["ZZZZ", " ZZZ", " Z Z", " Z"] + - name: "alternating_single_and_double_words" + in: + s: "AA A AA A AA A" + out: ["AAAAAA", "A A A"] + - name: "long_first_with_short_middle" + in: + s: "ABCDEFGHIJ K LMNOP QRSTU" + out: ["AKLQ", "B MR", "C NS", "D OT", "E PU", "F", "G", "H", "I", "J"] + - name: "maximum_width_single_letters" + in: + s: "A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A" + - name: "maximum_height_generated_word" + seed: 132401 + in: + s: + gen: "str" + len: 200 + alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + - name: "maximum_length_repeated_triples" + in: + s: "ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC ABC" diff --git a/tests/1001-1500/1324. print-words-vertically/sol.cpp b/tests/1001-1500/1324. print-words-vertically/sol.cpp new file mode 100644 index 00000000..92a4d717 --- /dev/null +++ b/tests/1001-1500/1324. print-words-vertically/sol.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + vector printVertically(string s) { + vector words; + stringstream ss(s); + string word; + while (ss >> word) { + words.push_back(word); + } + int maxLen = 0; + for (const auto& w : words) { + if (w.length() > maxLen) { + maxLen = w.length(); + } + } + vector res; + for (int i = 0; i < maxLen; i++) { + string currWord; + for (const auto& w : words) { + if (i < w.length()) { + currWord += w[i]; + } else { + currWord += ' '; + } + } + while (!currWord.empty() && currWord.back() == ' ') { + currWord.pop_back(); + } + res.push_back(currWord); + } + return res; + } +}; diff --git a/tests/1001-1500/1324. print-words-vertically/sol.cs b/tests/1001-1500/1324. print-words-vertically/sol.cs new file mode 100644 index 00000000..874aa63f --- /dev/null +++ b/tests/1001-1500/1324. print-words-vertically/sol.cs @@ -0,0 +1,24 @@ +public class Solution { + public IList PrintVertically(string s) { + string[] words = s.Split(' '); + int maxLen = 0; + foreach (string word in words) { + if (word.Length > maxLen) { + maxLen = word.Length; + } + } + IList res = new List(); + for (int i = 0; i < maxLen; i++) { + string currWord = ""; + foreach (string word in words) { + if (i < word.Length) { + currWord += word[i]; + } else { + currWord += " "; + } + } + res.Add(currWord.TrimEnd(' ')); + } + return res; + } +} diff --git a/tests/1001-1500/1324. print-words-vertically/sol.dart b/tests/1001-1500/1324. print-words-vertically/sol.dart new file mode 100644 index 00000000..ce34ab12 --- /dev/null +++ b/tests/1001-1500/1324. print-words-vertically/sol.dart @@ -0,0 +1,26 @@ +class Solution { + List printVertically(String s) { + final words = s.split(' '); + var maxLen = 0; + for (final word in words) { + if (word.length > maxLen) { + maxLen = word.length; + } + } + + final result = []; + for (var col = 0; col < maxLen; col++) { + final buffer = StringBuffer(); + for (final word in words) { + if (col < word.length) { + buffer.write(word[col]); + } else { + buffer.write(' '); + } + } + result.add(buffer.toString().trimRight()); + } + + return result; + } +} diff --git a/tests/1001-1500/1324. print-words-vertically/sol.go b/tests/1001-1500/1324. print-words-vertically/sol.go new file mode 100644 index 00000000..6a3b1c7a --- /dev/null +++ b/tests/1001-1500/1324. print-words-vertically/sol.go @@ -0,0 +1,24 @@ +func printVertically(s string) []string { + words := strings.Split(s, " ") + maxLen := 0 + for _, word := range words { + if len(word) > maxLen { + maxLen = len(word) + } + } + res := make([]string, 0, maxLen) + for i := 0; i < maxLen; i++ { + var currWord strings.Builder + for _, word := range words { + if i < len(word) { + currWord.WriteByte(word[i]) + } else { + currWord.WriteByte(' ') + } + } + str := currWord.String() + str = strings.TrimRight(str, " ") + res = append(res, str) + } + return res +} diff --git a/tests/1001-1500/1324. print-words-vertically/sol.java b/tests/1001-1500/1324. print-words-vertically/sol.java new file mode 100644 index 00000000..625cdb3c --- /dev/null +++ b/tests/1001-1500/1324. print-words-vertically/sol.java @@ -0,0 +1,28 @@ +class Solution { + public List printVertically(String s) { + String[] words = s.split(" "); + int maxLen = 0; + for (String word : words) { + if (word.length() > maxLen) { + maxLen = word.length(); + } + } + List res = new ArrayList<>(); + for (int i = 0; i < maxLen; i++) { + StringBuilder currWord = new StringBuilder(); + for (String word : words) { + if (i < word.length()) { + currWord.append(word.charAt(i)); + } else { + currWord.append(' '); + } + } + String str = currWord.toString(); + while (str.endsWith(" ")) { + str = str.substring(0, str.length() - 1); + } + res.add(str); + } + return res; + } +} diff --git a/tests/1001-1500/1324. print-words-vertically/sol.kt b/tests/1001-1500/1324. print-words-vertically/sol.kt new file mode 100644 index 00000000..6e43b80c --- /dev/null +++ b/tests/1001-1500/1324. print-words-vertically/sol.kt @@ -0,0 +1,19 @@ +class Solution { + fun printVertically(s: String): List { + val words = s.split(" ") + val maxLen = words.maxOfOrNull { it.length } ?: 0 + val res = mutableListOf() + for (i in 0 until maxLen) { + val sb = StringBuilder() + for (word in words) { + if (i < word.length) { + sb.append(word[i]) + } else { + sb.append(' ') + } + } + res.add(sb.toString().trimEnd()) + } + return res + } +} diff --git a/tests/1001-1500/1324. print-words-vertically/sol.py b/tests/1001-1500/1324. print-words-vertically/sol.py new file mode 100644 index 00000000..f05b0108 --- /dev/null +++ b/tests/1001-1500/1324. print-words-vertically/sol.py @@ -0,0 +1,22 @@ +from typing import List + + +class Solution: + def printVertically(self, s: str) -> List[str]: + words = s.split() + res = [] + + # Find the length of the longest word + max_len = max(len(word) for word in words) + + # Build each vertical word + for i in range(max_len): + curr_word = "" + for word in words: + if i < len(word): + curr_word += word[i] + else: + curr_word += " " + res.append(curr_word.rstrip()) # remove trailing spaces + + return res diff --git a/tests/1001-1500/1324. print-words-vertically/sol.py2 b/tests/1001-1500/1324. print-words-vertically/sol.py2 new file mode 100644 index 00000000..fd13bc7e --- /dev/null +++ b/tests/1001-1500/1324. print-words-vertically/sol.py2 @@ -0,0 +1,18 @@ +class Solution(object): + def printVertically(self, s): + """ + :type s: str + :rtype: List[str] + """ + words = s.split() + max_len = max(len(word) for word in words) + res = [] + for i in range(max_len): + curr_word = "" + for word in words: + if i < len(word): + curr_word += word[i] + else: + curr_word += " " + res.append(curr_word.rstrip()) + return res diff --git a/tests/1001-1500/1324. print-words-vertically/sol.rb b/tests/1001-1500/1324. print-words-vertically/sol.rb new file mode 100644 index 00000000..c7549b14 --- /dev/null +++ b/tests/1001-1500/1324. print-words-vertically/sol.rb @@ -0,0 +1,19 @@ +# @param {String} s +# @return {String[]} +def print_vertically(s) + words = s.split + max_len = words.map(&:length).max + res = [] + (0...max_len).each do |i| + curr_word = "" + words.each do |word| + if i < word.length + curr_word += word[i] + else + curr_word += " " + end + end + res << curr_word.rstrip + end + res +end diff --git a/tests/1001-1500/1324. print-words-vertically/sol.rs b/tests/1001-1500/1324. print-words-vertically/sol.rs new file mode 100644 index 00000000..fc30af7b --- /dev/null +++ b/tests/1001-1500/1324. print-words-vertically/sol.rs @@ -0,0 +1,20 @@ +impl Solution { + pub fn print_vertically(s: String) -> Vec { + let words: Vec<&str> = s.split_whitespace().collect(); + let max_len = words.iter().map(|w| w.len()).max().unwrap_or(0); + let mut res = Vec::new(); + for i in 0..max_len { + let mut curr_word = String::new(); + for word in &words { + if i < word.len() { + curr_word.push(word.as_bytes()[i] as char); + } else { + curr_word.push(' '); + } + } + let trimmed = curr_word.trim_end().to_string(); + res.push(trimmed); + } + res + } +} diff --git a/tests/1001-1500/1324. print-words-vertically/sol.swift b/tests/1001-1500/1324. print-words-vertically/sol.swift new file mode 100644 index 00000000..f6ddc432 --- /dev/null +++ b/tests/1001-1500/1324. print-words-vertically/sol.swift @@ -0,0 +1,23 @@ +class Solution { + func printVertically(_ s: String) -> [String] { + let words = s.split(separator: " ").map { String($0) } + let maxLen = words.map { $0.count }.max() ?? 0 + var res = [String]() + for i in 0.. maxLen) { + maxLen = word.length; + } + } + const res: string[] = []; + for (let i = 0; i < maxLen; i++) { + let currWord = ""; + for (const word of words) { + if (i < word.length) { + currWord += word[i]; + } else { + currWord += " "; + } + } + res.push(currWord.trimEnd()); + } + return res; +} diff --git a/tests/1001-1500/1325. delete-leaves-with-a-given-value/manifest.yaml b/tests/1001-1500/1325. delete-leaves-with-a-given-value/manifest.yaml new file mode 100644 index 00000000..baf515be --- /dev/null +++ b/tests/1001-1500/1325. delete-leaves-with-a-given-value/manifest.yaml @@ -0,0 +1,347 @@ +entry: + id: 1325 + title: delete-leaves-with-a-given-value + params: + root: + type: tree_node + target: + type: int + call: + cpp: "treeNodeToArray(Solution().removeLeafNodes({root}, {target}))" + rust: "TreeNode::tree_node_to_array(Solution::remove_leaf_nodes({root}, {target}))" + python3: "tree_node_to_array(Solution().removeLeafNodes({root}, {target}))" + python2: "tree_node_to_array(Solution().removeLeafNodes({root}, {target}))" + ruby: "tree_node_to_array(remove_leaf_nodes({root}, {target}))" + java: "TreeNode.treeNodeToArray(new Solution().removeLeafNodes({root}, {target}))" + csharp: "TreeNode.TreeNodeToArray(new Solution().RemoveLeafNodes({root}, {target}))" + kotlin: "treeNodeToArray(Solution().removeLeafNodes({root}, {target}))" + go: "treeNodeToArray(removeLeafNodes({root}, {target}))" + dart: "tree_node_to_array(Solution().removeLeafNodes({root}, {target}))" + swift: "tree_node_to_array(Solution().removeLeafNodes({root}, {target}))" + typescript: "treeNodeToArray(removeLeafNodes({root}, {target}))" +judge: + type: exact +limits: + time_ms: 1000 + memory_mb: 256 +oracle: + python3: + call: "Checker().removeLeafNodes(root, target, {result})" + checker: | + class Checker: + def removeLeafNodes(self, root, target, result): + if not isinstance(root, list) or not root or root[0] is None: + return False + if not isinstance(result, list): + return False + + class Node: + def __init__(self, val): + self.val = val + self.left = None + self.right = None + + tree_root = Node(root[0]) + queue = [tree_root] + read = 1 + for node in queue: + if read < len(root) and root[read] is not None: + node.left = Node(root[read]) + queue.append(node.left) + read += 1 + if read < len(root) and root[read] is not None: + node.right = Node(root[read]) + queue.append(node.right) + read += 1 + + def prune(node): + if node is None: + return None + node.left = prune(node.left) + node.right = prune(node.right) + if node.left is None and node.right is None and node.val == target: + return None + return node + + tree_root = prune(tree_root) + if tree_root is None: + return result == [] + expected = [] + queue = [tree_root] + while queue: + node = queue.pop(0) + if node is None: + expected.append(None) + else: + expected.append(node.val) + queue.append(node.left) + queue.append(node.right) + while expected and expected[-1] is None: + expected.pop() + return result == expected +seed: 1325 +tests: + - name: example_one + in: + root: [1, 2, 3, 2, null, 2, 4] + target: 2 + - name: example_two + in: + root: [1, 3, 3, 3, 2] + target: 3 + - name: example_three + in: + root: [1, 2, null, 2, null, 2] + target: 2 + - name: single_target + in: + root: [5] + target: 5 + - name: single_non_target + in: + root: [5] + target: 1 + - name: target_root_with_children + in: + root: [2, 1, 1] + target: 2 + - name: root_becomes_target_leaf + in: + root: [2, 2, 2] + target: 2 + - name: one_target_leaf + in: + root: [1, 2, 3] + target: 2 + - name: no_matching_value + in: + root: [1, 2, 3, 4, 5, 6, 7] + target: 8 + - name: left_cascade + in: + root: [1, 2, 3, 2] + target: 2 + - name: right_cascade + in: + root: [1, 3, 2, null, null, 2] + target: 2 + - name: long_left_spine + in: + root: [1, 2, null, 2, null, 2, null, 2, null, 2, null, 2] + target: 2 + - name: long_right_spine + in: + root: [1, null, 2, null, 2, null, 2, null, 2, null, 2] + target: 2 + - name: independent_cascades + in: + root: [9, 2, 2, 2, null, 3, 2] + target: 2 + - name: cascade_preserves_sibling + in: + root: [5, 2, 8, 2, 2, 1, 2] + target: 2 + - name: target_internal_nodes_survive + in: + root: [2, 1, 2, 2, 3, 2, 4] + target: 2 + - name: minimum_value_target + in: + root: [1, 1, 2, 1, 1, 1, 2] + target: 1 + - name: maximum_value_target + in: + root: [1000, 1000, 2, 1000, 3, 4, 1000] + target: 1000 + - name: all_nodes_target + in: + root: [7, 7, 7, 7, 7, 7, 7] + target: 7 + - name: full_tree_target_leaves_only + in: + root: [4, 2, 6, 2, 3, 2, 2] + target: 2 + - name: non_target_leaf_blocks_parent + in: + root: [3, 3, 4, 3, 3, 4, 4] + target: 3 + - name: sparse_left_then_right + in: + root: [1, 2, null, null, 3, null, 2] + target: 2 + - name: sparse_right_then_left + in: + root: [1, null, 2, 3, null, 2] + target: 2 + - name: mixed_branch_depths + in: + root: [4, 2, 4, 2, 2, 4, 2, 2, null, null, 2] + target: 2 + - name: target_parent_with_one_kept_child + in: + root: [6, 1, 2, null, null, 2, 3] + target: 2 + - name: target_parent_with_left_kept_child + in: + root: [6, 2, 1, 3, 2] + target: 2 + - name: repeated_values_across_levels + in: + root: [9, 4, 4, 4, 5, 5, 4, 4, null, null, 4] + target: 4 + - name: target_on_one_complete_subtree + in: + root: [8, 5, 5, 5, 5, 6, 6, 5, 5, 5, 5, 6, 6, 6, 6] + target: 5 + - name: target_leaves_under_non_target_chain + in: + root: [10, 9, 8, 7, null, null, 6, 5, null, null, 5] + target: 5 + - name: asymmetric_pruning + in: + root: [1, 2, 2, 2, 1, 1, 2, 2, null, null, 2, 2, null, null, 2] + target: 2 + - name: target_at_multiple_frontiers + in: + root: [11, 4, 4, 4, 7, 7, 4, 4, 4, null, null, null, 4, 4, 4] + target: 4 + - name: near_complete_with_gaps + in: + root: [12, 3, 3, 3, null, 4, 3, 3, 3, null, null, 3, 5] + target: 3 + - name: all_same_deep_spine + in: + root: + [ + 13, + 13, + null, + 13, + null, + 13, + null, + 13, + null, + 13, + null, + 13, + null, + 13, + null, + 13, + ] + target: 13 + - name: alternating_spine + in: + root: [14, null, 2, null, 14, null, 2, null, 14, null, 2, null, 14] + target: 14 + - name: complete_three_levels_no_prune + in: + root: [15, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] + target: 1000 + - name: complete_four_levels_partial_prune + in: + root: + [ + 16, + 2, + 3, + 2, + 4, + 5, + 2, + 2, + 2, + 4, + 2, + 2, + 5, + 2, + 2, + 2, + 2, + 3, + 3, + 4, + 4, + 5, + 5, + 2, + 2, + 3, + 3, + 4, + 4, + 5, + 5, + ] + target: 2 + - name: high_value_non_target_structure + in: + root: [999, 1000, 998, 1000, 997, 996, 1000] + target: 1000 + - name: maximum_complete_tree_no_match + in: + root: + gen: "array" + len: 3000 + of: + gen: "int" + min: 2 + max: 1000 + distinct: false + sorted: false + elemType: "int" + target: 1 + seed: 132501 + - name: maximum_complete_tree_all_match + in: + root: + gen: "array" + len: 3000 + of: + gen: "int" + min: 1000 + max: 1000 + distinct: false + sorted: false + elemType: "int" + target: 1000 + seed: 132502 + - name: broad_tree_cascading_inner_targets + in: + root: + [ + 17, + 2, + 2, + 2, + 2, + 8, + 2, + 2, + 2, + 2, + 2, + 8, + 8, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 8, + 8, + 8, + 8, + 2, + 2, + 2, + 2, + 2, + 2, + ] + target: 2 diff --git a/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.cpp b/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.cpp new file mode 100644 index 00000000..b9036a34 --- /dev/null +++ b/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.cpp @@ -0,0 +1,38 @@ +/** + * 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: + TreeNode* removeLeafNodes(TreeNode* root, int target) { + function traverseAndRemove = [&](TreeNode* temp) -> bool { + if (temp == nullptr) { + return false; + } + if (temp->left == nullptr && temp->right == nullptr) { + return temp->val != target; + } + bool left = traverseAndRemove(temp->left); + bool right = traverseAndRemove(temp->right); + if (!left) { + temp->left = nullptr; + } + if (!right) { + temp->right = nullptr; + } + return left || right || temp->val != target; + }; + + if (!traverseAndRemove(root)) { + return nullptr; + } + return root; + } +}; diff --git a/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.cs b/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.cs new file mode 100644 index 00000000..680eb232 --- /dev/null +++ b/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.cs @@ -0,0 +1,39 @@ +/** + * 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 TreeNode RemoveLeafNodes(TreeNode root, int target) { + bool TraverseAndRemove(TreeNode temp) { + if (temp == null) { + return false; + } + if (temp.left == null && temp.right == null) { + return temp.val != target; + } + bool left = TraverseAndRemove(temp.left); + bool right = TraverseAndRemove(temp.right); + if (!left) { + temp.left = null; + } + if (!right) { + temp.right = null; + } + return left || right || temp.val != target; + } + + if (!TraverseAndRemove(root)) { + return null; + } + return root; + } +} diff --git a/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.dart b/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.dart new file mode 100644 index 00000000..2ea0a93c --- /dev/null +++ b/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.dart @@ -0,0 +1,35 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * int val; + * TreeNode? left; + * TreeNode? right; + * TreeNode([this.val = 0, this.left, this.right]); + * } + */ +class Solution { + TreeNode? removeLeafNodes(TreeNode? root, int target) { + bool traverseAndRemove(TreeNode? temp) { + if (temp == null) { + return false; + } + if (temp.left == null && temp.right == null) { + return temp.val != target; + } + bool left = traverseAndRemove(temp.left); + bool right = traverseAndRemove(temp.right); + if (!left) { + temp.left = null; + } + if (!right) { + temp.right = null; + } + return left || right || temp.val != target; + } + + if (!traverseAndRemove(root)) { + return null; + } + return root; + } +} diff --git a/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.go b/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.go new file mode 100644 index 00000000..4c96970e --- /dev/null +++ b/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.go @@ -0,0 +1,33 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func removeLeafNodes(root *TreeNode, target int) *TreeNode { + var traverseAndRemove func(temp *TreeNode) bool + traverseAndRemove = func(temp *TreeNode) bool { + if temp == nil { + return false + } + if temp.Left == nil && temp.Right == nil { + return temp.Val != target + } + left := traverseAndRemove(temp.Left) + right := traverseAndRemove(temp.Right) + if !left { + temp.Left = nil + } + if !right { + temp.Right = nil + } + return left || right || temp.Val != target + } + + if !traverseAndRemove(root) { + return nil + } + return root +} diff --git a/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.java b/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.java new file mode 100644 index 00000000..13304775 --- /dev/null +++ b/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.java @@ -0,0 +1,41 @@ +/** + * 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 TreeNode removeLeafNodes(TreeNode root, int target) { + if (!traverseAndRemove(root, target)) { + return null; + } + return root; + } + + private boolean traverseAndRemove(TreeNode temp, int target) { + if (temp == null) { + return false; + } + if (temp.left == null && temp.right == null) { + return temp.val != target; + } + boolean left = traverseAndRemove(temp.left, target); + boolean right = traverseAndRemove(temp.right, target); + if (!left) { + temp.left = null; + } + if (!right) { + temp.right = null; + } + return left || right || temp.val != target; + } +} diff --git a/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.kt b/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.kt new file mode 100644 index 00000000..9a06f496 --- /dev/null +++ b/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.kt @@ -0,0 +1,36 @@ +/** + * 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 removeLeafNodes(root: TreeNode?, target: Int): TreeNode? { + fun traverseAndRemove(temp: TreeNode?): Boolean { + if (temp == null) { + return false + } + if (temp.left == null && temp.right == null) { + return temp.`val` != target + } + val left = traverseAndRemove(temp.left) + val right = traverseAndRemove(temp.right) + if (!left) { + temp.left = null + } + if (!right) { + temp.right = null + } + return left || right || temp.`val` != target + } + + if (!traverseAndRemove(root)) { + return null + } + return root + } +} diff --git a/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.py b/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.py new file mode 100644 index 00000000..4040f2de --- /dev/null +++ b/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.py @@ -0,0 +1,29 @@ +# 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 removeLeafNodes( + self, root: Optional[TreeNode], target: int + ) -> Optional[TreeNode]: + def traverseAndRemove(temp): + if not temp: + return + if not temp.left and not temp.right: + if temp.val == target: + return False + else: + return True + left = traverseAndRemove(temp.left) + right = traverseAndRemove(temp.right) + if not left: + temp.left = None + if not right: + temp.right = None + return left or right or temp.val != target + + if not traverseAndRemove(root): + return + return root diff --git a/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.py2 b/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.py2 new file mode 100644 index 00000000..e444b83c --- /dev/null +++ b/tests/1001-1500/1325. delete-leaves-with-a-given-value/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 removeLeafNodes(self, root, target): + """ + :type root: Optional[TreeNode] + :type target: int + :rtype: Optional[TreeNode] + """ + def traverseAndRemove(temp): + if not temp: + return False + if not temp.left and not temp.right: + if temp.val == target: + return False + else: + return True + left = traverseAndRemove(temp.left) + right = traverseAndRemove(temp.right) + if not left: + temp.left = None + if not right: + temp.right = None + return left or right or temp.val != target + + if not traverseAndRemove(root): + return None + return root diff --git a/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.rb b/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.rb new file mode 100644 index 00000000..65fb72ef --- /dev/null +++ b/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.rb @@ -0,0 +1,28 @@ +# 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} target +# @return {TreeNode} +def remove_leaf_nodes(root, target) + def traverse_and_remove(temp, target) + return false if temp.nil? + if temp.left.nil? && temp.right.nil? + return temp.val != target + end + left = traverse_and_remove(temp.left, target) + right = traverse_and_remove(temp.right, target) + temp.left = nil if !left + temp.right = nil if !right + return left || right || temp.val != target + end + + return nil if !traverse_and_remove(root, target) + return root +end diff --git a/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.rs b/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.rs new file mode 100644 index 00000000..4a41457c --- /dev/null +++ b/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.rs @@ -0,0 +1,57 @@ +// 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 remove_leaf_nodes(root: Option>>, target: i32) -> Option>> { + fn traverse_and_remove(temp: Option>>, target: i32) -> bool { + match temp { + None => false, + Some(node) => { + let node_ref = node.borrow(); + if node_ref.left.is_none() && node_ref.right.is_none() { + return node_ref.val != target; + } + drop(node_ref); + + let left_result = { + let left_child = node.borrow().left.clone(); + traverse_and_remove(left_child, target) + }; + let right_result = { + let right_child = node.borrow().right.clone(); + traverse_and_remove(right_child, target) + }; + + if !left_result { + node.borrow_mut().left = None; + } + if !right_result { + node.borrow_mut().right = None; + } + + left_result || right_result || node.borrow().val != target + } + } + } + + if !traverse_and_remove(root.clone(), target) { + return None; + } + return root; + } +} diff --git a/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.swift b/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.swift new file mode 100644 index 00000000..380874c0 --- /dev/null +++ b/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.swift @@ -0,0 +1,41 @@ +/** + * 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 removeLeafNodes(_ root: TreeNode?, _ target: Int) -> TreeNode? { + func traverseAndRemove(_ temp: TreeNode?) -> Bool { + guard let temp = temp else { + return false + } + if temp.left == nil && temp.right == nil { + return temp.val != target + } + let left = traverseAndRemove(temp.left) + let right = traverseAndRemove(temp.right) + if !left { + temp.left = nil + } + if !right { + temp.right = nil + } + return left || right || temp.val != target + } + + if !traverseAndRemove(root) { + return nil + } + return root + } +} diff --git a/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.ts b/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.ts new file mode 100644 index 00000000..3524caa6 --- /dev/null +++ b/tests/1001-1500/1325. delete-leaves-with-a-given-value/sol.ts @@ -0,0 +1,41 @@ +/** + * 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 removeLeafNodes( + root: TreeNode | null, + target: number, +): TreeNode | null { + const traverseAndRemove = (temp: TreeNode | null): boolean => { + if (temp === null) { + return false; + } + if (temp.left === null && temp.right === null) { + return temp.val !== target; + } + const left = traverseAndRemove(temp.left); + const right = traverseAndRemove(temp.right); + if (!left) { + temp.left = null; + } + if (!right) { + temp.right = null; + } + return left || right || temp.val !== target; + }; + + if (!traverseAndRemove(root)) { + return null; + } + return root; +} diff --git a/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/manifest.yaml b/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/manifest.yaml new file mode 100644 index 00000000..30333aa0 --- /dev/null +++ b/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/manifest.yaml @@ -0,0 +1,316 @@ +entry: + id: 1326 + title: "minimum-number-of-taps-to-open-to-water-a-garden" + params: + n: + type: int + ranges: + type: array + items: + type: int + call: + cpp: "Solution().minTaps({n}, {ranges})" + rust: "Solution::min_taps({n}, {ranges})" + python3: "Solution().minTaps({n}, {ranges})" + python2: "Solution().minTaps({n}, {ranges})" + ruby: "min_taps({n}, {ranges})" + java: "new Solution().minTaps({n}, {ranges})" + csharp: "new Solution().MinTaps({n}, {ranges})" + kotlin: "Solution().minTaps({n}, {ranges})" + go: "minTaps({n}, {ranges})" + dart: "Solution().minTaps({n}, {ranges})" + swift: "Solution().minTaps({n}, {ranges})" + typescript: "minTaps({n}, {ranges})" +judge: + type: "exact" +limits: + time_ms: 500 + memory_mb: 300 +oracle: + python3: + call: "Checker().minTaps(n, ranges, {result})" + checker: | + class Checker: + def minTaps(self, n, ranges, result): + if isinstance(result, bool) or not isinstance(result, int): + return False + if n < 1 or len(ranges) != n + 1: + return False + + intervals = [] + for position, radius in enumerate(ranges): + if radius < 0 or radius > 100: + return False + intervals.append((max(0, position - radius), min(n, position + radius))) + intervals.sort() + + covered = 0 + taps = 0 + index = 0 + while covered < n: + furthest = covered + while index < len(intervals) and intervals[index][0] <= covered: + furthest = max(furthest, intervals[index][1]) + index += 1 + if furthest == covered: + return result == -1 + covered = furthest + taps += 1 + return result == taps +seed: 1326 +tests: + - name: "single_garden_left_tap" + in: + n: 1 + ranges: [1, 0] + out: 1 + - name: "single_garden_right_tap" + in: + n: 1 + ranges: [0, 1] + out: 1 + - name: "single_center_covers_two" + in: + n: 2 + ranges: [0, 2, 0] + out: 1 + - name: "example_one" + in: + n: 5 + ranges: [3, 4, 1, 1, 0, 0] + out: 1 + - name: "example_two_all_zero" + in: + n: 3 + ranges: [0, 0, 0, 0] + out: -1 + - name: "two_overlapping_taps" + in: + n: 4 + ranges: [0, 1, 1, 1, 0] + out: 2 + - name: "unit_radius_chain" + in: + n: 6 + ranges: [1, 1, 1, 1, 1, 1, 1] + out: 3 + - name: "radius_two_chain" + in: + n: 8 + ranges: [2, 2, 2, 2, 2, 2, 2, 2, 2] + out: 2 + - name: "left_boundary_alone" + in: + n: 5 + ranges: [5, 0, 0, 0, 0, 0] + out: 1 + - name: "unbridgeable_middle_gap" + in: + n: 6 + ranges: [2, 0, 0, 0, 0, 2, 0] + out: -1 + - name: "both_endpoints_need_coverage" + in: + n: 3 + ranges: [1, 1, 1, 1] + out: 2 + - name: "right_boundary_alone" + in: + n: 5 + ranges: [0, 0, 0, 0, 0, 5] + out: 1 + - name: "zero_radius_everywhere" + in: + n: 5 + ranges: [0, 0, 0, 0, 0, 0] + out: -1 + - name: "two_taps_meet_at_middle" + in: + n: 5 + ranges: [2, 0, 1, 0, 2, 0] + out: 2 + - name: "alternating_unit_taps" + in: + n: 7 + ranges: [0, 1, 0, 1, 0, 1, 0, 1] + out: 4 + - name: "long_overlap_from_middle" + in: + n: 7 + ranges: [3, 0, 0, 0, 3, 0, 0, 0] + out: 2 + - name: "two_large_overlaps" + in: + n: 10 + ranges: [0, 5, 0, 0, 0, 0, 4, 0, 0, 0, 0] + out: 2 + - name: "three_staged_intervals" + in: + n: 10 + ranges: [0, 0, 2, 0, 0, 3, 0, 0, 2, 0, 0] + out: 3 + - name: "coverage_stops_after_first_unit" + in: + n: 10 + ranges: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + out: -1 + - name: "far_right_full_radius" + in: + n: 10 + ranges: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10] + out: 1 + - name: "two_endpoint_intervals" + in: + n: 2 + ranges: [1, 0, 1] + - name: "three_exactly_touching_intervals" + in: + n: 9 + ranges: [0, 2, 0, 0, 1, 0, 0, 2, 0, 0] + - name: "left_edge_not_reached" + in: + n: 9 + ranges: [0, 1, 0, 0, 0, 0, 0, 0, 0, 0] + - name: "large_left_then_middle" + in: + n: 9 + ranges: [4, 0, 0, 0, 0, 4, 0, 0, 0, 0] + - name: "missing_initial_coverage" + in: + n: 12 + ranges: [0, 0, 2, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0] + - name: "four_taps_with_overlaps" + in: + n: 12 + ranges: [2, 0, 0, 0, 3, 0, 0, 0, 3, 0, 0, 0, 2] + - name: "three_wide_centered_taps" + in: + n: 12 + ranges: [0, 3, 0, 0, 0, 3, 0, 0, 0, 3, 0, 0, 0] + - name: "three_taps_touching_boundaries" + in: + n: 15 + ranges: [0, 0, 2, 0, 0, 0, 0, 3, 0, 0, 0, 0, 3, 0, 0, 0] + - name: "overlap_requires_late_final_tap" + in: + n: 15 + ranges: [5, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 3, 0, 0, 0] + - name: "fifteen_unit_coverage" + in: + n: 15 + ranges: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - name: "one_maximum_radius_tap" + in: + n: 20 + ranges: [100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - name: "rightmost_tap_spans_garden" + in: + n: 20 + ranges: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20] + - name: "initial_tap_cannot_be_extended" + in: + n: 20 + ranges: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - name: "four_interval_chain_length_twenty" + in: + n: 20 + ranges: [4, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 2, 0, 0] + - name: "four_touching_triplets" + in: + n: 20 + ranges: [0, 0, 0, 3, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 2] + - name: "seven_sparse_radius_two_taps" + in: + n: 25 + ranges: + [ + 2, + 0, + 0, + 0, + 2, + 0, + 0, + 0, + 2, + 0, + 0, + 0, + 2, + 0, + 0, + 0, + 2, + 0, + 0, + 0, + 2, + 0, + 0, + 0, + 2, + 0, + ] + - name: "one_hundred_length_alternating_taps" + in: + n: 30 + ranges: + [ + 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, + ] + - name: "interior_maximum_radius_clamps_both_sides" + in: + n: 20 + ranges: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - name: "large_all_zero_impossible" + seed: 132601 + in: + n: 10000 + ranges: + gen: "array" + len: 10001 + of: + gen: "int" + min: 0 + max: 0 + - name: "large_maximum_allowed_radius" + seed: 132602 + in: + n: 10000 + ranges: + gen: "array" + len: 10001 + of: + gen: "int" + min: 100 + max: 100 diff --git a/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.cpp b/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.cpp new file mode 100644 index 00000000..9a7e1c1c --- /dev/null +++ b/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + int minTaps(int n, vector& ranges) { + vector maxRange(n + 1, 0); + + for (int i = 0; i < ranges.size(); i++) { + int left = max(0, i - ranges[i]); + int right = min(n, i + ranges[i]); + maxRange[left] = max(maxRange[left], right); + } + + int end = 0, farthest = 0, taps = 0; + int i = 0; + + while (end < n) { + while (i <= end) { + farthest = max(farthest, maxRange[i]); + i++; + } + + if (farthest <= end) { + return -1; + } + + end = farthest; + taps++; + } + + return taps; + } +}; diff --git a/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.cs b/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.cs new file mode 100644 index 00000000..1e3a4cce --- /dev/null +++ b/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.cs @@ -0,0 +1,30 @@ +public class Solution { + public int MinTaps(int n, int[] ranges) { + int[] maxRange = new int[n + 1]; + + for (int index = 0; index < ranges.Length; index++) { + int left = Math.Max(0, index - ranges[index]); + int right = Math.Min(n, index + ranges[index]); + maxRange[left] = Math.Max(maxRange[left], right); + } + + int end = 0, farthest = 0, taps = 0; + int i = 0; + + while (end < n) { + while (i <= end) { + farthest = Math.Max(farthest, maxRange[i]); + i++; + } + + if (farthest <= end) { + return -1; + } + + end = farthest; + taps++; + } + + return taps; + } +} diff --git a/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.dart b/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.dart new file mode 100644 index 00000000..dd0be0d4 --- /dev/null +++ b/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.dart @@ -0,0 +1,30 @@ +class Solution { + int minTaps(int n, List ranges) { + List maxRange = List.filled(n + 1, 0); + + for (int i = 0; i < ranges.length; i++) { + int left = (0 > i - ranges[i]) ? 0 : i - ranges[i]; + int right = (n < i + ranges[i]) ? n : i + ranges[i]; + maxRange[left] = (maxRange[left] > right) ? maxRange[left] : right; + } + + int end = 0, farthest = 0, taps = 0; + int i = 0; + + while (end < n) { + while (i <= end) { + farthest = (farthest > maxRange[i]) ? farthest : maxRange[i]; + i++; + } + + if (farthest <= end) { + return -1; + } + + end = farthest; + taps++; + } + + return taps; + } +} diff --git a/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.go b/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.go new file mode 100644 index 00000000..66a22ce4 --- /dev/null +++ b/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.go @@ -0,0 +1,28 @@ +func minTaps(n int, ranges []int) int { + maxRange := make([]int, n+1) + + for i := 0; i < len(ranges); i++ { + left := max(0, i - ranges[i]) + right := min(n, i + ranges[i]) + maxRange[left] = max(maxRange[left], right) + } + + end, farthest, taps := 0, 0, 0 + i := 0 + + for end < n { + for i <= end { + farthest = max(farthest, maxRange[i]) + i++ + } + + if farthest <= end { + return -1 + } + + end = farthest + taps++ + } + + return taps +} diff --git a/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.java b/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.java new file mode 100644 index 00000000..c7590b11 --- /dev/null +++ b/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.java @@ -0,0 +1,30 @@ +class Solution { + public int minTaps(int n, int[] ranges) { + int[] maxRange = new int[n + 1]; + + for (int i = 0; i < ranges.length; i++) { + int left = Math.max(0, i - ranges[i]); + int right = Math.min(n, i + ranges[i]); + maxRange[left] = Math.max(maxRange[left], right); + } + + int end = 0, farthest = 0, taps = 0; + int i = 0; + + while (end < n) { + while (i <= end) { + farthest = Math.max(farthest, maxRange[i]); + i++; + } + + if (farthest <= end) { + return -1; + } + + end = farthest; + taps++; + } + + return taps; + } +} diff --git a/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.kt b/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.kt new file mode 100644 index 00000000..5bd6cbad --- /dev/null +++ b/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.kt @@ -0,0 +1,32 @@ +class Solution { + fun minTaps(n: Int, ranges: IntArray): Int { + val maxRange = IntArray(n + 1) + + for (i in ranges.indices) { + val left = maxOf(0, i - ranges[i]) + val right = minOf(n, i + ranges[i]) + maxRange[left] = maxOf(maxRange[left], right) + } + + var end = 0 + var farthest = 0 + var taps = 0 + var i = 0 + + while (end < n) { + while (i <= end) { + farthest = maxOf(farthest, maxRange[i]) + i++ + } + + if (farthest <= end) { + return -1 + } + + end = farthest + taps++ + } + + return taps + } +} diff --git a/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.py b/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.py new file mode 100644 index 00000000..7a15d90f --- /dev/null +++ b/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.py @@ -0,0 +1,24 @@ +class Solution: + def minTaps(self, n: int, ranges: List[int]) -> int: + max_range = [0] * (n + 1) + + for i in range(len(ranges)): + left = max(0, i - ranges[i]) + right = min(n, i + ranges[i]) + max_range[left] = max(max_range[left], right) + + end = farthest = taps = 0 + i = 0 + + while end < n: + while i <= end: + farthest = max(farthest, max_range[i]) + i += 1 + + if farthest <= end: + return -1 # Unable to cover the entire garden + + end = farthest + taps += 1 + + return taps diff --git a/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.py2 b/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.py2 new file mode 100644 index 00000000..db7578d5 --- /dev/null +++ b/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.py2 @@ -0,0 +1,29 @@ +class Solution(object): + def minTaps(self, n, ranges): + """ + :type n: int + :type ranges: List[int] + :rtype: int + """ + max_range = [0] * (n + 1) + + for i in range(len(ranges)): + left = max(0, i - ranges[i]) + right = min(n, i + ranges[i]) + max_range[left] = max(max_range[left], right) + + end = farthest = taps = 0 + i = 0 + + while end < n: + while i <= end: + farthest = max(farthest, max_range[i]) + i += 1 + + if farthest <= end: + return -1 + + end = farthest + taps += 1 + + return taps diff --git a/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.rb b/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.rb new file mode 100644 index 00000000..836b776e --- /dev/null +++ b/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.rb @@ -0,0 +1,31 @@ +# @param {Integer} n +# @param {Integer[]} ranges +# @return {Integer} +def min_taps(n, ranges) + max_range = [0] * (n + 1) + + ranges.each_with_index do |r, i| + left = [0, i - r].max + right = [n, i + r].min + max_range[left] = [max_range[left], right].max + end + + end_pos = farthest = taps = 0 + i = 0 + + while end_pos < n + while i <= end_pos + farthest = [farthest, max_range[i]].max + i += 1 + end + + if farthest <= end_pos + return -1 + end + + end_pos = farthest + taps += 1 + end + + return taps +end diff --git a/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.rs b/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.rs new file mode 100644 index 00000000..b439c54a --- /dev/null +++ b/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.rs @@ -0,0 +1,33 @@ +impl Solution { + pub fn min_taps(n: i32, ranges: Vec) -> i32 { + let n = n as usize; + let mut max_range = vec![0; n + 1]; + + for i in 0..ranges.len() { + let left = if (i as i32 - ranges[i]) < 0 { 0 } else { i as i32 - ranges[i] } as usize; + let right = if (i as i32 + ranges[i]) > n as i32 { n } else { (i as i32 + ranges[i]) as usize }; + max_range[left] = max_range[left].max(right); + } + + let mut end = 0; + let mut farthest = 0; + let mut taps = 0; + let mut i = 0; + + while end < n { + while i <= end { + farthest = farthest.max(max_range[i]); + i += 1; + } + + if farthest <= end { + return -1; + } + + end = farthest; + taps += 1; + } + + taps + } +} diff --git a/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.swift b/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.swift new file mode 100644 index 00000000..96cffac7 --- /dev/null +++ b/tests/1001-1500/1326. minimum-number-of-taps-to-open-to-water-a-garden/sol.swift @@ -0,0 +1,30 @@ +class Solution { + func minTaps(_ n: Int, _ ranges: [Int]) -> Int { + var maxRange = [Int](repeating: 0, count: n + 1) + + for i in 0.. chars = palindrome.split(''); + for (int i = 0; i < chars.length ~/ 2; i++) { + if (chars[i] != 'a') { + chars[i] = 'a'; + return chars.join(''); + } + } + chars[chars.length - 1] = 'b'; + return chars.join(''); + } +} diff --git a/tests/1001-1500/1328. break-a-palindrome/sol.go b/tests/1001-1500/1328. break-a-palindrome/sol.go new file mode 100644 index 00000000..674ad38c --- /dev/null +++ b/tests/1001-1500/1328. break-a-palindrome/sol.go @@ -0,0 +1,14 @@ +func breakPalindrome(palindrome string) string { + if len(palindrome) == 1 { + return "" + } + arr := []byte(palindrome) + for i := 0; i < len(arr)/2; i++ { + if arr[i] != 'a' { + arr[i] = 'a' + return string(arr) + } + } + arr[len(arr)-1] = 'b' + return string(arr) +} diff --git a/tests/1001-1500/1328. break-a-palindrome/sol.java b/tests/1001-1500/1328. break-a-palindrome/sol.java new file mode 100644 index 00000000..fcb63bbe --- /dev/null +++ b/tests/1001-1500/1328. break-a-palindrome/sol.java @@ -0,0 +1,14 @@ +class Solution { + public String breakPalindrome(String palindrome) { + if (palindrome.length() == 1) return ""; + char[] arr = palindrome.toCharArray(); + for (int i = 0; i < arr.length / 2; i++) { + if (arr[i] != 'a') { + arr[i] = 'a'; + return new String(arr); + } + } + arr[arr.length - 1] = 'b'; + return new String(arr); + } +} diff --git a/tests/1001-1500/1328. break-a-palindrome/sol.kt b/tests/1001-1500/1328. break-a-palindrome/sol.kt new file mode 100644 index 00000000..c218e28e --- /dev/null +++ b/tests/1001-1500/1328. break-a-palindrome/sol.kt @@ -0,0 +1,14 @@ +class Solution { + fun breakPalindrome(palindrome: String): String { + if (palindrome.length == 1) return "" + val arr = palindrome.toCharArray() + for (i in 0 until arr.size / 2) { + if (arr[i] != 'a') { + arr[i] = 'a' + return String(arr) + } + } + arr[arr.size - 1] = 'b' + return String(arr) + } +} diff --git a/tests/1001-1500/1328. break-a-palindrome/sol.py b/tests/1001-1500/1328. break-a-palindrome/sol.py new file mode 100644 index 00000000..9ea7f018 --- /dev/null +++ b/tests/1001-1500/1328. break-a-palindrome/sol.py @@ -0,0 +1,12 @@ +class Solution(object): + def breakPalindrome(self, palindrome): + """ + :type palindrome: str + :rtype: str + """ + if len(palindrome) == 1: + return "" + for i in range(len(palindrome) // 2): + if palindrome[i] != "a": + return palindrome[:i] + "a" + palindrome[i + 1 :] + return palindrome[:-1] + "b" diff --git a/tests/1001-1500/1328. break-a-palindrome/sol.py2 b/tests/1001-1500/1328. break-a-palindrome/sol.py2 new file mode 100644 index 00000000..c53187a2 --- /dev/null +++ b/tests/1001-1500/1328. break-a-palindrome/sol.py2 @@ -0,0 +1,11 @@ +class Solution(object): + def breakPalindrome(self, palindrome): + """ + :type palindrome: str + :rtype: str + """ + if len(palindrome) == 1: return "" + for i in range(len(palindrome) // 2): + if palindrome[i] != 'a': + return palindrome[:i] + 'a' + palindrome[i+1:] + return palindrome[:-1] + 'b' diff --git a/tests/1001-1500/1328. break-a-palindrome/sol.rb b/tests/1001-1500/1328. break-a-palindrome/sol.rb new file mode 100644 index 00000000..ce4bcf1c --- /dev/null +++ b/tests/1001-1500/1328. break-a-palindrome/sol.rb @@ -0,0 +1,11 @@ +# @param {String} palindrome +# @return {String} +def break_palindrome(palindrome) + return "" if palindrome.length == 1 + (0...palindrome.length / 2).each do |i| + if palindrome[i] != 'a' + return palindrome[0...i] + 'a' + palindrome[i+1..-1] + end + end + palindrome[0...-1] + 'b' +end diff --git a/tests/1001-1500/1328. break-a-palindrome/sol.rs b/tests/1001-1500/1328. break-a-palindrome/sol.rs new file mode 100644 index 00000000..b472edc0 --- /dev/null +++ b/tests/1001-1500/1328. break-a-palindrome/sol.rs @@ -0,0 +1,17 @@ +impl Solution { + pub fn break_palindrome(palindrome: String) -> String { + if palindrome.len() == 1 { + return "".to_string(); + } + let mut chars: Vec = palindrome.chars().collect(); + let n = chars.len(); + for i in 0..n / 2 { + if chars[i] != 'a' { + chars[i] = 'a'; + return chars.into_iter().collect(); + } + } + chars[n - 1] = 'b'; + chars.into_iter().collect() + } +} diff --git a/tests/1001-1500/1328. break-a-palindrome/sol.swift b/tests/1001-1500/1328. break-a-palindrome/sol.swift new file mode 100644 index 00000000..a275ce94 --- /dev/null +++ b/tests/1001-1500/1328. break-a-palindrome/sol.swift @@ -0,0 +1,14 @@ +class Solution { + func breakPalindrome(_ palindrome: String) -> String { + if palindrome.count == 1 { return "" } + var chars = Array(palindrome) + for i in 0..> diagonalSort(vector>& mat) { + int m = mat.size(), n = mat[0].size(); + unordered_map> diagonals; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + diagonals[i - j].push_back(mat[i][j]); + } + } + + for (auto& [key, vec] : diagonals) { + sort(vec.begin(), vec.end(), greater()); + } + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + auto& vec = diagonals[i - j]; + mat[i][j] = vec.back(); + vec.pop_back(); + } + } + + return mat; + } +}; diff --git a/tests/1001-1500/1329. sort-the-matrix-diagonally/sol.cs b/tests/1001-1500/1329. sort-the-matrix-diagonally/sol.cs new file mode 100644 index 00000000..4ceabb8e --- /dev/null +++ b/tests/1001-1500/1329. sort-the-matrix-diagonally/sol.cs @@ -0,0 +1,32 @@ +using System.Collections.Generic; + +public class Solution { + public int[][] DiagonalSort(int[][] mat) { + int m = mat.Length, n = mat[0].Length; + Dictionary> diagonals = new Dictionary>(); + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + int key = i - j; + if (!diagonals.ContainsKey(key)) { + diagonals[key] = new List(); + } + diagonals[key].Add(mat[i][j]); + } + } + + foreach (var list in diagonals.Values) { + list.Sort((a, b) => b - a); + } + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + var list = diagonals[i - j]; + mat[i][j] = list[list.Count - 1]; + list.RemoveAt(list.Count - 1); + } + } + + return mat; + } +} diff --git a/tests/1001-1500/1329. sort-the-matrix-diagonally/sol.dart b/tests/1001-1500/1329. sort-the-matrix-diagonally/sol.dart new file mode 100644 index 00000000..abca77a3 --- /dev/null +++ b/tests/1001-1500/1329. sort-the-matrix-diagonally/sol.dart @@ -0,0 +1,26 @@ +class Solution { + List> diagonalSort(List> mat) { + int m = mat.length, n = mat[0].length; + Map> diagonals = {}; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + int key = i - j; + diagonals.putIfAbsent(key, () => []); + diagonals[key]!.add(mat[i][j]); + } + } + + for (var list in diagonals.values) { + list.sort((a, b) => b.compareTo(a)); + } + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + mat[i][j] = diagonals[i - j]!.removeLast(); + } + } + + return mat; + } +} diff --git a/tests/1001-1500/1329. sort-the-matrix-diagonally/sol.go b/tests/1001-1500/1329. sort-the-matrix-diagonally/sol.go new file mode 100644 index 00000000..2de023ea --- /dev/null +++ b/tests/1001-1500/1329. sort-the-matrix-diagonally/sol.go @@ -0,0 +1,28 @@ +func diagonalSort(mat [][]int) [][]int { + m, n := len(mat), len(mat[0]) + diagonals := make(map[int][]int) + + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + key := i - j + diagonals[key] = append(diagonals[key], mat[i][j]) + } + } + + for key := range diagonals { + sort.Slice(diagonals[key], func(a, b int) bool { + return diagonals[key][a] > diagonals[key][b] + }) + } + + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + key := i - j + list := diagonals[key] + mat[i][j] = list[len(list)-1] + diagonals[key] = list[:len(list)-1] + } + } + + return mat +} diff --git a/tests/1001-1500/1329. sort-the-matrix-diagonally/sol.java b/tests/1001-1500/1329. sort-the-matrix-diagonally/sol.java new file mode 100644 index 00000000..35422f37 --- /dev/null +++ b/tests/1001-1500/1329. sort-the-matrix-diagonally/sol.java @@ -0,0 +1,31 @@ +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +class Solution { + public int[][] diagonalSort(int[][] mat) { + int m = mat.length, n = mat[0].length; + Map> diagonals = new HashMap<>(); + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + int key = i - j; + diagonals.computeIfAbsent(key, k -> new ArrayList<>()).add(mat[i][j]); + } + } + + for (List list : diagonals.values()) { + list.sort((a, b) -> b - a); + } + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + List list = diagonals.get(i - j); + mat[i][j] = list.remove(list.size() - 1); + } + } + + return mat; + } +} diff --git a/tests/1001-1500/1329. sort-the-matrix-diagonally/sol.kt b/tests/1001-1500/1329. sort-the-matrix-diagonally/sol.kt new file mode 100644 index 00000000..c8aacb69 --- /dev/null +++ b/tests/1001-1500/1329. sort-the-matrix-diagonally/sol.kt @@ -0,0 +1,27 @@ +class Solution { + fun diagonalSort(mat: Array): Array { + val m = mat.size + val n = mat[0].size + val diagonals = mutableMapOf>() + + for (i in 0 until m) { + for (j in 0 until n) { + val key = i - j + diagonals.getOrPut(key) { mutableListOf() }.add(mat[i][j]) + } + } + + for (list in diagonals.values) { + list.sortDescending() + } + + for (i in 0 until m) { + for (j in 0 until n) { + val list = diagonals[i - j]!! + mat[i][j] = list.removeAt(list.size - 1) + } + } + + return mat + } +} diff --git a/tests/1001-1500/1329. sort-the-matrix-diagonally/sol.py b/tests/1001-1500/1329. sort-the-matrix-diagonally/sol.py new file mode 100644 index 00000000..28195744 --- /dev/null +++ b/tests/1001-1500/1329. sort-the-matrix-diagonally/sol.py @@ -0,0 +1,28 @@ +from collections import defaultdict +from typing import List + + +class Solution(object): + def diagonalSort(self, mat): + """ + :type mat: List[List[int]] + :rtype: List[List[int]] + """ + m, n = len(mat), len(mat[0]) + diagonals = defaultdict(list) + + # Step 1: Group all elements by their diagonals + for i in range(m): + for j in range(n): + diagonals[i - j].append(mat[i][j]) + + # Step 2: Sort each diagonal in reverse so we can pop smallest later + for key in diagonals: + diagonals[key].sort(reverse=True) + + # Step 3: Fill back the sorted values + for i in range(m): + for j in range(n): + mat[i][j] = diagonals[i - j].pop() + + return mat diff --git a/tests/1001-1500/1329. sort-the-matrix-diagonally/sol.py2 b/tests/1001-1500/1329. sort-the-matrix-diagonally/sol.py2 new file mode 100644 index 00000000..4dd610c7 --- /dev/null +++ b/tests/1001-1500/1329. sort-the-matrix-diagonally/sol.py2 @@ -0,0 +1,24 @@ +class Solution(object): + def diagonalSort(self, mat): + """ + :type mat: List[List[int]] + :rtype: List[List[int]] + """ + m, n = len(mat), len(mat[0]) + diagonals = defaultdict(list) + + # Step 1: Group all elements by their diagonals + for i in range(m): + for j in range(n): + diagonals[i - j].append(mat[i][j]) + + # Step 2: Sort each diagonal in reverse so we can pop smallest later + for key in diagonals: + diagonals[key].sort(reverse=True) + + # Step 3: Fill back the sorted values + for i in range(m): + for j in range(n): + mat[i][j] = diagonals[i - j].pop() + + return mat diff --git a/tests/1001-1500/1329. sort-the-matrix-diagonally/sol.rb b/tests/1001-1500/1329. sort-the-matrix-diagonally/sol.rb new file mode 100644 index 00000000..897a006e --- /dev/null +++ b/tests/1001-1500/1329. sort-the-matrix-diagonally/sol.rb @@ -0,0 +1,22 @@ +# @param {Integer[][]} mat +# @return {Integer[][]} +def diagonal_sort(mat) + m, n = mat.length, mat[0].length + diagonals = Hash.new { |h, k| h[k] = [] } + + (0...m).each do |i| + (0...n).each do |j| + diagonals[i - j] << mat[i][j] + end + end + + diagonals.each_value { |v| v.sort! { |a, b| b <=> a } } + + (0...m).each do |i| + (0...n).each do |j| + mat[i][j] = diagonals[i - j].pop + end + end + + mat +end diff --git a/tests/1001-1500/1329. sort-the-matrix-diagonally/sol.rs b/tests/1001-1500/1329. sort-the-matrix-diagonally/sol.rs new file mode 100644 index 00000000..39077a29 --- /dev/null +++ b/tests/1001-1500/1329. sort-the-matrix-diagonally/sol.rs @@ -0,0 +1,30 @@ +use std::collections::HashMap; + +impl Solution { + pub fn diagonal_sort(mat: Vec>) -> Vec> { + let mut mat = mat; + let m = mat.len(); + let n = mat[0].len(); + let mut diagonals: HashMap> = HashMap::new(); + + for i in 0..m { + for j in 0..n { + let key = i as i32 - j as i32; + diagonals.entry(key).or_insert_with(Vec::new).push(mat[i][j]); + } + } + + for list in diagonals.values_mut() { + list.sort_by(|a, b| b.cmp(a)); + } + + for i in 0..m { + for j in 0..n { + let key = i as i32 - j as i32; + mat[i][j] = diagonals.get_mut(&key).unwrap().pop().unwrap(); + } + } + + mat + } +} diff --git a/tests/1001-1500/1329. sort-the-matrix-diagonally/sol.swift b/tests/1001-1500/1329. sort-the-matrix-diagonally/sol.swift new file mode 100644 index 00000000..bd158adc --- /dev/null +++ b/tests/1001-1500/1329. sort-the-matrix-diagonally/sol.swift @@ -0,0 +1,26 @@ +class Solution { + func diagonalSort(_ mat: [[Int]]) -> [[Int]] { + var mat = mat + let m = mat.count, n = mat[0].count + var diagonals = [Int: [Int]]() + + for i in 0..) + } + + for i in 0.. = new Map(); + + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + const key = i - j; + if (!diagonals.has(key)) { + diagonals.set(key, []); + } + diagonals.get(key)!.push(mat[i][j]); + } + } + + for (const list of diagonals.values()) { + list.sort((a, b) => b - a); + } + + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + const list = diagonals.get(i - j)!; + mat[i][j] = list.pop()!; + } + } + + return mat; +} diff --git a/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/manifest.yaml b/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/manifest.yaml new file mode 100644 index 00000000..25bd2e14 --- /dev/null +++ b/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/manifest.yaml @@ -0,0 +1,209 @@ +entry: + id: 1330 + title: "reverse-subarray-to-maximize-array-value" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().maxValueAfterReverse({nums})" + rust: "Solution::max_value_after_reverse({nums})" + python3: "Solution().maxValueAfterReverse({nums})" + python2: "Solution().maxValueAfterReverse({nums})" + ruby: "max_value_after_reverse({nums})" + java: "new Solution().maxValueAfterReverse({nums})" + csharp: "new Solution().MaxValueAfterReverse({nums})" + kotlin: "Solution().maxValueAfterReverse({nums})" + go: "maxValueAfterReverse({nums})" + dart: "Solution().maxValueAfterReverse({nums})" + swift: "Solution().maxValueAfterReverse({nums})" + typescript: "maxValueAfterReverse({nums})" +judge: + type: "exact" +limits: + time_ms: 1000 + memory_mb: 256 +oracle: + python3: + call: "Checker().maxValueAfterReverse(nums, {result})" + checker: | + class Checker: + def maxValueAfterReverse(self, nums, result): + if not isinstance(result, int) or len(nums) < 2: + return False + base = 0 + endpoint_gain = 0 + largest_lower = -10**18 + smallest_upper = 10**18 + for left, right in zip(nums, nums[1:]): + edge = abs(left - right) + base += edge + endpoint_gain = max( + endpoint_gain, + abs(nums[-1] - left) - edge, + abs(nums[0] - right) - edge, + ) + largest_lower = max(largest_lower, min(left, right)) + smallest_upper = min(smallest_upper, max(left, right)) + interior_gain = 2 * (largest_lower - smallest_upper) + return result == base + max(0, endpoint_gain, interior_gain) +seed: 1330 +tests: + - name: "example_one" + in: + nums: [2, 3, 1, 5, 4] + out: 10 + - name: "example_two" + in: + nums: [2, 4, 9, 24, 2, 1, 10] + out: 68 + - name: "two_equal" + in: + nums: [7, 7] + - name: "two_min_to_max" + in: + nums: [-100000, 100000] + - name: "two_max_to_min" + in: + nums: [100000, -100000] + - name: "all_equal" + in: + nums: [42, 42, 42, 42, 42] + - name: "strictly_increasing" + in: + nums: [-9, -4, 0, 3, 11] + - name: "strictly_decreasing" + in: + nums: [11, 3, 0, -4, -9] + - name: "three_element_peak" + in: + nums: [1, 10, 2] + - name: "three_element_valley" + in: + nums: [10, 1, 9] + - name: "alternating_small" + in: + nums: [0, 9, 1, 8, 2, 7] + - name: "alternating_extremes" + in: + nums: [-100000, 100000, -100000, 100000, -100000] + - name: "duplicate_plateaus" + in: + nums: [1, 1, 9, 9, 1, 1] + - name: "negative_only" + in: + nums: [-8, -1, -6, -2, -10, -3] + - name: "crosses_zero" + in: + nums: [-5, 0, 7, -2, 4] + - name: "endpoint_left_gain" + in: + nums: [20, 1, 2, 3, 19] + - name: "endpoint_right_gain" + in: + nums: [19, 3, 2, 1, 20] + - name: "interior_gain" + in: + nums: [8, 3, 12, 4, 6] + - name: "equal_edges" + in: + nums: [5, 1, 5, 1, 5] + - name: "long_flat_prefix" + in: + nums: [4, 4, 4, 10, 0, 4] + - name: "long_flat_suffix" + in: + nums: [4, 0, 10, 4, 4, 4] + - name: "repeated_low_high" + in: + nums: [2, 9, 2, 9, 2, 9, 2] + - name: "zigzag_with_duplicates" + in: + nums: [3, 8, 3, 8, 5, 5, 1] + - name: "large_positive_values" + in: + nums: [99999, 1, 99998, 2, 100000] + - name: "large_negative_values" + in: + nums: [-99999, -1, -99998, -2, -100000] + - name: "symmetric_walk" + in: + nums: [0, 6, 2, 8, 2, 6, 0] + - name: "mixed_seven" + in: + nums: [7, -2, 9, -1, 8, -3, 6] + - name: "small_steps_with_outlier" + in: + nums: [1, 2, 3, 100, 4, 5, 6] + - name: "outlier_at_start" + in: + nums: [100, 1, 2, 3, 4, 5] + - name: "outlier_at_end" + in: + nums: [5, 4, 3, 2, 1, 100] + - name: "two_runs" + in: + nums: [1, 2, 8, 9, 3, 4] + - name: "many_adjacent_duplicates" + in: + nums: [-3, -3, 4, 4, 4, -3, -3, 4] + - name: "near_boundary_values" + in: + nums: [-100000, -99999, 99999, 100000, -100000] + - name: "nontrivial_nine" + in: + nums: [13, -7, 4, 4, -12, 9, 0, 15, -3] + - name: "wide_range_ten" + in: + nums: [-50, 40, -30, 20, -10, 0, 10, -20, 30, -40] + - name: "generated_minimum_length" + seed: 101 + in: + nums: + gen: "array" + len: 2 + of: + gen: "int" + min: -100000 + max: 100000 + - name: "generated_short_random" + seed: 202 + in: + nums: + gen: "array" + len: 37 + of: + gen: "int" + min: -100000 + max: 100000 + - name: "generated_duplicate_dense" + seed: 303 + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: -3 + max: 3 + - name: "generated_maximum_length_full_range" + seed: 404 + in: + nums: + gen: "array" + len: 30000 + of: + gen: "int" + min: -100000 + max: 100000 + - name: "generated_near_maximum_length" + seed: 505 + in: + nums: + gen: "array" + len: 29999 + of: + gen: "int" + min: -100000 + max: 100000 diff --git a/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.cpp b/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.cpp new file mode 100644 index 00000000..6298a7e3 --- /dev/null +++ b/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int maxValueAfterReverse(vector& nums) { + if (nums.size() < 2) return 0; + + int maxMin = INT_MIN; + int minMin = INT_MAX; + int S = 0; + int boundary = INT_MIN; + + for (int i = 0; i < nums.size() - 1; i++) { + int a = nums[i]; + int b = nums[i + 1]; + int distance = abs(a - b); + boundary = max(boundary, max(abs(nums.back() - a), abs(nums[0] - b)) - distance); + S += distance; + minMin = min(max(a, b), minMin); + maxMin = max(min(a, b), maxMin); + } + + return S + max(2 * (maxMin - minMin), boundary); + } +}; diff --git a/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.cs b/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.cs new file mode 100644 index 00000000..27170af1 --- /dev/null +++ b/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.cs @@ -0,0 +1,22 @@ +public class Solution { + public int MaxValueAfterReverse(int[] nums) { + if (nums.Length < 2) return 0; + + int maxMin = int.MinValue; + int minMin = int.MaxValue; + int S = 0; + int boundary = int.MinValue; + + for (int i = 0; i < nums.Length - 1; i++) { + int a = nums[i]; + int b = nums[i + 1]; + int distance = Math.Abs(a - b); + boundary = Math.Max(boundary, Math.Max(Math.Abs(nums[nums.Length - 1] - a), Math.Abs(nums[0] - b)) - distance); + S += distance; + minMin = Math.Min(Math.Max(a, b), minMin); + maxMin = Math.Max(Math.Min(a, b), maxMin); + } + + return S + Math.Max(2 * (maxMin - minMin), boundary); + } +} diff --git a/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.dart b/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.dart new file mode 100644 index 00000000..adcf9efb --- /dev/null +++ b/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.dart @@ -0,0 +1,25 @@ +class Solution { + int maxValueAfterReverse(List nums) { + if (nums.length < 2) return 0; + + int maxMin = -1 << 63; + int minMin = 1 << 62; + int S = 0; + int boundary = -1 << 63; + + for (int i = 0; i < nums.length - 1; i++) { + int a = nums[i]; + int b = nums[i + 1]; + int distance = (a - b).abs(); + boundary = max(boundary, max((nums.last - a).abs(), (nums[0] - b).abs()) - distance); + S += distance; + minMin = min(max(a, b), minMin); + maxMin = max(min(a, b), maxMin); + } + + return S + max(2 * (maxMin - minMin), boundary); + } + + int max(int a, int b) => a > b ? a : b; + int min(int a, int b) => a < b ? a : b; +} diff --git a/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.go b/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.go new file mode 100644 index 00000000..0869a8be --- /dev/null +++ b/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.go @@ -0,0 +1,29 @@ +func maxValueAfterReverse(nums []int) int { + if len(nums) < 2 { + return 0 + } + + maxMin := -1 << 31 + minMin := 1<<31 - 1 + S := 0 + boundary := -1 << 31 + + for i := 0; i < len(nums)-1; i++ { + a := nums[i] + b := nums[i+1] + distance := abs(a - b) + boundary = max(boundary, max(abs(nums[len(nums)-1]-a), abs(nums[0]-b))-distance) + S += distance + minMin = min(max(a, b), minMin) + maxMin = max(min(a, b), maxMin) + } + + return S + max(2*(maxMin-minMin), boundary) +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} diff --git a/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.java b/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.java new file mode 100644 index 00000000..ea659b52 --- /dev/null +++ b/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.java @@ -0,0 +1,22 @@ +class Solution { + public int maxValueAfterReverse(int[] nums) { + if (nums.length < 2) return 0; + + int maxMin = Integer.MIN_VALUE; + int minMin = Integer.MAX_VALUE; + int S = 0; + int boundary = Integer.MIN_VALUE; + + for (int i = 0; i < nums.length - 1; i++) { + int a = nums[i]; + int b = nums[i + 1]; + int distance = Math.abs(a - b); + boundary = Math.max(boundary, Math.max(Math.abs(nums[nums.length - 1] - a), Math.abs(nums[0] - b)) - distance); + S += distance; + minMin = Math.min(Math.max(a, b), minMin); + maxMin = Math.max(Math.min(a, b), maxMin); + } + + return S + Math.max(2 * (maxMin - minMin), boundary); + } +} diff --git a/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.kt b/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.kt new file mode 100644 index 00000000..1276ac45 --- /dev/null +++ b/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.kt @@ -0,0 +1,22 @@ +class Solution { + fun maxValueAfterReverse(nums: IntArray): Int { + if (nums.size < 2) return 0 + + var maxMin = Int.MIN_VALUE + var minMin = Int.MAX_VALUE + var S = 0 + var boundary = Int.MIN_VALUE + + for (i in 0 until nums.size - 1) { + val a = nums[i] + val b = nums[i + 1] + val distance = Math.abs(a - b) + boundary = maxOf(boundary, maxOf(Math.abs(nums.last() - a), Math.abs(nums[0] - b)) - distance) + S += distance + minMin = minOf(maxOf(a, b), minMin) + maxMin = maxOf(minOf(a, b), maxMin) + } + + return S + maxOf(2 * (maxMin - minMin), boundary) + } +} diff --git a/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.py b/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.py new file mode 100644 index 00000000..d8b3c6c6 --- /dev/null +++ b/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.py @@ -0,0 +1,22 @@ +from typing import List +from math import inf + + +class Solution: + def maxValueAfterReverse(self, nums: List[int]) -> int: + if len(nums) < 2: + return 0 + + maxMin = -inf + minMin = inf + S = 0 + boundary = -inf + for a, b in zip(nums[:-1], nums[1:]): + distance = abs(a - b) + boundary = max( + boundary, max(abs(nums[-1] - a), abs(nums[0] - b)) - distance + ) + S += distance + minMin = min(max(a, b), minMin) + maxMin = max(min(a, b), maxMin) + return S + max(2 * (maxMin - minMin), boundary) diff --git a/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.py2 b/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.py2 new file mode 100644 index 00000000..05f03c28 --- /dev/null +++ b/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.py2 @@ -0,0 +1,20 @@ +class Solution(object): + def maxValueAfterReverse(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + if len(nums) < 2: + return 0 + + maxMin = -float('inf') + minMin = float('inf') + S = 0 + boundary = -float('inf') + for a, b in zip(nums[:-1], nums[1:]): + distance = abs(a - b) + boundary = max(boundary, max(abs(nums[-1] - a), abs(nums[0] - b)) - distance) + S += distance + minMin = min(max(a, b), minMin) + maxMin = max(min(a, b), maxMin) + return S + max(2 * (maxMin - minMin), boundary) diff --git a/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.rb b/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.rb new file mode 100644 index 00000000..1a07b457 --- /dev/null +++ b/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.rb @@ -0,0 +1,22 @@ +# @param {Integer[]} nums +# @return {Integer} +def max_value_after_reverse(nums) + return 0 if nums.length < 2 + + max_min = -Float::INFINITY + min_min = Float::INFINITY + s = 0 + boundary = -Float::INFINITY + + (0...nums.length-1).each do |i| + a = nums[i] + b = nums[i+1] + distance = (a - b).abs + boundary = [boundary, [(nums[-1] - a).abs, (nums[0] - b).abs].max - distance].max + s += distance + min_min = [[a, b].max, min_min].min + max_min = [[a, b].min, max_min].max + end + + s + [2 * (max_min - min_min), boundary].max +end diff --git a/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.rs b/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.rs new file mode 100644 index 00000000..b173e4c2 --- /dev/null +++ b/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.rs @@ -0,0 +1,26 @@ +impl Solution { + pub fn max_value_after_reverse(nums: Vec) -> i32 { + if nums.len() < 2 { + return 0; + } + + let mut max_min = i32::MIN; + let mut min_min = i32::MAX; + let mut s = 0; + let mut boundary = i32::MIN; + + for i in 0..nums.len() - 1 { + let a = nums[i]; + let b = nums[i + 1]; + let distance = (a - b).abs(); + boundary = boundary.max( + ((nums[nums.len() - 1] - a).abs()).max((nums[0] - b).abs()) - distance + ); + s += distance; + min_min = min_min.min(a.max(b)); + max_min = max_min.max(a.min(b)); + } + + s + (2 * (max_min - min_min)).max(boundary) + } +} diff --git a/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.swift b/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.swift new file mode 100644 index 00000000..9aac3b07 --- /dev/null +++ b/tests/1001-1500/1330. reverse-subarray-to-maximize-array-value/sol.swift @@ -0,0 +1,24 @@ +class Solution { + func maxValueAfterReverse(_ nums: [Int]) -> Int { + if nums.count < 2 { + return 0 + } + + var maxMin = Int.min + var minMin = Int.max + var S = 0 + var boundary = Int.min + + for i in 0.. arrayRankTransform(vector& arr) { + vector s = arr; + sort(s.begin(), s.end()); + vector unique; + for (int x : s) { + if (unique.empty() || unique.back() != x) { + unique.push_back(x); + } + } + for (int i = 0; i < arr.size(); i++) { + arr[i] = bisect_left(unique, arr[i]) + 1; + } + return arr; + } + +private: + int bisect_left(vector& a, int x) { + int lo = 0, hi = a.size(); + while (lo < hi) { + int mid = (lo + hi) / 2; + if (a[mid] < x) { + lo = mid + 1; + } else { + hi = mid; + } + } + return lo; + } +}; diff --git a/tests/1001-1500/1331. rank-transform-of-an-array/sol.cs b/tests/1001-1500/1331. rank-transform-of-an-array/sol.cs new file mode 100644 index 00000000..bb085e6a --- /dev/null +++ b/tests/1001-1500/1331. rank-transform-of-an-array/sol.cs @@ -0,0 +1,29 @@ +public class Solution { + public int[] ArrayRankTransform(int[] arr) { + int[] s = (int[])arr.Clone(); + Array.Sort(s); + List unique = new List(); + foreach (int x in s) { + if (unique.Count == 0 || unique[unique.Count - 1] != x) { + unique.Add(x); + } + } + for (int i = 0; i < arr.Length; i++) { + arr[i] = BisectLeft(unique, arr[i]) + 1; + } + return arr; + } + + private int BisectLeft(List a, int x) { + int lo = 0, hi = a.Count; + while (lo < hi) { + int mid = (lo + hi) / 2; + if (a[mid] < x) { + lo = mid + 1; + } else { + hi = mid; + } + } + return lo; + } +} diff --git a/tests/1001-1500/1331. rank-transform-of-an-array/sol.dart b/tests/1001-1500/1331. rank-transform-of-an-array/sol.dart new file mode 100644 index 00000000..02bbdc7c --- /dev/null +++ b/tests/1001-1500/1331. rank-transform-of-an-array/sol.dart @@ -0,0 +1,28 @@ +class Solution { + List arrayRankTransform(List arr) { + List s = List.from(arr)..sort(); + List unique = []; + for (int x in s) { + if (unique.isEmpty || unique.last != x) { + unique.add(x); + } + } + for (int i = 0; i < arr.length; i++) { + arr[i] = bisectLeft(unique, arr[i]) + 1; + } + return arr; + } + + int bisectLeft(List a, int x) { + int lo = 0, hi = a.length; + while (lo < hi) { + int mid = (lo + hi) ~/ 2; + if (a[mid] < x) { + lo = mid + 1; + } else { + hi = mid; + } + } + return lo; + } +} diff --git a/tests/1001-1500/1331. rank-transform-of-an-array/sol.go b/tests/1001-1500/1331. rank-transform-of-an-array/sol.go new file mode 100644 index 00000000..bea9fda6 --- /dev/null +++ b/tests/1001-1500/1331. rank-transform-of-an-array/sol.go @@ -0,0 +1,28 @@ +func arrayRankTransform(arr []int) []int { + s := make([]int, len(arr)) + copy(s, arr) + sort.Ints(s) + unique := []int{} + for _, x := range s { + if len(unique) == 0 || unique[len(unique)-1] != x { + unique = append(unique, x) + } + } + for i := 0; i < len(arr); i++ { + arr[i] = bisectLeft(unique, arr[i]) + 1 + } + return arr +} + +func bisectLeft(a []int, x int) int { + lo, hi := 0, len(a) + for lo < hi { + mid := (lo + hi) / 2 + if a[mid] < x { + lo = mid + 1 + } else { + hi = mid + } + } + return lo +} diff --git a/tests/1001-1500/1331. rank-transform-of-an-array/sol.java b/tests/1001-1500/1331. rank-transform-of-an-array/sol.java new file mode 100644 index 00000000..f455d44c --- /dev/null +++ b/tests/1001-1500/1331. rank-transform-of-an-array/sol.java @@ -0,0 +1,30 @@ +class Solution { + public int[] arrayRankTransform(int[] arr) { + int[] s = arr.clone(); + Arrays.sort(s); + List uniqueList = new ArrayList<>(); + for (int x : s) { + if (uniqueList.isEmpty() || uniqueList.get(uniqueList.size() - 1) != x) { + uniqueList.add(x); + } + } + int[] unique = uniqueList.stream().mapToInt(i -> i).toArray(); + for (int i = 0; i < arr.length; i++) { + arr[i] = bisectLeft(unique, arr[i]) + 1; + } + return arr; + } + + private int bisectLeft(int[] a, int x) { + int lo = 0, hi = a.length; + while (lo < hi) { + int mid = (lo + hi) / 2; + if (a[mid] < x) { + lo = mid + 1; + } else { + hi = mid; + } + } + return lo; + } +} diff --git a/tests/1001-1500/1331. rank-transform-of-an-array/sol.kt b/tests/1001-1500/1331. rank-transform-of-an-array/sol.kt new file mode 100644 index 00000000..da556a0e --- /dev/null +++ b/tests/1001-1500/1331. rank-transform-of-an-array/sol.kt @@ -0,0 +1,29 @@ +class Solution { + fun arrayRankTransform(arr: IntArray): IntArray { + val s = arr.sorted() + val unique = mutableListOf() + for (x in s) { + if (unique.isEmpty() || unique.last() != x) { + unique.add(x) + } + } + for (i in arr.indices) { + arr[i] = bisectLeft(unique, arr[i]) + 1 + } + return arr + } + + private fun bisectLeft(a: List, x: Int): Int { + var lo = 0 + var hi = a.size + while (lo < hi) { + val mid = (lo + hi) / 2 + if (a[mid] < x) { + lo = mid + 1 + } else { + hi = mid + } + } + return lo + } +} diff --git a/tests/1001-1500/1331. rank-transform-of-an-array/sol.py b/tests/1001-1500/1331. rank-transform-of-an-array/sol.py new file mode 100644 index 00000000..ca214650 --- /dev/null +++ b/tests/1001-1500/1331. rank-transform-of-an-array/sol.py @@ -0,0 +1,16 @@ +from bisect import bisect_left + + +class Solution: + def arrayRankTransform(self, arr: list[int]) -> list[int]: + s = sorted(arr) + unique = [] + + for x in s: + if not unique or unique[-1] != x: + unique.append(x) + + for i in range(len(arr)): + arr[i] = bisect_left(unique, arr[i]) + 1 + + return arr diff --git a/tests/1001-1500/1331. rank-transform-of-an-array/sol.py2 b/tests/1001-1500/1331. rank-transform-of-an-array/sol.py2 new file mode 100644 index 00000000..796d3d0c --- /dev/null +++ b/tests/1001-1500/1331. rank-transform-of-an-array/sol.py2 @@ -0,0 +1,24 @@ +class Solution(object): + def arrayRankTransform(self, arr): + """ + :type arr: List[int] + :rtype: List[int] + """ + s = sorted(arr) + unique = [] + for x in s: + if not unique or unique[-1] != x: + unique.append(x) + for i in range(len(arr)): + arr[i] = self._bisect_left(unique, arr[i]) + 1 + return arr + + def _bisect_left(self, a, x): + lo, hi = 0, len(a) + while lo < hi: + mid = (lo + hi) // 2 + if a[mid] < x: + lo = mid + 1 + else: + hi = mid + return lo diff --git a/tests/1001-1500/1331. rank-transform-of-an-array/sol.rb b/tests/1001-1500/1331. rank-transform-of-an-array/sol.rb new file mode 100644 index 00000000..22384cac --- /dev/null +++ b/tests/1001-1500/1331. rank-transform-of-an-array/sol.rb @@ -0,0 +1,29 @@ +# @param {Integer[]} arr +# @return {Integer[]} +def array_rank_transform(arr) + s = arr.sort + unique = [] + s.each do |x| + if unique.empty? || unique.last != x + unique << x + end + end + arr.map! do |x| + bisect_left(unique, x) + 1 + end + arr +end + +def bisect_left(a, x) + lo = 0 + hi = a.length + while lo < hi + mid = (lo + hi) / 2 + if a[mid] < x + lo = mid + 1 + else + hi = mid + end + end + lo +end diff --git a/tests/1001-1500/1331. rank-transform-of-an-array/sol.rs b/tests/1001-1500/1331. rank-transform-of-an-array/sol.rs new file mode 100644 index 00000000..11f9be4f --- /dev/null +++ b/tests/1001-1500/1331. rank-transform-of-an-array/sol.rs @@ -0,0 +1,27 @@ +impl Solution { + pub fn array_rank_transform(arr: Vec) -> Vec { + let mut s = arr.clone(); + s.sort(); + let mut unique = Vec::new(); + for &x in &s { + if unique.is_empty() || *unique.last().unwrap() != x { + unique.push(x); + } + } + arr.iter().map(|&x| Solution::bisect_left(&unique, x) as i32 + 1).collect() + } + + fn bisect_left(a: &Vec, x: i32) -> usize { + let mut lo = 0; + let mut hi = a.len(); + while lo < hi { + let mid = (lo + hi) / 2; + if a[mid] < x { + lo = mid + 1; + } else { + hi = mid; + } + } + lo + } +} diff --git a/tests/1001-1500/1331. rank-transform-of-an-array/sol.swift b/tests/1001-1500/1331. rank-transform-of-an-array/sol.swift new file mode 100644 index 00000000..9e020779 --- /dev/null +++ b/tests/1001-1500/1331. rank-transform-of-an-array/sol.swift @@ -0,0 +1,29 @@ +class Solution { + func arrayRankTransform(_ arr: [Int]) -> [Int] { + let s = arr.sorted() + var unique = [Int]() + for x in s { + if unique.isEmpty || unique.last! != x { + unique.append(x) + } + } + var result = arr + for i in 0.. Int { + var lo = 0, hi = a.count + while lo < hi { + let mid = (lo + hi) / 2 + if a[mid] < x { + lo = mid + 1 + } else { + hi = mid + } + } + return lo + } +} diff --git a/tests/1001-1500/1331. rank-transform-of-an-array/sol.ts b/tests/1001-1500/1331. rank-transform-of-an-array/sol.ts new file mode 100644 index 00000000..06f1e9c5 --- /dev/null +++ b/tests/1001-1500/1331. rank-transform-of-an-array/sol.ts @@ -0,0 +1,27 @@ +function arrayRankTransform(arr: number[]): number[] { + const s = [...arr].sort((a, b) => a - b); + const unique: number[] = []; + for (const x of s) { + if (unique.length === 0 || unique[unique.length - 1] !== x) { + unique.push(x); + } + } + for (let i = 0; i < arr.length; i++) { + arr[i] = bisectLeft(unique, arr[i]) + 1; + } + return arr; +} + +function bisectLeft(a: number[], x: number): number { + let lo = 0, + hi = a.length; + while (lo < hi) { + const mid = (lo + hi) >> 1; + if (a[mid] < x) { + lo = mid + 1; + } else { + hi = mid; + } + } + return lo; +} diff --git a/tests/1001-1500/1332. remove-palindromic-subsequences/manifest.yaml b/tests/1001-1500/1332. remove-palindromic-subsequences/manifest.yaml new file mode 100644 index 00000000..1c979c62 --- /dev/null +++ b/tests/1001-1500/1332. remove-palindromic-subsequences/manifest.yaml @@ -0,0 +1,198 @@ +entry: + id: 1332 + title: remove-palindromic-subsequences + params: + s: + type: string + call: + cpp: "Solution().removePalindromeSub({s})" + rust: "Solution::remove_palindrome_sub({s})" + python3: "Solution().removePalindromeSub({s})" + python2: "Solution().removePalindromeSub({s})" + ruby: "remove_palindrome_sub({s})" + java: "new Solution().removePalindromeSub({s})" + csharp: "new Solution().RemovePalindromeSub({s})" + kotlin: "Solution().removePalindromeSub({s})" + go: "removePalindromeSub({s})" + dart: "Solution().removePalindromeSub({s})" + swift: "Solution().removePalindromeSub({s})" + typescript: "removePalindromeSub({s})" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().removePalindromeSub(s, {result})" + checker: | + class Checker: + def removePalindromeSub(self, s, result): + expected = 1 if s == s[::-1] else 2 + return type(result) is int and result == expected +seed: 1332 +tests: + - name: example-palindrome + in: + s: ababa + out: 1 + - name: example-non-palindrome + in: + s: abb + out: 2 + - name: example-subsequence-removal + in: + s: baabb + out: 2 + - name: single-a + in: + s: a + out: 1 + - name: single-b + in: + s: b + out: 1 + - name: equal-as + in: + s: aa + out: 1 + - name: equal-bs + in: + s: bb + out: 1 + - name: ordered-ab + in: + s: ab + out: 2 + - name: ordered-ba + in: + s: ba + out: 2 + - name: odd-center-a + in: + s: aba + out: 1 + - name: odd-center-b + in: + s: bab + out: 1 + - name: even-palindrome + in: + s: abba + out: 1 + - name: short-alternating-even + in: + s: abab + out: 2 + - name: all-as + in: + s: aaaaaa + out: 1 + - name: all-bs + in: + s: bbbbbb + out: 1 + - name: alternating-odd-palindrome + in: + s: ababababa + out: 1 + - name: alternating-even-non-palindrome + in: + s: ababababab + out: 2 + - name: nested-a-center + in: + s: aaabaaa + out: 1 + - name: nested-b-center + in: + s: bbbabbb + out: 1 + - name: symmetric-runs + in: + s: aabbbaa + out: 1 + - name: symmetric-inner-run + in: + s: abbbba + out: 1 + - name: two-character-center + in: + s: aabbaa + out: 1 + - name: unequal-tail + in: + s: aaabb + out: 2 + - name: longer-palindrome + in: + s: ababbaba + out: 1 + - name: longer-non-palindrome + in: + s: aabbabab + out: 2 + - name: symmetric-blocks + in: + s: aaabbbaaa + out: 1 + - name: asymmetric-blocks + in: + s: aaabbbaab + out: 2 + - name: one-b-in-as + in: + s: aaaaabaaaaa + out: 1 + - name: one-a-in-bs + in: + s: bbbbbabbbbb + out: 1 + - name: leading-run-non-palindrome + in: + s: bbaaabbb + out: 2 + - name: leading-run-palindrome + in: + s: bbaaaabb + out: 1 + - name: repeated-non-palindrome + in: + s: aabbaabbaabb + out: 2 + - name: wide-middle-palindrome + in: + s: aabbbbbbaa + out: 1 + - name: near-palindrome-left-change + in: + s: aababbaa + out: 2 + - name: near-palindrome-right-change + in: + s: aababbba + out: 2 + - name: mixed-odd-palindrome + in: + s: baababaab + out: 1 + - name: mixed-odd-non-palindrome + in: + s: baabababb + out: 2 + - name: matching-ends-non-palindrome + in: + s: abbbaabbb + out: 2 + - name: max-length-all-a + in: + s: + gen: str + len: 1000 + alphabet: a + - name: max-length-all-b + in: + s: + gen: str + len: 1000 + alphabet: b diff --git a/tests/1001-1500/1332. remove-palindromic-subsequences/sol.cpp b/tests/1001-1500/1332. remove-palindromic-subsequences/sol.cpp new file mode 100644 index 00000000..d5c79c22 --- /dev/null +++ b/tests/1001-1500/1332. remove-palindromic-subsequences/sol.cpp @@ -0,0 +1,8 @@ +class Solution { +public: + int removePalindromeSub(string s) { + string rev = s; + reverse(rev.begin(), rev.end()); + return s == rev ? 1 : 2; + } +}; diff --git a/tests/1001-1500/1332. remove-palindromic-subsequences/sol.cs b/tests/1001-1500/1332. remove-palindromic-subsequences/sol.cs new file mode 100644 index 00000000..931afe13 --- /dev/null +++ b/tests/1001-1500/1332. remove-palindromic-subsequences/sol.cs @@ -0,0 +1,7 @@ +public class Solution { + public int RemovePalindromeSub(string s) { + char[] arr = s.ToCharArray(); + Array.Reverse(arr); + return s == new string(arr) ? 1 : 2; + } +} diff --git a/tests/1001-1500/1332. remove-palindromic-subsequences/sol.dart b/tests/1001-1500/1332. remove-palindromic-subsequences/sol.dart new file mode 100644 index 00000000..9a5b6b01 --- /dev/null +++ b/tests/1001-1500/1332. remove-palindromic-subsequences/sol.dart @@ -0,0 +1,5 @@ +class Solution { + int removePalindromeSub(String s) { + return s == s.split('').reversed.join('') ? 1 : 2; + } +} diff --git a/tests/1001-1500/1332. remove-palindromic-subsequences/sol.go b/tests/1001-1500/1332. remove-palindromic-subsequences/sol.go new file mode 100644 index 00000000..2536cdb5 --- /dev/null +++ b/tests/1001-1500/1332. remove-palindromic-subsequences/sol.go @@ -0,0 +1,8 @@ +func removePalindromeSub(s string) int { + for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { + if s[i] != s[j] { + return 2 + } + } + return 1 +} diff --git a/tests/1001-1500/1332. remove-palindromic-subsequences/sol.java b/tests/1001-1500/1332. remove-palindromic-subsequences/sol.java new file mode 100644 index 00000000..0c821e06 --- /dev/null +++ b/tests/1001-1500/1332. remove-palindromic-subsequences/sol.java @@ -0,0 +1,6 @@ +class Solution { + public int removePalindromeSub(String s) { + String reversed = new StringBuilder(s).reverse().toString(); + return s.equals(reversed) ? 1 : 2; + } +} diff --git a/tests/1001-1500/1332. remove-palindromic-subsequences/sol.kt b/tests/1001-1500/1332. remove-palindromic-subsequences/sol.kt new file mode 100644 index 00000000..f819fd7b --- /dev/null +++ b/tests/1001-1500/1332. remove-palindromic-subsequences/sol.kt @@ -0,0 +1,5 @@ +class Solution { + fun removePalindromeSub(s: String): Int { + return if (s == s.reversed()) 1 else 2 + } +} diff --git a/tests/1001-1500/1332. remove-palindromic-subsequences/sol.py b/tests/1001-1500/1332. remove-palindromic-subsequences/sol.py new file mode 100644 index 00000000..c44f232b --- /dev/null +++ b/tests/1001-1500/1332. remove-palindromic-subsequences/sol.py @@ -0,0 +1,3 @@ +class Solution(object): + def removePalindromeSub(self, s): + return 1 if s == s[::-1] else 2 diff --git a/tests/1001-1500/1332. remove-palindromic-subsequences/sol.py2 b/tests/1001-1500/1332. remove-palindromic-subsequences/sol.py2 new file mode 100644 index 00000000..c44f232b --- /dev/null +++ b/tests/1001-1500/1332. remove-palindromic-subsequences/sol.py2 @@ -0,0 +1,3 @@ +class Solution(object): + def removePalindromeSub(self, s): + return 1 if s == s[::-1] else 2 diff --git a/tests/1001-1500/1332. remove-palindromic-subsequences/sol.rb b/tests/1001-1500/1332. remove-palindromic-subsequences/sol.rb new file mode 100644 index 00000000..7405a5a7 --- /dev/null +++ b/tests/1001-1500/1332. remove-palindromic-subsequences/sol.rb @@ -0,0 +1,5 @@ +# @param {String} s +# @return {Integer} +def remove_palindrome_sub(s) + s == s.reverse ? 1 : 2 +end diff --git a/tests/1001-1500/1332. remove-palindromic-subsequences/sol.rs b/tests/1001-1500/1332. remove-palindromic-subsequences/sol.rs new file mode 100644 index 00000000..2c2ee17c --- /dev/null +++ b/tests/1001-1500/1332. remove-palindromic-subsequences/sol.rs @@ -0,0 +1,6 @@ +impl Solution { + pub fn remove_palindrome_sub(s: String) -> i32 { + let rev: String = s.chars().rev().collect(); + if s == rev { 1 } else { 2 } + } +} diff --git a/tests/1001-1500/1332. remove-palindromic-subsequences/sol.swift b/tests/1001-1500/1332. remove-palindromic-subsequences/sol.swift new file mode 100644 index 00000000..4205c0df --- /dev/null +++ b/tests/1001-1500/1332. remove-palindromic-subsequences/sol.swift @@ -0,0 +1,5 @@ +class Solution { + func removePalindromeSub(_ s: String) -> Int { + return String(s.reversed()) == s ? 1 : 2 + } +} diff --git a/tests/1001-1500/1332. remove-palindromic-subsequences/sol.ts b/tests/1001-1500/1332. remove-palindromic-subsequences/sol.ts new file mode 100644 index 00000000..d5f581ea --- /dev/null +++ b/tests/1001-1500/1332. remove-palindromic-subsequences/sol.ts @@ -0,0 +1,3 @@ +function removePalindromeSub(s: string): number { + return s === s.split("").reverse().join("") ? 1 : 2; +} diff --git a/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/manifest.yaml b/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/manifest.yaml new file mode 100644 index 00000000..ebe07f38 --- /dev/null +++ b/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/manifest.yaml @@ -0,0 +1,431 @@ +entry: + id: 1333 + title: filter-restaurants-by-vegan-friendly-price-and-distance + params: + restaurants: + type: array + items: + type: array + items: + type: int + veganFriendly: + type: int + maxPrice: + type: int + maxDistance: + type: int + call: + cpp: "Solution().filterRestaurants({restaurants}, {veganFriendly}, {maxPrice}, {maxDistance})" + rust: "Solution::filter_restaurants({restaurants}, {veganFriendly}, {maxPrice}, {maxDistance})" + python3: "Solution().filterRestaurants({restaurants}, {veganFriendly}, {maxPrice}, {maxDistance})" + python2: "Solution().filterRestaurants({restaurants}, {veganFriendly}, {maxPrice}, {maxDistance})" + ruby: "filter_restaurants({restaurants}, {veganFriendly}, {maxPrice}, {maxDistance})" + java: "new Solution().filterRestaurants({restaurants}, {veganFriendly}, {maxPrice}, {maxDistance})" + csharp: "new Solution().FilterRestaurants({restaurants}, {veganFriendly}, {maxPrice}, {maxDistance})" + kotlin: "Solution().filterRestaurants({restaurants}, {veganFriendly}, {maxPrice}, {maxDistance})" + go: "filterRestaurants({restaurants}, {veganFriendly}, {maxPrice}, {maxDistance})" + dart: "Solution().filterRestaurants({restaurants}, {veganFriendly}, {maxPrice}, {maxDistance})" + swift: "Solution().filterRestaurants({restaurants}, {veganFriendly}, {maxPrice}, {maxDistance})" + typescript: "filterRestaurants({restaurants}, {veganFriendly}, {maxPrice}, {maxDistance})" +judge: + type: exact +limits: + time_ms: 1000 + memory_mb: 256 +oracle: + python3: + call: "Checker().filterRestaurants(restaurants, veganFriendly, maxPrice, maxDistance, {result})" + checker: | + class Checker: + def filterRestaurants(self, restaurants, veganFriendly, maxPrice, maxDistance, result): + if not isinstance(restaurants, list) or not 1 <= len(restaurants) <= 10000: + return False + if veganFriendly not in (0, 1) or not isinstance(maxPrice, int) or not isinstance(maxDistance, int): + return False + if not isinstance(result, list): + return False + rows = [] + ids = set() + for row in restaurants: + if not isinstance(row, list) or len(row) != 5: + return False + rid, rating, vegan, price, distance = row + if rid in ids or not all(isinstance(value, int) and not isinstance(value, bool) for value in row): + return False + ids.add(rid) + if vegan not in (0, 1): + return False + if veganFriendly == 0 or vegan == 1: + if price <= maxPrice and distance <= maxDistance: + rows.append((rating, rid)) + expected = [rid for rating, rid in sorted(rows, reverse=True)] + return result == expected +seed: 1333 +tests: + - name: example_one + in: + restaurants: + - [1, 4, 1, 40, 10] + - [2, 8, 0, 50, 5] + - [3, 8, 1, 30, 4] + - [4, 10, 0, 10, 3] + - [5, 1, 1, 15, 1] + veganFriendly: 1 + maxPrice: 50 + maxDistance: 10 + - name: example_two + in: + restaurants: + - [1, 4, 1, 40, 10] + - [2, 8, 0, 50, 5] + - [3, 8, 1, 30, 4] + - [4, 10, 0, 10, 3] + - [5, 1, 1, 15, 1] + veganFriendly: 0 + maxPrice: 50 + maxDistance: 10 + - name: example_three + in: + restaurants: + - [1, 4, 1, 40, 10] + - [2, 8, 0, 50, 5] + - [3, 8, 1, 30, 4] + - [4, 10, 0, 10, 3] + - [5, 1, 1, 15, 1] + veganFriendly: 0 + maxPrice: 30 + maxDistance: 3 + - name: single_match + in: + restaurants: + - [9, 100, 1, 20, 2] + veganFriendly: 1 + maxPrice: 20 + maxDistance: 2 + - name: single_rejected + in: + restaurants: + - [9, 100, 0, 20, 2] + veganFriendly: 1 + maxPrice: 20 + maxDistance: 2 + - name: no_vegan_filter + in: + restaurants: + - [1, 5, 0, 10, 1] + - [2, 4, 1, 10, 1] + veganFriendly: 0 + maxPrice: 10 + maxDistance: 1 + - name: price_boundary + in: + restaurants: + - [1, 5, 1, 10, 1] + - [2, 9, 1, 11, 1] + veganFriendly: 1 + maxPrice: 10 + maxDistance: 1 + - name: distance_boundary + in: + restaurants: + - [1, 5, 1, 10, 10] + - [2, 9, 1, 10, 11] + veganFriendly: 1 + maxPrice: 10 + maxDistance: 10 + - name: rating_order + in: + restaurants: + - [1, 3, 1, 1, 1] + - [2, 9, 1, 1, 1] + - [3, 6, 1, 1, 1] + veganFriendly: 1 + maxPrice: 1 + maxDistance: 1 + - name: rating_tie_id_order + in: + restaurants: + - [10, 8, 1, 10, 10] + - [4, 8, 1, 10, 10] + - [7, 8, 1, 10, 10] + veganFriendly: 1 + maxPrice: 10 + maxDistance: 10 + - name: empty_result_price + in: + restaurants: + - [1, 5, 1, 100, 1] + - [2, 6, 0, 100, 1] + veganFriendly: 0 + maxPrice: 99 + maxDistance: 10 + - name: empty_result_distance + in: + restaurants: + - [1, 5, 1, 1, 100] + veganFriendly: 1 + maxPrice: 10 + maxDistance: 99 + - name: mixed_filters + in: + restaurants: + - [1, 10, 1, 5, 5] + - [2, 20, 0, 5, 5] + - [3, 30, 1, 15, 5] + - [4, 40, 1, 5, 15] + veganFriendly: 1 + maxPrice: 10 + maxDistance: 10 + - name: all_match + in: + restaurants: + - [1, 1, 0, 1, 1] + - [2, 2, 1, 2, 2] + - [3, 3, 0, 3, 3] + veganFriendly: 0 + maxPrice: 3 + maxDistance: 3 + - name: all_nonvegan + in: + restaurants: + - [1, 10, 0, 1, 1] + - [2, 20, 0, 1, 1] + veganFriendly: 1 + maxPrice: 10 + maxDistance: 10 + - name: large_ids + in: + restaurants: + - [100000, 5, 1, 5, 5] + - [99999, 5, 1, 5, 5] + veganFriendly: 1 + maxPrice: 5 + maxDistance: 5 + - name: zero_thresholds + in: + restaurants: + - [1, 5, 1, 1, 1] + - [2, 6, 1, 2, 1] + veganFriendly: 1 + maxPrice: 1 + maxDistance: 1 + - name: price_distance_cross + in: + restaurants: + - [1, 5, 1, 1, 10] + - [2, 6, 1, 10, 1] + - [3, 7, 1, 5, 5] + veganFriendly: 1 + maxPrice: 5 + maxDistance: 5 + - name: five_candidates + in: + restaurants: + - [1, 1, 1, 1, 1] + - [2, 2, 0, 1, 1] + - [3, 3, 1, 2, 2] + - [4, 4, 0, 2, 2] + - [5, 5, 1, 3, 3] + veganFriendly: 0 + maxPrice: 2 + maxDistance: 2 + - name: descending_input + in: + restaurants: + - [5, 1, 1, 1, 1] + - [4, 2, 1, 1, 1] + - [3, 3, 1, 1, 1] + - [2, 4, 1, 1, 1] + veganFriendly: 1 + maxPrice: 1 + maxDistance: 1 + - name: interleaved_vegan + in: + restaurants: + - [1, 9, 0, 2, 2] + - [2, 8, 1, 2, 2] + - [3, 7, 0, 2, 2] + - [4, 6, 1, 2, 2] + veganFriendly: 1 + maxPrice: 2 + maxDistance: 2 + - name: max_bounds + in: + restaurants: + - [1, 100000, 1, 100000, 100000] + - [2, 99999, 0, 100000, 100000] + veganFriendly: 0 + maxPrice: 100000 + maxDistance: 100000 + - name: one_filter_each + in: + restaurants: + - [1, 4, 1, 4, 9] + - [2, 5, 1, 9, 4] + - [3, 6, 1, 4, 4] + veganFriendly: 1 + maxPrice: 4 + maxDistance: 4 + - name: equal_everything_except_id + in: + restaurants: + - [3, 10, 1, 5, 5] + - [1, 10, 1, 5, 5] + - [2, 10, 1, 5, 5] + veganFriendly: 1 + maxPrice: 5 + maxDistance: 5 + - name: multiple_rejections + in: + restaurants: + - [1, 10, 0, 100, 100] + - [2, 9, 1, 100, 1] + - [3, 8, 1, 1, 100] + - [4, 7, 1, 1, 1] + veganFriendly: 1 + maxPrice: 10 + maxDistance: 10 + - name: small_ratings + in: + restaurants: + - [1, 1, 1, 1, 1] + - [2, 2, 1, 1, 1] + veganFriendly: 1 + maxPrice: 1 + maxDistance: 1 + - name: seven_rows + in: + restaurants: + - [1, 7, 1, 7, 7] + - [2, 3, 0, 7, 7] + - [3, 9, 1, 8, 7] + - [4, 8, 1, 7, 8] + - [5, 6, 0, 6, 6] + - [6, 5, 1, 5, 5] + - [7, 4, 1, 4, 4] + veganFriendly: 1 + maxPrice: 7 + maxDistance: 7 + - name: exact_all_limits + in: + restaurants: + - [1, 50, 1, 50, 50] + - [2, 60, 1, 49, 51] + veganFriendly: 1 + maxPrice: 50 + maxDistance: 50 + - name: final_mixed + in: + restaurants: + - [11, 90, 1, 20, 20] + - [12, 90, 1, 20, 20] + - [13, 91, 0, 20, 20] + - [14, 89, 1, 19, 19] + veganFriendly: 1 + maxPrice: 20 + maxDistance: 20 + - name: vegan_zero_boundary + in: + restaurants: + - [1, 10, 0, 1, 1] + - [2, 9, 1, 1, 1] + veganFriendly: 0 + maxPrice: 1 + maxDistance: 1 + - name: rating_tie_after_filters + in: + restaurants: + - [8, 12, 1, 5, 5] + - [4, 12, 1, 5, 6] + - [9, 13, 0, 5, 5] + veganFriendly: 1 + maxPrice: 5 + maxDistance: 5 + - name: only_distance_match + in: + restaurants: + - [1, 4, 1, 10, 2] + - [2, 5, 1, 2, 10] + - [3, 6, 1, 3, 3] + veganFriendly: 1 + maxPrice: 3 + maxDistance: 3 + - name: only_price_match + in: + restaurants: + - [1, 4, 1, 2, 10] + - [2, 5, 1, 10, 2] + - [3, 6, 1, 3, 3] + veganFriendly: 1 + maxPrice: 3 + maxDistance: 3 + - name: all_equal_ratings + in: + restaurants: + - [20, 7, 0, 2, 2] + - [10, 7, 0, 2, 2] + - [30, 7, 0, 2, 2] + - [5, 7, 0, 2, 2] + veganFriendly: 0 + maxPrice: 2 + maxDistance: 2 + - name: strict_both_limits + in: + restaurants: + - [1, 100, 1, 9, 9] + - [2, 90, 1, 10, 10] + - [3, 80, 1, 11, 9] + veganFriendly: 1 + maxPrice: 10 + maxDistance: 10 + - name: duplicate_ratings_with_exclusions + in: + restaurants: + - [101, 50, 1, 25, 25] + - [102, 50, 1, 26, 25] + - [103, 50, 1, 25, 26] + - [104, 50, 1, 25, 25] + veganFriendly: 1 + maxPrice: 25 + maxDistance: 25 + - name: nonvegan_highest_rating_allowed + in: + restaurants: + - [1, 99, 0, 1, 100000] + - [2, 98, 1, 100000, 1] + - [3, 97, 1, 100000, 100000] + veganFriendly: 0 + maxPrice: 100000 + maxDistance: 100000 + - name: max_id_tie_break + in: + restaurants: + - [100000, 100000, 1, 100000, 100000] + - [1, 100000, 1, 1, 1] + - [50000, 99999, 1, 1, 1] + veganFriendly: 1 + maxPrice: 100000 + maxDistance: 100000 + - name: filters_leave_middle_rows + in: + restaurants: + - [1, 100, 1, 11, 10] + - [2, 90, 1, 10, 10] + - [3, 80, 0, 1, 1] + - [4, 70, 1, 1, 11] + - [5, 60, 1, 9, 9] + veganFriendly: 1 + maxPrice: 10 + maxDistance: 10 + - name: unordered_input_multiple_ties + in: + restaurants: + - [44, 3, 0, 4, 4] + - [11, 8, 1, 4, 4] + - [77, 8, 0, 4, 4] + - [22, 8, 1, 4, 4] + - [55, 9, 1, 4, 4] + - [33, 9, 0, 4, 4] + veganFriendly: 0 + maxPrice: 4 + maxDistance: 4 diff --git a/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.cpp b/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.cpp new file mode 100644 index 00000000..5c8390a3 --- /dev/null +++ b/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + vector filterRestaurants(vector>& restaurants, int veganFriendly, int maxPrice, int maxDistance) { + vector> restaurantsFiltered; + + for (const auto& restaurant : restaurants) { + if (veganFriendly == 1 && restaurant[2] != 1) { + continue; + } + + if (restaurant[3] > maxPrice) { + continue; + } + + if (restaurant[4] > maxDistance) { + continue; + } + + restaurantsFiltered.push_back({restaurant[1], restaurant[0]}); + } + + sort(restaurantsFiltered.begin(), restaurantsFiltered.end(), [](const vector& a, const vector& b) { + if (a[0] != b[0]) { + return a[0] > b[0]; + } + return a[1] > b[1]; + }); + + vector result; + + for (const auto& restaurant : restaurantsFiltered) { + result.push_back(restaurant[1]); + } + + return result; + } +}; diff --git a/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.cs b/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.cs new file mode 100644 index 00000000..eac49cbd --- /dev/null +++ b/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.cs @@ -0,0 +1,36 @@ +public class Solution { + public IList FilterRestaurants(int[][] restaurants, int veganFriendly, int maxPrice, int maxDistance) { + List restaurantsFiltered = new List(); + + foreach (var restaurant in restaurants) { + if (veganFriendly == 1 && restaurant[2] != 1) { + continue; + } + + if (restaurant[3] > maxPrice) { + continue; + } + + if (restaurant[4] > maxDistance) { + continue; + } + + restaurantsFiltered.Add(new int[] { restaurant[1], restaurant[0] }); + } + + restaurantsFiltered.Sort((a, b) => { + if (b[0] != a[0]) { + return b[0].CompareTo(a[0]); + } + return b[1].CompareTo(a[1]); + }); + + List result = new List(); + + foreach (var restaurant in restaurantsFiltered) { + result.Add(restaurant[1]); + } + + return result; + } +} diff --git a/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.dart b/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.dart new file mode 100644 index 00000000..7f7d4cfd --- /dev/null +++ b/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.dart @@ -0,0 +1,36 @@ +class Solution { + List filterRestaurants(List> restaurants, int veganFriendly, int maxPrice, int maxDistance) { + List> restaurantsFiltered = []; + + for (var restaurant in restaurants) { + if (veganFriendly == 1 && restaurant[2] != 1) { + continue; + } + + if (restaurant[3] > maxPrice) { + continue; + } + + if (restaurant[4] > maxDistance) { + continue; + } + + restaurantsFiltered.add([restaurant[1], restaurant[0]]); + } + + restaurantsFiltered.sort((a, b) { + if (b[0] != a[0]) { + return b[0].compareTo(a[0]); + } + return b[1].compareTo(a[1]); + }); + + List result = []; + + for (var restaurant in restaurantsFiltered) { + result.add(restaurant[1]); + } + + return result; + } +} diff --git a/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.go b/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.go new file mode 100644 index 00000000..e3249639 --- /dev/null +++ b/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.go @@ -0,0 +1,34 @@ +func filterRestaurants(restaurants [][]int, veganFriendly int, maxPrice int, maxDistance int) []int { + restaurantsFiltered := [][]int{} + + for _, restaurant := range restaurants { + if veganFriendly == 1 && restaurant[2] != 1 { + continue + } + + if restaurant[3] > maxPrice { + continue + } + + if restaurant[4] > maxDistance { + continue + } + + restaurantsFiltered = append(restaurantsFiltered, []int{restaurant[1], restaurant[0]}) + } + + sort.Slice(restaurantsFiltered, func(i, j int) bool { + if restaurantsFiltered[i][0] != restaurantsFiltered[j][0] { + return restaurantsFiltered[i][0] > restaurantsFiltered[j][0] + } + return restaurantsFiltered[i][1] > restaurantsFiltered[j][1] + }) + + result := []int{} + + for _, restaurant := range restaurantsFiltered { + result = append(result, restaurant[1]) + } + + return result +} diff --git a/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.java b/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.java new file mode 100644 index 00000000..3b838cc1 --- /dev/null +++ b/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.java @@ -0,0 +1,36 @@ +class Solution { + public List filterRestaurants(int[][] restaurants, int veganFriendly, int maxPrice, int maxDistance) { + List restaurantsFiltered = new ArrayList<>(); + + for (int[] restaurant : restaurants) { + if (veganFriendly == 1 && restaurant[2] != 1) { + continue; + } + + if (restaurant[3] > maxPrice) { + continue; + } + + if (restaurant[4] > maxDistance) { + continue; + } + + restaurantsFiltered.add(new int[]{restaurant[1], restaurant[0]}); + } + + restaurantsFiltered.sort((a, b) -> { + if (b[0] != a[0]) { + return Integer.compare(b[0], a[0]); + } + return Integer.compare(b[1], a[1]); + }); + + List result = new ArrayList<>(); + + for (int[] restaurant : restaurantsFiltered) { + result.add(restaurant[1]); + } + + return result; + } +} diff --git a/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.kt b/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.kt new file mode 100644 index 00000000..7a891961 --- /dev/null +++ b/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.kt @@ -0,0 +1,31 @@ +class Solution { + fun filterRestaurants(restaurants: Array, veganFriendly: Int, maxPrice: Int, maxDistance: Int): List { + val restaurantsFiltered = mutableListOf() + + for (restaurant in restaurants) { + if (veganFriendly == 1 && restaurant[2] != 1) { + continue + } + + if (restaurant[3] > maxPrice) { + continue + } + + if (restaurant[4] > maxDistance) { + continue + } + + restaurantsFiltered.add(intArrayOf(restaurant[1], restaurant[0])) + } + + restaurantsFiltered.sortWith(compareByDescending { it[0] }.thenByDescending { it[1] }) + + val result = mutableListOf() + + for (restaurant in restaurantsFiltered) { + result.add(restaurant[1]) + } + + return result + } +} diff --git a/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.py b/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.py new file mode 100644 index 00000000..ec1192ef --- /dev/null +++ b/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.py @@ -0,0 +1,32 @@ +class Solution: + def filterRestaurants( + self, + restaurants: List[List[int]], + veganFriendly: int, + maxPrice: int, + maxDistance: int, + ) -> List[int]: + + restaurants_filtered = [] + + for restaurant in restaurants: + if veganFriendly == 1 and restaurant[2] != 1: + continue + + if restaurant[3] > maxPrice: + continue + + if restaurant[4] > maxDistance: + continue + + restaurants_filtered.append([restaurant[1], restaurant[0]]) # [rating, id] + + restaurants_filtered.sort() + restaurants_filtered.reverse() + + result = [] + + for restaurant in restaurants_filtered: + result.append(restaurant[1]) + + return result diff --git a/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.py2 b/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.py2 new file mode 100644 index 00000000..b0aa3860 --- /dev/null +++ b/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.py2 @@ -0,0 +1,32 @@ +class Solution(object): + def filterRestaurants(self, restaurants, veganFriendly, maxPrice, maxDistance): + """ + :type restaurants: List[List[int]] + :type veganFriendly: int + :type maxPrice: int + :type maxDistance: int + :rtype: List[int] + """ + restaurants_filtered = [] + + for restaurant in restaurants: + if veganFriendly == 1 and restaurant[2] != 1: + continue + + if restaurant[3] > maxPrice: + continue + + if restaurant[4] > maxDistance: + continue + + restaurants_filtered.append([restaurant[1], restaurant[0]]) + + restaurants_filtered.sort() + restaurants_filtered.reverse() + + result = [] + + for restaurant in restaurants_filtered: + result.append(restaurant[1]) + + return result diff --git a/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.rb b/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.rb new file mode 100644 index 00000000..8e264c20 --- /dev/null +++ b/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.rb @@ -0,0 +1,35 @@ +# @param {Integer[][]} restaurants +# @param {Integer} vegan_friendly +# @param {Integer} max_price +# @param {Integer} max_distance +# @return {Integer[]} +def filter_restaurants(restaurants, vegan_friendly, max_price, max_distance) + restaurants_filtered = [] + + restaurants.each do |restaurant| + if vegan_friendly == 1 && restaurant[2] != 1 + next + end + + if restaurant[3] > max_price + next + end + + if restaurant[4] > max_distance + next + end + + restaurants_filtered << [restaurant[1], restaurant[0]] + end + + restaurants_filtered.sort! + restaurants_filtered.reverse! + + result = [] + + restaurants_filtered.each do |restaurant| + result << restaurant[1] + end + + return result +end diff --git a/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.rs b/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.rs new file mode 100644 index 00000000..441697c0 --- /dev/null +++ b/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.rs @@ -0,0 +1,33 @@ +impl Solution { + pub fn filter_restaurants(restaurants: Vec>, vegan_friendly: i32, max_price: i32, max_distance: i32) -> Vec { + let mut restaurants_filtered: Vec> = Vec::new(); + + for restaurant in &restaurants { + if vegan_friendly == 1 && restaurant[2] != 1 { + continue; + } + + if restaurant[3] > max_price { + continue; + } + + if restaurant[4] > max_distance { + continue; + } + + restaurants_filtered.push(vec![restaurant[1], restaurant[0]]); + } + + restaurants_filtered.sort_by(|a, b| { + b[0].cmp(&a[0]).then(b[1].cmp(&a[1])) + }); + + let mut result: Vec = Vec::new(); + + for restaurant in &restaurants_filtered { + result.push(restaurant[1]); + } + + result + } +} diff --git a/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.swift b/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.swift new file mode 100644 index 00000000..fc22b2f0 --- /dev/null +++ b/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.swift @@ -0,0 +1,36 @@ +class Solution { + func filterRestaurants(_ restaurants: [[Int]], _ veganFriendly: Int, _ maxPrice: Int, _ maxDistance: Int) -> [Int] { + var restaurantsFiltered: [[Int]] = [] + + for restaurant in restaurants { + if veganFriendly == 1 && restaurant[2] != 1 { + continue + } + + if restaurant[3] > maxPrice { + continue + } + + if restaurant[4] > maxDistance { + continue + } + + restaurantsFiltered.append([restaurant[1], restaurant[0]]) + } + + restaurantsFiltered.sort { a, b in + if a[0] != b[0] { + return a[0] > b[0] + } + return a[1] > b[1] + } + + var result: [Int] = [] + + for restaurant in restaurantsFiltered { + result.append(restaurant[1]) + } + + return result + } +} diff --git a/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.ts b/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.ts new file mode 100644 index 00000000..d63017d3 --- /dev/null +++ b/tests/1001-1500/1333. filter-restaurants-by-vegan-friendly-price-and-distance/sol.ts @@ -0,0 +1,39 @@ +function filterRestaurants( + restaurants: number[][], + veganFriendly: number, + maxPrice: number, + maxDistance: number, +): number[] { + const restaurantsFiltered: number[][] = []; + + for (const restaurant of restaurants) { + if (veganFriendly === 1 && restaurant[2] !== 1) { + continue; + } + + if (restaurant[3] > maxPrice) { + continue; + } + + if (restaurant[4] > maxDistance) { + continue; + } + + restaurantsFiltered.push([restaurant[1], restaurant[0]]); + } + + restaurantsFiltered.sort((a, b) => { + if (b[0] !== a[0]) { + return b[0] - a[0]; + } + return b[1] - a[1]; + }); + + const result: number[] = []; + + for (const restaurant of restaurantsFiltered) { + result.push(restaurant[1]); + } + + return result; +} diff --git a/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/manifest.yaml b/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/manifest.yaml new file mode 100644 index 00000000..f3149330 --- /dev/null +++ b/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/manifest.yaml @@ -0,0 +1,583 @@ +entry: + id: 1334 + title: "find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance" + params: + n: + type: int + edges: + type: array + items: + type: array + items: + type: int + distanceThreshold: + type: int + call: + cpp: "Solution().findTheCity({n}, {edges}, {distanceThreshold})" + rust: "Solution::find_the_city({n}, {edges}, {distanceThreshold})" + python3: "Solution().findTheCity({n}, {edges}, {distanceThreshold})" + python2: "Solution().findTheCity({n}, {edges}, {distanceThreshold})" + ruby: "find_the_city({n}, {edges}, {distanceThreshold})" + java: "new Solution().findTheCity({n}, {edges}, {distanceThreshold})" + csharp: "new Solution().FindTheCity({n}, {edges}, {distanceThreshold})" + kotlin: "Solution().findTheCity({n}, {edges}, {distanceThreshold})" + go: "findTheCity({n}, {edges}, {distanceThreshold})" + dart: "Solution().findTheCity({n}, {edges}, {distanceThreshold})" + swift: "Solution().findTheCity({n}, {edges}, {distanceThreshold})" + typescript: "findTheCity({n}, {edges}, {distanceThreshold})" +judge: + type: exact +limits: + time_ms: 800 + memory_mb: 300 +oracle: + python3: + call: "Checker().findTheCity(n, edges, distanceThreshold, {result})" + checker: | + import heapq + + class Checker: + def findTheCity(self, n, edges, threshold, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + graph = [[] for _ in range(n)] + for source, target, weight in edges: + graph[source].append((target, weight)) + graph[target].append((source, weight)) + fewest = n + answer = -1 + for city in range(n): + distance = [float("inf")] * n + distance[city] = 0 + queue = [(0, city)] + while queue: + current_distance, node = heapq.heappop(queue) + if current_distance != distance[node]: + continue + for neighbor, weight in graph[node]: + candidate = current_distance + weight + if candidate <= threshold and candidate < distance[neighbor]: + distance[neighbor] = candidate + heapq.heappush(queue, (candidate, neighbor)) + reachable = sum(value <= threshold for value in distance) - 1 + if reachable <= fewest: + fewest = reachable + answer = city + return result == answer +seed: 1334 +tests: + - name: two_near + in: + n: 2 + edges: + - [0, 1, 3] + distanceThreshold: 3 + - name: two_far + in: + n: 2 + edges: + - [0, 1, 3] + distanceThreshold: 2 + - name: path_three + in: + n: 3 + edges: + - [0, 1, 2] + - [1, 2, 2] + distanceThreshold: 2 + - name: triangle + in: + n: 3 + edges: + - [0, 1, 1] + - [1, 2, 1] + - [0, 2, 1] + distanceThreshold: 1 + - name: weighted_triangle + in: + n: 3 + edges: + - [0, 1, 5] + - [1, 2, 2] + - [0, 2, 10] + distanceThreshold: 6 + - name: four_path + in: + n: 4 + edges: + - [0, 1, 1] + - [1, 2, 1] + - [2, 3, 1] + distanceThreshold: 1 + - name: four_dense + in: + n: 4 + edges: + - [0, 1, 4] + - [0, 2, 2] + - [0, 3, 7] + - [1, 2, 1] + - [1, 3, 3] + - [2, 3, 5] + distanceThreshold: 5 + - name: disconnected + in: + n: 5 + edges: + - [0, 1, 1] + - [2, 3, 1] + distanceThreshold: 2 + - name: star + in: + n: 6 + edges: + - [0, 1, 2] + - [0, 2, 2] + - [0, 3, 2] + - [0, 4, 2] + - [0, 5, 2] + distanceThreshold: 2 + - name: chain_six + in: + n: 6 + edges: + - [0, 1, 1] + - [1, 2, 2] + - [2, 3, 3] + - [3, 4, 4] + - [4, 5, 5] + distanceThreshold: 5 + - name: shortcut + in: + n: 5 + edges: + - [0, 1, 10] + - [1, 2, 10] + - [2, 3, 10] + - [3, 4, 10] + - [0, 4, 1] + distanceThreshold: 5 + - name: equal_counts + in: + n: 4 + edges: + - [0, 1, 100] + - [2, 3, 100] + distanceThreshold: 1 + - name: complete_five + in: + n: 5 + edges: + - [0, 1, 1] + - [0, 2, 2] + - [0, 3, 3] + - [0, 4, 4] + - [1, 2, 1] + - [1, 3, 2] + - [1, 4, 3] + - [2, 3, 1] + - [2, 4, 2] + - [3, 4, 1] + distanceThreshold: 3 + - name: isolated_last + in: + n: 6 + edges: + - [0, 1, 1] + - [1, 2, 1] + - [2, 3, 1] + - [3, 4, 1] + distanceThreshold: 2 + - name: threshold_one + in: + n: 7 + edges: + - [0, 1, 1] + - [1, 2, 1] + - [2, 3, 1] + - [3, 4, 1] + - [4, 5, 1] + - [5, 6, 1] + distanceThreshold: 1 + - name: threshold_large + in: + n: 7 + edges: + - [0, 1, 100] + - [1, 2, 100] + - [2, 3, 100] + - [3, 4, 100] + - [4, 5, 100] + - [5, 6, 100] + distanceThreshold: 10000 + - name: alternate_weights + in: + n: 8 + edges: + - [0, 1, 1] + - [1, 2, 9] + - [2, 3, 1] + - [3, 4, 9] + - [4, 5, 1] + - [5, 6, 9] + - [6, 7, 1] + distanceThreshold: 10 + - name: bridge + in: + n: 8 + edges: + - [0, 1, 2] + - [1, 2, 2] + - [2, 3, 2] + - [4, 5, 2] + - [5, 6, 2] + - [6, 7, 2] + - [3, 4, 20] + distanceThreshold: 6 + - name: cycle_six + in: + n: 6 + edges: + - [0, 1, 3] + - [1, 2, 3] + - [2, 3, 3] + - [3, 4, 3] + - [4, 5, 3] + - [5, 0, 3] + distanceThreshold: 6 + - name: long_path + in: + n: 9 + edges: + - [0, 1, 2] + - [1, 2, 2] + - [2, 3, 2] + - [3, 4, 2] + - [4, 5, 2] + - [5, 6, 2] + - [6, 7, 2] + - [7, 8, 2] + distanceThreshold: 8 + - name: dense_six + in: + n: 6 + edges: + - [0, 1, 4] + - [0, 2, 8] + - [0, 3, 15] + - [0, 4, 7] + - [0, 5, 20] + - [1, 2, 3] + - [1, 3, 10] + - [1, 4, 5] + - [1, 5, 12] + - [2, 3, 4] + - [2, 4, 6] + - [2, 5, 9] + - [3, 4, 2] + - [3, 5, 5] + - [4, 5, 3] + distanceThreshold: 10 + - name: ten_city_unit_path_radius_three + in: + n: 10 + edges: + - [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] + distanceThreshold: 3 + - name: five_disjoint_weighted_pairs + in: + n: 10 + edges: + - [0, 1, 2] + - [2, 3, 4] + - [4, 5, 6] + - [6, 7, 8] + - [8, 9, 10] + distanceThreshold: 7 + - name: costly_direct_edge_loses_to_two_hop_route + in: + n: 5 + edges: + - [0, 1, 1] + - [1, 2, 1] + - [2, 3, 1] + - [3, 4, 1] + - [0, 4, 10] + distanceThreshold: 2 + - name: cycle_with_cheap_wraparound + in: + n: 6 + edges: + - [0, 1, 7] + - [1, 2, 7] + - [2, 3, 7] + - [3, 4, 7] + - [4, 5, 7] + - [0, 5, 1] + distanceThreshold: 7 + - name: path_with_unusable_endpoint_shortcut + in: + n: 7 + edges: + - [0, 1, 2] + - [1, 2, 2] + - [2, 3, 2] + - [3, 4, 2] + - [4, 5, 2] + - [5, 6, 2] + - [0, 6, 20] + distanceThreshold: 4 + - name: uneven_components_with_expensive_bridge + in: + n: 8 + edges: + - [0, 1, 5] + - [1, 2, 5] + - [2, 3, 5] + - [4, 5, 1] + - [5, 6, 1] + - [6, 7, 1] + - [3, 4, 50] + distanceThreshold: 3 + - name: nine_city_cycle_radius_two + in: + n: 9 + edges: + - [0, 1, 1] + - [1, 2, 1] + - [2, 3, 1] + - [3, 4, 1] + - [4, 5, 1] + - [5, 6, 1] + - [6, 7, 1] + - [7, 8, 1] + - [0, 8, 1] + distanceThreshold: 2 + - name: direct_edge_outside_threshold + in: + n: 4 + edges: + - [0, 1, 10] + - [1, 2, 20] + - [2, 3, 30] + - [0, 3, 5] + - [0, 2, 15] + distanceThreshold: 14 + - name: fan_with_chain_shortcuts + in: + n: 5 + edges: + - [0, 1, 2] + - [0, 2, 4] + - [0, 3, 6] + - [0, 4, 8] + - [1, 2, 2] + - [2, 3, 2] + - [3, 4, 2] + distanceThreshold: 5 + - name: alternating_cycle_weights + in: + n: 6 + edges: + - [0, 1, 1] + - [1, 2, 10] + - [2, 3, 1] + - [3, 4, 10] + - [4, 5, 1] + - [0, 5, 10] + distanceThreshold: 11 + - name: increasing_weight_path + in: + n: 7 + edges: + - [0, 1, 3] + - [1, 2, 4] + - [2, 3, 5] + - [3, 4, 6] + - [4, 5, 7] + - [5, 6, 8] + distanceThreshold: 9 + - name: weighted_star_threshold_boundary + in: + n: 8 + edges: + - [0, 1, 2] + - [0, 2, 3] + - [0, 3, 4] + - [0, 4, 5] + - [0, 5, 6] + - [0, 6, 7] + - [0, 7, 8] + distanceThreshold: 5 + - name: ten_city_cycle_with_cheap_closing_edge + in: + n: 10 + edges: + - [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] + - [0, 9, 1] + distanceThreshold: 6 + - name: cheap_outer_edge_bypasses_heavy_interior + in: + n: 5 + edges: + - [0, 1, 9] + - [1, 2, 1] + - [2, 3, 9] + - [3, 4, 1] + - [0, 4, 2] + distanceThreshold: 3 + - name: example_one_tie_uses_largest_city + in: + n: 4 + edges: + - [0, 1, 3] + - [1, 2, 1] + - [1, 3, 4] + - [2, 3, 1] + distanceThreshold: 4 + - name: example_two_unique_minimum + in: + n: 5 + edges: + - [0, 1, 2] + - [0, 4, 8] + - [1, 2, 3] + - [1, 4, 2] + - [2, 3, 1] + - [3, 4, 1] + distanceThreshold: 2 + - name: two_hop_distance_exactly_on_threshold + in: + n: 4 + edges: + - [0, 1, 4] + - [1, 2, 6] + - [2, 3, 4] + distanceThreshold: 10 + - name: hundred_city_mostly_isolated_graph + in: + n: 100 + edges: + - [0, 1, 1] + - [98, 99, 10000] + distanceThreshold: 1 + - name: hundred_city_star_with_limited_leaf_reach + in: + n: 100 + edges: + - [0, 1, 1] + - [0, 2, 1] + - [0, 3, 1] + - [0, 4, 1] + - [0, 5, 1] + - [0, 6, 1] + - [0, 7, 1] + - [0, 8, 1] + - [0, 9, 1] + - [0, 10, 1] + - [0, 11, 1] + - [0, 12, 1] + - [0, 13, 1] + - [0, 14, 1] + - [0, 15, 1] + - [0, 16, 1] + - [0, 17, 1] + - [0, 18, 1] + - [0, 19, 1] + - [0, 20, 1] + - [0, 21, 1] + - [0, 22, 1] + - [0, 23, 1] + - [0, 24, 1] + - [0, 25, 1] + - [0, 26, 1] + - [0, 27, 1] + - [0, 28, 1] + - [0, 29, 1] + - [0, 30, 1] + - [0, 31, 1] + - [0, 32, 1] + - [0, 33, 1] + - [0, 34, 1] + - [0, 35, 1] + - [0, 36, 1] + - [0, 37, 1] + - [0, 38, 1] + - [0, 39, 1] + - [0, 40, 1] + - [0, 41, 1] + - [0, 42, 1] + - [0, 43, 1] + - [0, 44, 1] + - [0, 45, 1] + - [0, 46, 1] + - [0, 47, 1] + - [0, 48, 1] + - [0, 49, 1] + - [0, 50, 1] + - [0, 51, 1] + - [0, 52, 1] + - [0, 53, 1] + - [0, 54, 1] + - [0, 55, 1] + - [0, 56, 1] + - [0, 57, 1] + - [0, 58, 1] + - [0, 59, 1] + - [0, 60, 1] + - [0, 61, 1] + - [0, 62, 1] + - [0, 63, 1] + - [0, 64, 1] + - [0, 65, 1] + - [0, 66, 1] + - [0, 67, 1] + - [0, 68, 1] + - [0, 69, 1] + - [0, 70, 1] + - [0, 71, 1] + - [0, 72, 1] + - [0, 73, 1] + - [0, 74, 1] + - [0, 75, 1] + - [0, 76, 1] + - [0, 77, 1] + - [0, 78, 1] + - [0, 79, 1] + - [0, 80, 1] + - [0, 81, 1] + - [0, 82, 1] + - [0, 83, 1] + - [0, 84, 1] + - [0, 85, 1] + - [0, 86, 1] + - [0, 87, 1] + - [0, 88, 1] + - [0, 89, 1] + - [0, 90, 1] + - [0, 91, 1] + - [0, 92, 1] + - [0, 93, 1] + - [0, 94, 1] + - [0, 95, 1] + - [0, 96, 1] + - [0, 97, 1] + - [0, 98, 1] + - [0, 99, 1] + distanceThreshold: 1 diff --git a/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.cpp b/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.cpp new file mode 100644 index 00000000..61eae2bc --- /dev/null +++ b/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.cpp @@ -0,0 +1,44 @@ +class Solution { +public: + int findTheCity(int n, vector>& edges, int distanceThreshold) { + const int INF = INT_MAX / 2; + vector> matrix(n, vector(n, INF)); + + for (int i = 0; i < n; i++) { + matrix[i][i] = 0; + } + + for (auto& edge : edges) { + int u = edge[0], v = edge[1], w = edge[2]; + matrix[u][v] = matrix[v][u] = w; + } + + for (int via = 0; via < n; via++) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (matrix[i][via] + matrix[via][j] < matrix[i][j]) { + matrix[i][j] = matrix[i][via] + matrix[via][j]; + } + } + } + } + + int minReachable = n; + int ans = -1; + + for (int i = 0; i < n; i++) { + int count = 0; + for (int j = 0; j < n; j++) { + if (matrix[i][j] <= distanceThreshold) { + count++; + } + } + if (count <= minReachable) { + minReachable = count; + ans = i; + } + } + + return ans; + } +}; diff --git a/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.cs b/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.cs new file mode 100644 index 00000000..f56d0b21 --- /dev/null +++ b/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.cs @@ -0,0 +1,47 @@ +public class Solution { + public int FindTheCity(int n, int[][] edges, int distanceThreshold) { + const int INF = int.MaxValue / 2; + int[,] matrix = new int[n, n]; + + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + matrix[i, j] = INF; + } + matrix[i, i] = 0; + } + + foreach (var edge in edges) { + int u = edge[0], v = edge[1], w = edge[2]; + matrix[u, v] = w; + matrix[v, u] = w; + } + + for (int via = 0; via < n; via++) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (matrix[i, via] + matrix[via, j] < matrix[i, j]) { + matrix[i, j] = matrix[i, via] + matrix[via, j]; + } + } + } + } + + int minReachable = n; + int ans = -1; + + for (int i = 0; i < n; i++) { + int count = 0; + for (int j = 0; j < n; j++) { + if (matrix[i, j] <= distanceThreshold) { + count++; + } + } + if (count <= minReachable) { + minReachable = count; + ans = i; + } + } + + return ans; + } +} diff --git a/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.dart b/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.dart new file mode 100644 index 00000000..7e60b8fe --- /dev/null +++ b/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.dart @@ -0,0 +1,44 @@ +class Solution { + int findTheCity(int n, List> edges, int distanceThreshold) { + const int INF = 1 << 30; + List> matrix = List.generate(n, (_) => List.filled(n, INF)); + + for (int i = 0; i < n; i++) { + matrix[i][i] = 0; + } + + for (var edge in edges) { + int u = edge[0], v = edge[1], w = edge[2]; + matrix[u][v] = w; + matrix[v][u] = w; + } + + for (int via = 0; via < n; via++) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (matrix[i][via] + matrix[via][j] < matrix[i][j]) { + matrix[i][j] = matrix[i][via] + matrix[via][j]; + } + } + } + } + + int minReachable = n; + int ans = -1; + + for (int i = 0; i < n; i++) { + int count = 0; + for (int j = 0; j < n; j++) { + if (matrix[i][j] <= distanceThreshold) { + count++; + } + } + if (count <= minReachable) { + minReachable = count; + ans = i; + } + } + + return ans; + } +} diff --git a/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.go b/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.go new file mode 100644 index 00000000..3f958882 --- /dev/null +++ b/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.go @@ -0,0 +1,45 @@ +func findTheCity(n int, edges [][]int, distanceThreshold int) int { + const INF = int(1e9) + matrix := make([][]int, n) + for i := 0; i < n; i++ { + matrix[i] = make([]int, n) + for j := 0; j < n; j++ { + matrix[i][j] = INF + } + matrix[i][i] = 0 + } + + for _, edge := range edges { + u, v, w := edge[0], edge[1], edge[2] + matrix[u][v] = w + matrix[v][u] = w + } + + for via := 0; via < n; via++ { + for i := 0; i < n; i++ { + for j := 0; j < n; j++ { + if matrix[i][via] + matrix[via][j] < matrix[i][j] { + matrix[i][j] = matrix[i][via] + matrix[via][j] + } + } + } + } + + minReachable := n + ans := -1 + + for i := 0; i < n; i++ { + count := 0 + for j := 0; j < n; j++ { + if matrix[i][j] <= distanceThreshold { + count++ + } + } + if count <= minReachable { + minReachable = count + ans = i + } + } + + return ans +} diff --git a/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.java b/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.java new file mode 100644 index 00000000..8ee30638 --- /dev/null +++ b/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.java @@ -0,0 +1,46 @@ +class Solution { + public int findTheCity(int n, int[][] edges, int distanceThreshold) { + final int INF = Integer.MAX_VALUE / 2; + int[][] matrix = new int[n][n]; + + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + matrix[i][j] = INF; + } + matrix[i][i] = 0; + } + + for (int[] edge : edges) { + int u = edge[0], v = edge[1], w = edge[2]; + matrix[u][v] = matrix[v][u] = w; + } + + for (int via = 0; via < n; via++) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (matrix[i][via] + matrix[via][j] < matrix[i][j]) { + matrix[i][j] = matrix[i][via] + matrix[via][j]; + } + } + } + } + + int minReachable = n; + int ans = -1; + + for (int i = 0; i < n; i++) { + int count = 0; + for (int j = 0; j < n; j++) { + if (matrix[i][j] <= distanceThreshold) { + count++; + } + } + if (count <= minReachable) { + minReachable = count; + ans = i; + } + } + + return ans; + } +} diff --git a/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.kt b/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.kt new file mode 100644 index 00000000..daa7502c --- /dev/null +++ b/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.kt @@ -0,0 +1,46 @@ +class Solution { + fun findTheCity(n: Int, edges: Array, distanceThreshold: Int): Int { + val INF = Int.MAX_VALUE / 2 + val matrix = Array(n) { IntArray(n) { INF } } + + for (i in 0 until n) { + matrix[i][i] = 0 + } + + for (edge in edges) { + val u = edge[0] + val v = edge[1] + val w = edge[2] + matrix[u][v] = w + matrix[v][u] = w + } + + for (via in 0 until n) { + for (i in 0 until n) { + for (j in 0 until n) { + if (matrix[i][via] + matrix[via][j] < matrix[i][j]) { + matrix[i][j] = matrix[i][via] + matrix[via][j] + } + } + } + } + + var minReachable = n + var ans = -1 + + for (i in 0 until n) { + var count = 0 + for (j in 0 until n) { + if (matrix[i][j] <= distanceThreshold) { + count++ + } + } + if (count <= minReachable) { + minReachable = count + ans = i + } + } + + return ans + } +} diff --git a/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.py b/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.py new file mode 100644 index 00000000..87660e9c --- /dev/null +++ b/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.py @@ -0,0 +1,32 @@ +from typing import List + + +class Solution: + def findTheCity( + self, n: int, edges: List[List[int]], distanceThreshold: int + ) -> int: + INF = float("inf") + matrix = [[INF] * n for _ in range(n)] + + for i in range(n): + matrix[i][i] = 0 + + for u, v, w in edges: + matrix[u][v] = matrix[v][u] = w + + # Floyd-Warshall + for via in range(n): + for i in range(n): + for j in range(n): + matrix[i][j] = min(matrix[i][j], matrix[i][via] + matrix[via][j]) + + min_reachable = n + ans = -1 + + for i in range(n): + count = sum(1 for j in range(n) if matrix[i][j] <= distanceThreshold) + if count <= min_reachable: + min_reachable = count + ans = i + + return ans diff --git a/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.py2 b/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.py2 new file mode 100644 index 00000000..10e90c55 --- /dev/null +++ b/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.py2 @@ -0,0 +1,33 @@ +class Solution(object): + def findTheCity(self, n, edges, distanceThreshold): + """ + :type n: int + :type edges: List[List[int]] + :type distanceThreshold: int + :rtype: int + """ + INF = float('inf') + matrix = [[INF] * n for _ in range(n)] + + for i in range(n): + matrix[i][i] = 0 + + for u, v, w in edges: + matrix[u][v] = matrix[v][u] = w + + for via in range(n): + for i in range(n): + for j in range(n): + if matrix[i][via] + matrix[via][j] < matrix[i][j]: + matrix[i][j] = matrix[i][via] + matrix[via][j] + + min_reachable = n + ans = -1 + + for i in range(n): + count = sum(1 for j in range(n) if matrix[i][j] <= distanceThreshold) + if count <= min_reachable: + min_reachable = count + ans = i + + return ans diff --git a/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.rb b/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.rb new file mode 100644 index 00000000..1deb04c9 --- /dev/null +++ b/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.rb @@ -0,0 +1,37 @@ +# @param {Integer} n +# @param {Integer[][]} edges +# @param {Integer} distance_threshold +# @return {Integer} +def find_the_city(n, edges, distance_threshold) + inf = Float::INFINITY + matrix = Array.new(n) { Array.new(n, inf) } + + (0...n).each { |i| matrix[i][i] = 0 } + + edges.each do |u, v, w| + matrix[u][v] = matrix[v][u] = w + end + + (0...n).each do |via| + (0...n).each do |i| + (0...n).each do |j| + if matrix[i][via] + matrix[via][j] < matrix[i][j] + matrix[i][j] = matrix[i][via] + matrix[via][j] + end + end + end + end + + min_reachable = n + ans = -1 + + (0...n).each do |i| + count = (0...n).count { |j| matrix[i][j] <= distance_threshold } + if count <= min_reachable + min_reachable = count + ans = i + end + end + + ans +end diff --git a/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.rs b/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.rs new file mode 100644 index 00000000..e3cf8199 --- /dev/null +++ b/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.rs @@ -0,0 +1,42 @@ +impl Solution { + pub fn find_the_city(n: i32, edges: Vec>, distance_threshold: i32) -> i32 { + let n = n as usize; + let inf = i32::MAX / 2; + let mut matrix = vec![vec![inf; n]; n]; + + for i in 0..n { + matrix[i][i] = 0; + } + + for edge in &edges { + let u = edge[0] as usize; + let v = edge[1] as usize; + let w = edge[2]; + matrix[u][v] = w; + matrix[v][u] = w; + } + + for via in 0..n { + for i in 0..n { + for j in 0..n { + if matrix[i][via] + matrix[via][j] < matrix[i][j] { + matrix[i][j] = matrix[i][via] + matrix[via][j]; + } + } + } + } + + let mut min_reachable = n as i32; + let mut ans: i32 = -1; + + for i in 0..n { + let count = (0..n).filter(|&j| matrix[i][j] <= distance_threshold).count() as i32; + if count <= min_reachable { + min_reachable = count; + ans = i as i32; + } + } + + ans + } +} diff --git a/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.swift b/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.swift new file mode 100644 index 00000000..87f2e209 --- /dev/null +++ b/tests/1001-1500/1334. find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/sol.swift @@ -0,0 +1,44 @@ +class Solution { + func findTheCity(_ n: Int, _ edges: [[Int]], _ distanceThreshold: Int) -> Int { + let INF = Int.max / 2 + var matrix = Array(repeating: Array(repeating: INF, count: n), count: n) + + for i in 0.. + Array(n).fill(INF), + ); + + for (let i = 0; i < n; i++) { + matrix[i][i] = 0; + } + + for (const [u, v, w] of edges) { + matrix[u][v] = w; + matrix[v][u] = w; + } + + for (let via = 0; via < n; via++) { + for (let i = 0; i < n; i++) { + for (let j = 0; j < n; j++) { + if (matrix[i][via] + matrix[via][j] < matrix[i][j]) { + matrix[i][j] = matrix[i][via] + matrix[via][j]; + } + } + } + } + + let minReachable = n; + let ans = -1; + + for (let i = 0; i < n; i++) { + let count = 0; + for (let j = 0; j < n; j++) { + if (matrix[i][j] <= distanceThreshold) { + count++; + } + } + if (count <= minReachable) { + minReachable = count; + ans = i; + } + } + + return ans; +} diff --git a/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/manifest.yaml b/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/manifest.yaml new file mode 100644 index 00000000..723f1de2 --- /dev/null +++ b/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/manifest.yaml @@ -0,0 +1,297 @@ +entry: + id: 1335 + title: "minimum-difficulty-of-a-job-schedule" + params: + jobDifficulty: + type: array + items: + type: int + d: + type: int + call: + cpp: "Solution().minDifficulty({jobDifficulty}, {d})" + rust: "Solution::min_difficulty({jobDifficulty}, {d})" + python3: "Solution().minDifficulty({jobDifficulty}, {d})" + python2: "Solution().minDifficulty({jobDifficulty}, {d})" + ruby: "min_difficulty({jobDifficulty}, {d})" + java: "new Solution().minDifficulty({jobDifficulty}, {d})" + csharp: "new Solution().MinDifficulty({jobDifficulty}, {d})" + kotlin: "Solution().minDifficulty({jobDifficulty}, {d})" + go: "minDifficulty({jobDifficulty}, {d})" + dart: "Solution().minDifficulty({jobDifficulty}, {d})" + swift: "Solution().minDifficulty({jobDifficulty}, {d})" + typescript: "minDifficulty({jobDifficulty}, {d})" +judge: + type: "exact" +limits: + time_ms: 700 + memory_mb: 300 +oracle: + python3: + call: "Checker().minDifficulty(jobDifficulty, d, {result})" + checker: | + class Checker: + def minDifficulty(self, jobs, days, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + n = len(jobs) + if days > n: + return result == -1 + previous = [10**9] * (n + 1) + previous[0] = 0 + for day in range(1, days + 1): + current = [10**9] * (n + 1) + for end in range(day, n + 1): + maximum = 0 + for start in range(end - 1, day - 2, -1): + maximum = max(maximum, jobs[start]) + current[end] = min(current[end], previous[start] + maximum) + previous = current + return result == previous[n] +seed: 1335 +tests: + - name: "example_one_decreasing_two_days" + in: + jobDifficulty: [6, 5, 4, 3, 2, 1] + d: 2 + out: 7 + - name: "example_two_too_many_days" + in: + jobDifficulty: [9, 9, 9] + d: 4 + out: -1 + - name: "example_three_one_per_day" + in: + jobDifficulty: [1, 1, 1] + d: 3 + out: 3 + - name: "single_zero_job" + in: + jobDifficulty: [0] + d: 1 + out: 0 + - name: "one_day_uses_global_maximum" + in: + jobDifficulty: [6, 1, 8, 2, 5] + d: 1 + out: 8 + - name: "every_job_its_own_day" + in: + jobDifficulty: [6, 5, 4] + d: 3 + out: 15 + - name: "one_day_more_than_jobs" + in: + jobDifficulty: [6, 5, 4] + d: 4 + out: -1 + - name: "all_equal_split_three_days" + in: + jobDifficulty: [5, 5, 5, 5, 5] + d: 3 + out: 15 + - name: "increasing_two_days" + in: + jobDifficulty: [1, 2, 3, 4, 5] + d: 2 + out: 6 + - name: "decreasing_two_days" + in: + jobDifficulty: [5, 4, 3, 2, 1] + d: 2 + out: 6 + - name: "all_zero_two_days" + in: + jobDifficulty: [0, 0, 0, 0] + d: 2 + out: 0 + - name: "near_maximum_values" + in: + jobDifficulty: [1000, 999, 998, 997] + d: 2 + out: 1997 + - name: "alternating_highs" + in: + jobDifficulty: [1, 100, 2, 99, 3, 98] + d: 3 + out: 199 + - name: "separated_peaks" + in: + jobDifficulty: [10, 1, 10, 1, 10] + d: 3 + out: 21 + - name: "separated_valleys" + in: + jobDifficulty: [1, 10, 1, 10, 1] + d: 3 + out: 12 + - name: "four_jobs_two_days" + in: + jobDifficulty: [7, 1, 5, 2] + d: 2 + out: 9 + - name: "four_jobs_three_days" + in: + jobDifficulty: [7, 1, 5, 2] + d: 3 + out: 13 + - name: "five_jobs_four_days" + in: + jobDifficulty: [8, 2, 6, 1, 7] + d: 4 + out: 22 + - name: "late_large_job_two_days" + in: + jobDifficulty: [1, 1, 1, 100] + d: 2 + out: 101 + - name: "early_large_job_two_days" + in: + jobDifficulty: [100, 1, 1, 1] + d: 2 + out: 101 + - name: "late_large_job_three_days" + in: + jobDifficulty: [1, 1, 1, 100] + d: 3 + out: 102 + - name: "repeated_peak_boundaries" + in: + jobDifficulty: [2, 8, 2, 8, 2, 8] + d: 3 + out: 18 + - name: "mixed_partition_a" + in: + jobDifficulty: [3, 7, 2, 9, 4, 6, 1] + d: 3 + out: 13 + - name: "mixed_partition_b" + in: + jobDifficulty: [10, 2, 8, 4, 6, 1, 9] + d: 4 + out: 26 + - name: "mixed_partition_c" + in: + jobDifficulty: [4, 4, 10, 1, 6, 6] + d: 2 + out: 14 + - name: "mixed_partition_d" + in: + jobDifficulty: [1, 9, 3, 7, 5] + d: 4 + out: 20 + - name: "mixed_partition_e" + in: + jobDifficulty: [9, 1, 8, 2, 7, 3] + d: 2 + out: 12 + - name: "small_value_alternation" + in: + jobDifficulty: [1, 2, 1, 2, 1, 2, 1] + d: 3 + out: 4 + - name: "all_maximum_values" + in: + jobDifficulty: [1000, 1000, 1000, 1000] + d: 2 + out: 2000 + - name: "six_equal_jobs_five_days" + in: + jobDifficulty: [1, 1, 1, 1, 1, 1] + d: 5 + out: 5 + - name: "seven_jobs_two_days" + in: + jobDifficulty: [7, 3, 8, 2, 5, 1, 6] + d: 2 + out: 14 + - name: "eight_jobs_four_days" + in: + jobDifficulty: [2, 9, 1, 8, 3, 7, 4, 6] + d: 4 + out: 20 + - name: "nine_decreasing_jobs_five_days" + in: + jobDifficulty: [9, 8, 7, 6, 5, 4, 3, 2, 1] + d: 5 + out: 19 + - name: "ten_job_zigzag_five_days" + in: + jobDifficulty: [1, 10, 2, 9, 3, 8, 4, 7, 5, 6] + d: 5 + out: 28 + - name: "ten_jobs_all_separate" + in: + jobDifficulty: [4, 1, 9, 2, 8, 3, 7, 5, 6, 10] + d: 10 + out: 55 + - name: "generated_max_length_one_day" + seed: 133501 + in: + jobDifficulty: + gen: "array" + len: 300 + of: + gen: "int" + min: 0 + max: 1000 + distinct: false + sorted: false + elemType: "int" + d: 1 + - name: "generated_max_length_two_days" + seed: 133502 + in: + jobDifficulty: + gen: "array" + len: 300 + of: + gen: "int" + min: 0 + max: 1000 + distinct: false + sorted: false + elemType: "int" + d: 2 + - name: "generated_max_length_five_days" + seed: 133503 + in: + jobDifficulty: + gen: "array" + len: 300 + of: + gen: "int" + min: 0 + max: 1000 + distinct: false + sorted: false + elemType: "int" + d: 5 + - name: "generated_max_length_nine_days" + seed: 133504 + in: + jobDifficulty: + gen: "array" + len: 300 + of: + gen: "int" + min: 0 + max: 1000 + distinct: false + sorted: false + elemType: "int" + d: 9 + - name: "generated_max_length_ten_days" + seed: 133505 + in: + jobDifficulty: + gen: "array" + len: 300 + of: + gen: "int" + min: 0 + max: 1000 + distinct: false + sorted: false + elemType: "int" + d: 10 diff --git a/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.cpp b/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.cpp new file mode 100644 index 00000000..96b362af --- /dev/null +++ b/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + int minDifficulty(vector& jobDifficulty, int d) { + int length = jobDifficulty.size(); + if (d > length) { + return -1; + } + + vector> minDifficulties(d, vector(length, INT_MAX)); + + int maxDiff = 0; + int i = 0; + while (i <= length - d) { + maxDiff = max(maxDiff, jobDifficulty[i]); + minDifficulties[0][i] = maxDiff; + i++; + } + + int currentDay = 1; + while (currentDay < d) { + int to = currentDay; + while (to <= length - d + currentDay) { + int currentJobDifficulty = jobDifficulty[to]; + int result = INT_MAX; + int j = to - 1; + while (j >= currentDay - 1) { + result = min(result, minDifficulties[currentDay - 1][j] + currentJobDifficulty); + currentJobDifficulty = max(currentJobDifficulty, jobDifficulty[j]); + j--; + } + minDifficulties[currentDay][to] = result; + to++; + } + currentDay++; + } + + return minDifficulties[d - 1][length - 1]; + } +}; diff --git a/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.cs b/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.cs new file mode 100644 index 00000000..48ad6f26 --- /dev/null +++ b/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.cs @@ -0,0 +1,44 @@ +public class Solution { + public int MinDifficulty(int[] jobDifficulty, int d) { + int length = jobDifficulty.Length; + if (d > length) { + return -1; + } + + int[][] minDifficulties = new int[d][]; + for (int day = 0; day < d; day++) { + minDifficulties[day] = new int[length]; + for (int i = 0; i < length; i++) { + minDifficulties[day][i] = int.MaxValue; + } + } + + int maxDiff = 0; + int idx = 0; + while (idx <= length - d) { + maxDiff = Math.Max(maxDiff, jobDifficulty[idx]); + minDifficulties[0][idx] = maxDiff; + idx++; + } + + int currentDay = 1; + while (currentDay < d) { + int to = currentDay; + while (to <= length - d + currentDay) { + int currentJobDifficulty = jobDifficulty[to]; + int result = int.MaxValue; + int j = to - 1; + while (j >= currentDay - 1) { + result = Math.Min(result, minDifficulties[currentDay - 1][j] + currentJobDifficulty); + currentJobDifficulty = Math.Max(currentJobDifficulty, jobDifficulty[j]); + j--; + } + minDifficulties[currentDay][to] = result; + to++; + } + currentDay++; + } + + return minDifficulties[d - 1][length - 1]; + } +} diff --git a/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.dart b/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.dart new file mode 100644 index 00000000..0019c5ed --- /dev/null +++ b/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.dart @@ -0,0 +1,40 @@ +import 'dart:math'; + +class Solution { + int minDifficulty(List jobDifficulty, int d) { + int length = jobDifficulty.length; + if (d > length) { + return -1; + } + + List> minDifficulties = List.generate(d, (_) => List.filled(length, 1 << 60)); + + int maxDiff = 0; + int i = 0; + while (i <= length - d) { + maxDiff = max(maxDiff, jobDifficulty[i]); + minDifficulties[0][i] = maxDiff; + i++; + } + + int currentDay = 1; + while (currentDay < d) { + int to = currentDay; + while (to <= length - d + currentDay) { + int currentJobDifficulty = jobDifficulty[to]; + int result = 1 << 60; + int j = to - 1; + while (j >= currentDay - 1) { + result = min(result, minDifficulties[currentDay - 1][j] + currentJobDifficulty); + currentJobDifficulty = max(currentJobDifficulty, jobDifficulty[j]); + j--; + } + minDifficulties[currentDay][to] = result; + to++; + } + currentDay++; + } + + return minDifficulties[d - 1][length - 1]; + } +} diff --git a/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.go b/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.go new file mode 100644 index 00000000..76d6f08d --- /dev/null +++ b/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.go @@ -0,0 +1,48 @@ +func minDifficulty(jobDifficulty []int, d int) int { + length := len(jobDifficulty) + if d > length { + return -1 + } + + minDifficulties := make([][]int, d) + for day := 0; day < d; day++ { + minDifficulties[day] = make([]int, length) + for i := 0; i < length; i++ { + minDifficulties[day][i] = math.MaxInt32 + } + } + + maxDiff := 0 + i := 0 + for i <= length - d { + if jobDifficulty[i] > maxDiff { + maxDiff = jobDifficulty[i] + } + minDifficulties[0][i] = maxDiff + i++ + } + + currentDay := 1 + for currentDay < d { + to := currentDay + for to <= length - d + currentDay { + currentJobDifficulty := jobDifficulty[to] + result := math.MaxInt32 + j := to - 1 + for j >= currentDay - 1 { + if minDifficulties[currentDay - 1][j] + currentJobDifficulty < result { + result = minDifficulties[currentDay - 1][j] + currentJobDifficulty + } + if jobDifficulty[j] > currentJobDifficulty { + currentJobDifficulty = jobDifficulty[j] + } + j-- + } + minDifficulties[currentDay][to] = result + to++ + } + currentDay++ + } + + return minDifficulties[d - 1][length - 1] +} diff --git a/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.java b/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.java new file mode 100644 index 00000000..f4c6f882 --- /dev/null +++ b/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.java @@ -0,0 +1,43 @@ +class Solution { + public int minDifficulty(int[] jobDifficulty, int d) { + int length = jobDifficulty.length; + if (d > length) { + return -1; + } + + int[][] minDifficulties = new int[d][length]; + for (int day = 0; day < d; day++) { + for (int i = 0; i < length; i++) { + minDifficulties[day][i] = Integer.MAX_VALUE; + } + } + + int maxDiff = 0; + int i = 0; + while (i <= length - d) { + maxDiff = Math.max(maxDiff, jobDifficulty[i]); + minDifficulties[0][i] = maxDiff; + i++; + } + + int currentDay = 1; + while (currentDay < d) { + int to = currentDay; + while (to <= length - d + currentDay) { + int currentJobDifficulty = jobDifficulty[to]; + int result = Integer.MAX_VALUE; + int j = to - 1; + while (j >= currentDay - 1) { + result = Math.min(result, minDifficulties[currentDay - 1][j] + currentJobDifficulty); + currentJobDifficulty = Math.max(currentJobDifficulty, jobDifficulty[j]); + j--; + } + minDifficulties[currentDay][to] = result; + to++; + } + currentDay++; + } + + return minDifficulties[d - 1][length - 1]; + } +} diff --git a/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.kt b/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.kt new file mode 100644 index 00000000..d049c404 --- /dev/null +++ b/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.kt @@ -0,0 +1,38 @@ +class Solution { + fun minDifficulty(jobDifficulty: IntArray, d: Int): Int { + val length = jobDifficulty.size + if (d > length) { + return -1 + } + + val minDifficulties = Array(d) { IntArray(length) { Int.MAX_VALUE } } + + var maxDiff = 0 + var i = 0 + while (i <= length - d) { + maxDiff = maxOf(maxDiff, jobDifficulty[i]) + minDifficulties[0][i] = maxDiff + i++ + } + + var currentDay = 1 + while (currentDay < d) { + var to = currentDay + while (to <= length - d + currentDay) { + var currentJobDifficulty = jobDifficulty[to] + var result = Int.MAX_VALUE + var j = to - 1 + while (j >= currentDay - 1) { + result = minOf(result, minDifficulties[currentDay - 1][j] + currentJobDifficulty) + currentJobDifficulty = maxOf(currentJobDifficulty, jobDifficulty[j]) + j-- + } + minDifficulties[currentDay][to] = result + to++ + } + currentDay++ + } + + return minDifficulties[d - 1][length - 1] + } +} diff --git a/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.py b/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.py new file mode 100644 index 00000000..d70a5720 --- /dev/null +++ b/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.py @@ -0,0 +1,36 @@ +class Solution: + def minDifficulty(self, jobDifficulty, days): + length = len(jobDifficulty) + if days > length: + return -1 + + min_difficulties = [[float("inf")] * length for _ in range(days)] + + max_diff = 0 + i = 0 + while i <= length - days: + max_diff = max(max_diff, jobDifficulty[i]) + min_difficulties[0][i] = max_diff + i += 1 + + current_day = 1 + while current_day < days: + to = current_day + while to <= length - days + current_day: + current_job_difficulty = jobDifficulty[to] + result = float("inf") + j = to - 1 + while j >= current_day - 1: + result = min( + result, + min_difficulties[current_day - 1][j] + current_job_difficulty, + ) + current_job_difficulty = max( + current_job_difficulty, jobDifficulty[j] + ) + j -= 1 + min_difficulties[current_day][to] = result + to += 1 + current_day += 1 + + return min_difficulties[days - 1][length - 1] diff --git a/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.py2 b/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.py2 new file mode 100644 index 00000000..2294ccc2 --- /dev/null +++ b/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.py2 @@ -0,0 +1,36 @@ +class Solution(object): + def minDifficulty(self, jobDifficulty, d): + """ + :type jobDifficulty: List[int] + :type d: int + :rtype: int + """ + length = len(jobDifficulty) + if d > length: + return -1 + + min_difficulties = [[float('inf')] * length for _ in range(d)] + + max_diff = 0 + i = 0 + while i <= length - d: + max_diff = max(max_diff, jobDifficulty[i]) + min_difficulties[0][i] = max_diff + i += 1 + + current_day = 1 + while current_day < d: + to = current_day + while to <= length - d + current_day: + current_job_difficulty = jobDifficulty[to] + result = float('inf') + j = to - 1 + while j >= current_day - 1: + result = min(result, min_difficulties[current_day - 1][j] + current_job_difficulty) + current_job_difficulty = max(current_job_difficulty, jobDifficulty[j]) + j -= 1 + min_difficulties[current_day][to] = result + to += 1 + current_day += 1 + + return min_difficulties[d - 1][length - 1] diff --git a/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.rb b/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.rb new file mode 100644 index 00000000..29a94408 --- /dev/null +++ b/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.rb @@ -0,0 +1,37 @@ +# @param {Integer[]} job_difficulty +# @param {Integer} d +# @return {Integer} +def min_difficulty(job_difficulty, d) + length = job_difficulty.length + return -1 if d > length + + min_difficulties = Array.new(d) { Array.new(length, Float::INFINITY) } + + max_diff = 0 + i = 0 + while i <= length - d + max_diff = [max_diff, job_difficulty[i]].max + min_difficulties[0][i] = max_diff + i += 1 + end + + current_day = 1 + while current_day < d + to = current_day + while to <= length - d + current_day + current_job_difficulty = job_difficulty[to] + result = Float::INFINITY + j = to - 1 + while j >= current_day - 1 + result = [result, min_difficulties[current_day - 1][j] + current_job_difficulty].min + current_job_difficulty = [current_job_difficulty, job_difficulty[j]].max + j -= 1 + end + min_difficulties[current_day][to] = result + to += 1 + end + current_day += 1 + end + + min_difficulties[d - 1][length - 1].to_i +end diff --git a/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.rs b/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.rs new file mode 100644 index 00000000..fb622b78 --- /dev/null +++ b/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.rs @@ -0,0 +1,42 @@ +impl Solution { + pub fn min_difficulty(job_difficulty: Vec, d: i32) -> i32 { + let length = job_difficulty.len(); + let d = d as usize; + if d > length { + return -1; + } + + let mut min_difficulties = vec![vec![i32::MAX; length]; d]; + + let mut max_diff = 0; + let mut i = 0; + while i <= length - d { + max_diff = max_diff.max(job_difficulty[i]); + min_difficulties[0][i] = max_diff; + i += 1; + } + + let mut current_day = 1; + while current_day < d { + let mut to = current_day; + while to <= length - d + current_day { + let mut current_job_difficulty = job_difficulty[to]; + let mut result = i32::MAX; + let mut j = to as i32 - 1; + while j >= (current_day as i32 - 1) { + let prev = min_difficulties[current_day - 1][j as usize]; + if prev != i32::MAX { + result = result.min(prev + current_job_difficulty); + } + current_job_difficulty = current_job_difficulty.max(job_difficulty[j as usize]); + j -= 1; + } + min_difficulties[current_day][to] = result; + to += 1; + } + current_day += 1; + } + + min_difficulties[d - 1][length - 1] + } +} diff --git a/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.swift b/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.swift new file mode 100644 index 00000000..97473be7 --- /dev/null +++ b/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.swift @@ -0,0 +1,40 @@ +class Solution { + func minDifficulty(_ jobDifficulty: [Int], _ d: Int) -> Int { + let length = jobDifficulty.count + if d > length { + return -1 + } + + var minDifficulties = Array(repeating: Array(repeating: Int.max, count: length), count: d) + + var maxDiff = 0 + var i = 0 + while i <= length - d { + maxDiff = max(maxDiff, jobDifficulty[i]) + minDifficulties[0][i] = maxDiff + i += 1 + } + + var currentDay = 1 + while currentDay < d { + var to = currentDay + while to <= length - d + currentDay { + var currentJobDifficulty = jobDifficulty[to] + var result = Int.max + var j = to - 1 + while j >= currentDay - 1 { + if minDifficulties[currentDay - 1][j] != Int.max { + result = min(result, minDifficulties[currentDay - 1][j] + currentJobDifficulty) + } + currentJobDifficulty = max(currentJobDifficulty, jobDifficulty[j]) + j -= 1 + } + minDifficulties[currentDay][to] = result + to += 1 + } + currentDay += 1 + } + + return minDifficulties[d - 1][length - 1] + } +} diff --git a/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.ts b/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.ts new file mode 100644 index 00000000..763093f2 --- /dev/null +++ b/tests/1001-1500/1335. minimum-difficulty-of-a-job-schedule/sol.ts @@ -0,0 +1,41 @@ +function minDifficulty(jobDifficulty: number[], d: number): number { + const length = jobDifficulty.length; + if (d > length) { + return -1; + } + + const minDifficulties: number[][] = Array.from({ length: d }, () => + Array(length).fill(Infinity), + ); + + let maxDiff = 0; + let i = 0; + while (i <= length - d) { + maxDiff = Math.max(maxDiff, jobDifficulty[i]); + minDifficulties[0][i] = maxDiff; + i++; + } + + let currentDay = 1; + while (currentDay < d) { + let to = currentDay; + while (to <= length - d + currentDay) { + let currentJobDifficulty = jobDifficulty[to]; + let result = Infinity; + let j = to - 1; + while (j >= currentDay - 1) { + result = Math.min( + result, + minDifficulties[currentDay - 1][j] + currentJobDifficulty, + ); + currentJobDifficulty = Math.max(currentJobDifficulty, jobDifficulty[j]); + j--; + } + minDifficulties[currentDay][to] = result; + to++; + } + currentDay++; + } + + return minDifficulties[d - 1][length - 1]; +} diff --git a/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/manifest.yaml b/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/manifest.yaml new file mode 100644 index 00000000..26a81e27 --- /dev/null +++ b/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/manifest.yaml @@ -0,0 +1,1559 @@ +entry: + id: 1337 + title: "the-k-weakest-rows-in-a-matrix" + params: + mat: + type: array + items: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().kWeakestRows({mat}, {k})" + rust: "Solution::k_weakest_rows({mat}, {k})" + python3: "Solution().kWeakestRows({mat}, {k})" + python2: "Solution().kWeakestRows({mat}, {k})" + ruby: "k_weakest_rows({mat}, {k})" + java: "new Solution().kWeakestRows({mat}, {k})" + csharp: "new Solution().KWeakestRows({mat}, {k})" + kotlin: "Solution().kWeakestRows({mat}, {k})" + go: "kWeakestRows({mat}, {k})" + dart: "Solution().kWeakestRows({mat}, {k})" + swift: "Solution().kWeakestRows({mat}, {k})" + typescript: "kWeakestRows({mat}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().kWeakestRows(mat, k, {result})" + checker: | + class Checker: + def kWeakestRows(self, mat, k, result): + if not isinstance(result, list) or len(result) != k: + return False + expected = sorted(range(len(mat)), key=lambda i: (sum(mat[i]), i))[:k] + return result == expected + +seed: 1337 + +tests: + - name: "example_one" + in: + mat: + elemType: "int" + value: + - [1, 1, 0, 0, 0] + - [1, 1, 1, 1, 0] + - [1, 0, 0, 0, 0] + - [1, 1, 0, 0, 0] + - [1, 1, 1, 1, 1] + k: 3 + out: [2, 0, 3] + + - name: "example_two" + in: + mat: + elemType: "int" + value: + - [1, 0, 0, 0] + - [1, 1, 1, 1] + - [1, 0, 0, 0] + - [1, 0, 0, 0] + k: 2 + out: [0, 2] + + - name: "minimum_all_zero" + in: + mat: + elemType: "int" + value: + - [0, 0] + - [0, 0] + k: 1 + out: [0] + + - name: "minimum_all_one" + in: + mat: + elemType: "int" + value: + - [1, 1] + - [1, 1] + k: 2 + out: [0, 1] + + - name: "minimum_distinct_strengths" + in: + mat: + elemType: "int" + value: + - [1, 1] + - [0, 0] + k: 1 + out: [1] + + - name: "k_one_tie_after_weaker_row" + in: + mat: + elemType: "int" + value: + - [1, 0, 0] + - [0, 0, 0] + - [1, 0, 0] + k: 1 + out: [1] + + - name: "k_all_unsorted_input" + in: + mat: + elemType: "int" + value: + - [1, 1, 0] + - [0, 0, 0] + - [1, 1, 1] + - [1, 0, 0] + k: 4 + out: [1, 3, 0, 2] + + - name: "every_possible_count" + in: + mat: + elemType: "int" + value: + - [1, 1, 1, 1] + - [1, 1, 0, 0] + - [0, 0, 0, 0] + - [1, 1, 1, 0] + - [1, 0, 0, 0] + k: 5 + out: [2, 4, 1, 3, 0] + + - name: "equal_groups_cross_cutoff" + in: + mat: + elemType: "int" + value: + - [1, 1, 0, 0] + - [1, 0, 0, 0] + - [1, 0, 0, 0] + - [1, 1, 0, 0] + - [1, 0, 0, 0] + k: 4 + out: [1, 2, 4, 0] + + - name: "zeros_at_late_indices" + in: + mat: + elemType: "int" + value: + - [1, 1, 1] + - [1, 0, 0] + - [1, 1, 0] + - [0, 0, 0] + - [1, 0, 0] + - [0, 0, 0] + k: 4 + out: [3, 5, 1, 4] + + - name: "wide_rows_with_midpoint_counts" + in: + mat: + elemType: "int" + value: + - [1, 1, 1, 1, 1, 0, 0, 0] + - [1, 1, 0, 0, 0, 0, 0, 0] + - [1, 1, 1, 1, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0] + k: 3 + out: [3, 1, 2] + + - name: "tall_narrow_matrix" + in: + mat: + elemType: "int" + value: + - [1, 0] + - [1, 1] + - [0, 0] + - [1, 0] + - [1, 1] + - [0, 0] + - [1, 0] + k: 5 + out: [2, 5, 0, 3, 6] + + - name: "all_rows_same_middle_strength" + in: + mat: + elemType: "int" + value: + - [1, 1, 0, 0, 0] + - [1, 1, 0, 0, 0] + - [1, 1, 0, 0, 0] + - [1, 1, 0, 0, 0] + k: 3 + out: [0, 1, 2] + + - name: "strongest_rows_excluded" + in: + mat: + elemType: "int" + value: + - [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] + k: 4 + out: [4, 3, 2, 1] + + - name: "interleaved_strength_groups" + in: + mat: + elemType: "int" + value: + - [1, 1, 0, 0] + - [0, 0, 0, 0] + - [1, 1, 1, 0] + - [1, 0, 0, 0] + - [0, 0, 0, 0] + - [1, 1, 0, 0] + k: 5 + out: [1, 4, 3, 0, 5] + + - name: "partial_final_tie_group" + in: + mat: + elemType: "int" + value: + - [1, 1, 1, 0] + - [1, 0, 0, 0] + - [1, 1, 0, 0] + - [1, 0, 0, 0] + - [1, 1, 0, 0] + - [0, 0, 0, 0] + k: 4 + out: [5, 1, 3, 2] + + - name: "two_column_all_categories" + in: + mat: + elemType: "int" + value: + - [1, 1] + - [1, 0] + - [0, 0] + - [1, 1] + - [0, 0] + - [1, 0] + k: 6 + out: [2, 4, 1, 5, 0, 3] + + - name: "six_column_boundary_counts" + in: + mat: + elemType: "int" + value: + - [1, 1, 1, 1, 1, 0] + - [1, 1, 1, 1, 1, 1] + - [1, 0, 0, 0, 0, 0] + - [1, 1, 1, 0, 0, 0] + - [0, 0, 0, 0, 0, 0] + k: 3 + out: [4, 2, 3] + + - name: "repeated_weakest_before_earlier_stronger" + in: + mat: + elemType: "int" + value: + - [1, 1, 1] + - [0, 0, 0] + - [0, 0, 0] + - [1, 0, 0] + - [1, 0, 0] + k: 4 + out: [1, 2, 3, 4] + + - name: "selection_ends_before_full_group" + in: + mat: + elemType: "int" + value: + - [1, 1, 0] + - [1, 0, 0] + - [1, 0, 0] + - [1, 0, 0] + - [0, 0, 0] + - [1, 1, 1] + k: 3 + out: [4, 1, 2] + + - name: "nine_rows_mixed_order" + in: + mat: + elemType: "int" + value: + - [1, 1, 1, 1] + - [1, 0, 0, 0] + - [0, 0, 0, 0] + - [1, 1, 0, 0] + - [1, 0, 0, 0] + - [1, 1, 1, 0] + - [0, 0, 0, 0] + - [1, 1, 0, 0] + - [1, 1, 1, 1] + k: 7 + out: [2, 6, 1, 4, 3, 7, 5] + + - name: "ten_columns_near_full" + in: + mat: + elemType: "int" + value: + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 0] + - [1, 1, 1, 1, 1, 1, 1, 1, 0, 0] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 0, 0, 0] + k: 2 + out: [3, 1] + + - name: "zero_and_full_rows_tie_indices" + in: + mat: + elemType: "int" + value: + - [1, 1, 1, 1] + - [0, 0, 0, 0] + - [1, 1, 1, 1] + - [0, 0, 0, 0] + - [1, 1, 1, 1] + k: 4 + out: [1, 3, 0, 2] + + - name: "descending_input_strengths" + in: + mat: + elemType: "int" + value: + - [1, 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, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0] + k: 7 + out: [6, 5, 4, 3, 2, 1, 0] + + - name: "alternating_tier_positions" + in: + mat: + elemType: "int" + value: + - [1, 1, 0, 0, 0] + - [0, 0, 0, 0, 0] + - [1, 1, 1, 1, 0] + - [1, 0, 0, 0, 0] + - [1, 1, 0, 0, 0] + - [0, 0, 0, 0, 0] + - [1, 1, 1, 0, 0] + - [1, 0, 0, 0, 0] + k: 6 + out: [1, 5, 3, 7, 0, 4] + + - name: "four_equal_groups" + in: + mat: + elemType: "int" + value: + - [1, 1, 1, 0] + - [0, 0, 0, 0] + - [1, 0, 0, 0] + - [1, 1, 0, 0] + - [0, 0, 0, 0] + - [1, 0, 0, 0] + - [1, 1, 0, 0] + - [1, 1, 1, 0] + k: 8 + out: [1, 4, 2, 5, 3, 6, 0, 7] + + - name: "large_width_two_rows" + 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, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 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, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 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: 2 + out: [0, 1] + + - name: "large_width_equal_ties" + 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, + ] + - [ + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 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, + ] + k: 2 + out: [0, 2] + + - name: "large_height_grouped_strengths" + 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, 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] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + k: 45 + out: + [ + 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, + ] + + - name: "large_height_ties_after_late_weakest" + 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, 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] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + k: 60 + out: + [ + 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, + 20, + 21, + 22, + ] + + - name: "large_height_all_equal" + in: + mat: + elemType: "int" + value: + - [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] + - [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] + - [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] + - [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: 98 + 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, + 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, + ] + + - name: "two_zero_rows_after_strong_rows" + in: + mat: + elemType: "int" + value: + - [1, 1, 1] + - [1, 1, 0] + - [0, 0, 0] + - [0, 0, 0] + k: 2 + out: [2, 3] + + - name: "only_weakest_tie_is_selected" + in: + mat: + elemType: "int" + value: + - [1, 1, 1, 1] + - [1, 0, 0, 0] + - [1, 0, 0, 0] + - [1, 1, 0, 0] + k: 2 + out: [1, 2] + + - name: "full_selection_preserves_all_tiers" + in: + mat: + elemType: "int" + value: + - [1, 1, 0, 0, 0] + - [1, 1, 1, 1, 1] + - [0, 0, 0, 0, 0] + - [1, 0, 0, 0, 0] + - [1, 1, 1, 0, 0] + k: 5 + out: [2, 3, 0, 4, 1] + + - name: "late_index_wins_only_after_strength" + in: + mat: + elemType: "int" + value: + - [1, 1, 1, 1] + - [1, 1, 0, 0] + - [1, 1, 1, 0] + - [1, 0, 0, 0] + - [0, 0, 0, 0] + k: 5 + out: [4, 3, 1, 2, 0] + + - name: "one_row_per_strength_with_ties" + in: + mat: + elemType: "int" + value: + - [1, 1, 1, 1, 0, 0] + - [1, 1, 0, 0, 0, 0] + - [1, 1, 0, 0, 0, 0] + - [1, 1, 1, 0, 0, 0] + - [0, 0, 0, 0, 0, 0] + - [1, 0, 0, 0, 0, 0] + k: 5 + out: [4, 5, 1, 2, 3] + + - name: "full_rows_only_at_early_indices" + in: + mat: + elemType: "int" + value: + - [1, 1, 1] + - [1, 1, 1] + - [1, 1, 0] + - [1, 1, 0] + - [1, 0, 0] + k: 3 + out: [4, 2, 3] + + - name: "narrow_zero_one_two_permutation" + in: + mat: + elemType: "int" + value: + - [1, 0] + - [0, 0] + - [1, 1] + - [1, 0] + - [0, 0] + - [1, 1] + - [1, 0] + - [0, 0] + k: 7 + out: [1, 4, 7, 0, 3, 6, 2] + + - name: "wide_cutoff_between_counts" + in: + mat: + elemType: "int" + value: + - [1, 1, 1, 1, 1, 1, 1, 0, 0] + - [1, 1, 0, 0, 0, 0, 0, 0, 0] + - [1, 1, 1, 1, 0, 0, 0, 0, 0] + - [1, 1, 1, 1, 1, 1, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0] + k: 4 + out: [4, 1, 2, 3] + + - name: "two_equal_weak_groups" + in: + mat: + elemType: "int" + value: + - [1, 1, 1, 1] + - [1, 0, 0, 0] + - [1, 1, 0, 0] + - [0, 0, 0, 0] + - [1, 0, 0, 0] + - [0, 0, 0, 0] + k: 5 + out: [3, 5, 1, 4, 2] diff --git a/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.cpp b/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.cpp new file mode 100644 index 00000000..8c2dcac9 --- /dev/null +++ b/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + vector kWeakestRows(vector>& mat, int k) { + int n = mat.size(); + vector> soldiers; + for (int i = 0; i < n; i++) { + int sum = 0; + for (int val : mat[i]) { + sum += val; + } + soldiers.push_back({sum, i}); + } + sort(soldiers.begin(), soldiers.end()); + vector result; + for (int i = 0; i < k; i++) { + result.push_back(soldiers[i].second); + } + return result; + } +}; diff --git a/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.cs b/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.cs new file mode 100644 index 00000000..031b9ea1 --- /dev/null +++ b/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.cs @@ -0,0 +1,14 @@ +public class Solution { + public int[] KWeakestRows(int[][] mat, int k) { + int n = mat.Length; + var dict = new Dictionary(); + for (int i = 0; i < n; i++) { + int sum = 0; + foreach (int val in mat[i]) { + sum += val; + } + dict[i] = sum; + } + return dict.OrderBy(x => x.Value).ThenBy(x => x.Key).Take(k).Select(x => x.Key).ToArray(); + } +} diff --git a/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.dart b/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.dart new file mode 100644 index 00000000..017da09e --- /dev/null +++ b/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.dart @@ -0,0 +1,12 @@ +class Solution { + List kWeakestRows(List> mat, int k) { + Map d = {}; + for (int i = 0; i < mat.length; i++) { + int sum = mat[i].fold(0, (prev, val) => prev + val); + d[i] = sum; + } + var entries = d.entries.toList() + ..sort((a, b) => a.value == b.value ? a.key.compareTo(b.key) : a.value.compareTo(b.value)); + return entries.take(k).map((e) => e.key).toList(); + } +} diff --git a/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.go b/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.go new file mode 100644 index 00000000..aba09604 --- /dev/null +++ b/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.go @@ -0,0 +1,26 @@ +func kWeakestRows(mat [][]int, k int) []int { + n := len(mat) + type pair struct { + idx int + sum int + } + pairs := make([]pair, n) + for i := 0; i < n; i++ { + sum := 0 + for _, v := range mat[i] { + sum += v + } + pairs[i] = pair{i, sum} + } + sort.Slice(pairs, func(a, b int) bool { + if pairs[a].sum == pairs[b].sum { + return pairs[a].idx < pairs[b].idx + } + return pairs[a].sum < pairs[b].sum + }) + result := make([]int, k) + for i := 0; i < k; i++ { + result[i] = pairs[i].idx + } + return result +} diff --git a/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.java b/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.java new file mode 100644 index 00000000..c0f191c5 --- /dev/null +++ b/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.java @@ -0,0 +1,20 @@ +class Solution { + public int[] kWeakestRows(int[][] mat, int k) { + int n = mat.length; + int[][] soldiers = new int[n][2]; + for (int i = 0; i < n; i++) { + int sum = 0; + for (int val : mat[i]) { + sum += val; + } + soldiers[i][0] = sum; + soldiers[i][1] = i; + } + Arrays.sort(soldiers, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); + int[] result = new int[k]; + for (int i = 0; i < k; i++) { + result[i] = soldiers[i][1]; + } + return result; + } +} diff --git a/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.kt b/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.kt new file mode 100644 index 00000000..d7af7562 --- /dev/null +++ b/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.kt @@ -0,0 +1,12 @@ +class Solution { + fun kWeakestRows(mat: Array, k: Int): IntArray { + val d = mutableMapOf() + for (i in mat.indices) { + d[i] = mat[i].sum() + } + return d.entries.sortedWith(compareBy({ it.value }, { it.key })) + .take(k) + .map { it.key } + .toIntArray() + } +} diff --git a/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.py b/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.py new file mode 100644 index 00000000..66f0aab4 --- /dev/null +++ b/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.py @@ -0,0 +1,10 @@ +from typing import List + + +class Solution(object): + def kWeakestRows(self, mat, k): + d = {} + n = len(mat) + for i in range(n): + d[i] = sum(mat[i]) + return sorted(d, key=d.get)[:k] diff --git a/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.py2 b/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.py2 new file mode 100644 index 00000000..806dfa16 --- /dev/null +++ b/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.py2 @@ -0,0 +1,7 @@ +class Solution(object): + def kWeakestRows(self, mat, k): + d = {} + n = len(mat) + for i in range(n): + d[i] = sum(mat[i]) + return sorted(d,key = d.get)[:k] diff --git a/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.rb b/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.rb new file mode 100644 index 00000000..8893d1aa --- /dev/null +++ b/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.rb @@ -0,0 +1,10 @@ +# @param {Integer[][]} mat +# @param {Integer} k +# @return {Integer[]} +def k_weakest_rows(mat, k) + d = {} + mat.each_with_index do |row, i| + d[i] = row.sum + end + d.keys.sort_by { |i| d[i] }.first(k) +end diff --git a/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.rs b/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.rs new file mode 100644 index 00000000..15078bd1 --- /dev/null +++ b/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.rs @@ -0,0 +1,11 @@ +impl Solution { + pub fn k_weakest_rows(mat: Vec>, k: i32) -> Vec { + let mut pairs: Vec<(i32, usize)> = mat + .iter() + .enumerate() + .map(|(i, row)| (row.iter().sum(), i)) + .collect(); + pairs.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1))); + pairs.iter().take(k as usize).map(|&(_, i)| i as i32).collect() + } +} diff --git a/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.swift b/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.swift new file mode 100644 index 00000000..82405abe --- /dev/null +++ b/tests/1001-1500/1337. the-k-weakest-rows-in-a-matrix/sol.swift @@ -0,0 +1,12 @@ +class Solution { + func kWeakestRows(_ mat: [[Int]], _ k: Int) -> [Int] { + var dict = [Int: Int]() + for i in 0.. a + b, 0); + } + return Object.keys(d) + .map(Number) + .sort((a, b) => (d[a] === d[b] ? a - b : d[a] - d[b])) + .slice(0, k); +} diff --git a/tests/1001-1500/1338. reduce-array-size-to-the-half/manifest.yaml b/tests/1001-1500/1338. reduce-array-size-to-the-half/manifest.yaml new file mode 100644 index 00000000..d8e3322a --- /dev/null +++ b/tests/1001-1500/1338. reduce-array-size-to-the-half/manifest.yaml @@ -0,0 +1,299 @@ +entry: + id: 1338 + title: "reduce-array-size-to-the-half" + params: + arr: + type: array + items: + type: int + call: + cpp: "Solution().minSetSize({arr})" + rust: "Solution::min_set_size({arr})" + python3: "Solution().minSetSize({arr})" + python2: "Solution().minSetSize({arr})" + ruby: "min_set_size({arr})" + java: "new Solution().minSetSize({arr})" + csharp: "new Solution().MinSetSize({arr})" + kotlin: "Solution().minSetSize({arr})" + go: "minSetSize({arr})" + dart: "Solution().minSetSize({arr})" + swift: "Solution().minSetSize({arr})" + typescript: "minSetSize({arr})" + +judge: + type: "exact" + +limits: + time_ms: 2500 + memory_mb: 256 + +oracle: + python3: + call: "Checker().minSetSize(arr, {result})" + checker: | + class Checker: + def minSetSize(self, arr, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + frequencies = {} + for value in arr: + frequencies[value] = frequencies.get(value, 0) + 1 + removed = 0 + for size, count in enumerate(sorted(frequencies.values(), reverse=True), 1): + removed += count + if removed >= len(arr) // 2: + return result == size + return False + +seed: 1338 + +tests: + - name: "example-one" + in: + arr: [3, 3, 3, 3, 5, 5, 5, 2, 2, 7] + out: 2 + - name: "example-two" + in: + arr: [7, 7, 7, 7, 7, 7] + out: 1 + - name: "two-equal" + in: + arr: [1, 1] + out: 1 + - name: "two-distinct" + in: + arr: [1, 2] + out: 1 + - name: "all-equal-four" + in: + arr: [4, 4, 4, 4] + out: 1 + - name: "all-distinct-four" + in: + arr: [1, 2, 3, 4] + out: 2 + - name: "balanced-pairs" + in: + arr: [1, 1, 2, 2, 3, 3, 4, 4] + out: 2 + - name: "dominant-exactly-half" + in: + arr: [1, 1, 1, 1, 1, 2, 3, 4, 5, 6] + out: 1 + - name: "dominant-over-half" + in: + arr: [1, 1, 1, 1, 1, 1, 2, 3, 4, 5] + out: 1 + - name: "two-large-groups" + in: + arr: [1, 1, 1, 1, 2, 2, 2, 2] + out: 1 + - name: "three-required-by-frequencies" + in: + arr: [1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 5] + out: 2 + - name: "odd-frequency-groups" + in: + arr: [1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 4, 4] + out: 2 + - name: "minimum-value-boundary" + in: + arr: [1, 1, 1, 1, 2, 2, 3, 4] + out: 1 + - name: "maximum-value-boundary" + in: + arr: [100000, 100000, 100000, 100000, 99999, 99999, 1, 1] + out: 1 + - name: "alternating-two-values" + in: + arr: [5, 6, 5, 6, 5, 6, 5, 6] + out: 1 + - name: "one-dominates" + in: + arr: [9, 9, 9, 9, 9, 9, 9, 2, 3, 4, 5, 6] + out: 1 + - name: "one-pair-many-singletons" + in: + arr: [1, 1, 2, 3, 4, 5, 6, 7, 8, 9] + out: 4 + - name: "four-equal-groups" + in: + arr: [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4] + out: 2 + - name: "large-first-group" + in: + arr: [1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 5] + out: 1 + - name: "large-last-group" + in: + arr: [1, 2, 3, 4, 5, 9, 9, 9, 9, 9, 9, 9] + out: 1 + - name: "sixteen-distinct" + in: + arr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] + out: 8 + - name: "sixteen-equal" + in: + arr: [8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8] + out: 1 + - name: "quarter-sized-groups" + in: + arr: [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4] + out: 2 + - name: "uneven-distribution" + in: + arr: [1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 4, 5, 6, 7] + out: 2 + - name: "mixed-value-boundaries" + in: + arr: [1, 1, 1, 100000, 100000, 99999, 99998, 99997] + out: 2 + - name: "six-repeated-pairs" + in: + arr: [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6] + out: 3 + - name: "two-thirds-dominant" + in: + arr: [7, 7, 7, 7, 7, 7, 7, 7, 1, 2, 3, 4] + out: 1 + - name: "small-frequency-tail" + in: + arr: [1, 1, 1, 1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9] + out: 2 + - name: "four-balanced-large-groups" + in: + arr: + [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4] + out: 2 + - name: "half-size-dominant" + in: + arr: + [ + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + ] + out: 1 + - name: "two-largest-needed" + in: + arr: [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 4, 4, 5, 5] + out: 2 + - name: "three-largest-needed" + in: + arr: [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6] + out: 3 + - name: "four-largest-needed" + in: + arr: [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8] + out: 4 + - name: "five-pairs-needed" + in: + arr: [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9] + out: 5 + - name: "generated-maximum-domain" + seed: 101 + in: + arr: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 100000 + elemType: "int" + distinct: false + sorted: false + - name: "generated-tiny-domain" + seed: 202 + in: + arr: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 2 + elemType: "int" + distinct: false + sorted: false + - name: "generated-narrow-domain" + seed: 303 + in: + arr: + gen: "array" + len: 80000 + of: + gen: "int" + min: 1 + max: 10 + elemType: "int" + distinct: false + sorted: false + - name: "generated-medium-domain" + seed: 404 + in: + arr: + gen: "array" + len: 75000 + of: + gen: "int" + min: 1 + max: 1000 + elemType: "int" + distinct: false + sorted: false + - name: "generated-wide-domain" + seed: 505 + in: + arr: + gen: "array" + len: 60000 + of: + gen: "int" + min: 1 + max: 50000 + elemType: "int" + distinct: false + sorted: false + - name: "generated-near-unique-domain" + seed: 606 + in: + arr: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 100000 + elemType: "int" + distinct: false + sorted: false diff --git a/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.cpp b/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.cpp new file mode 100644 index 00000000..b4bedc7d --- /dev/null +++ b/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int minSetSize(vector& arr) { + unordered_map freq; + for (int num : arr) { + freq[num]++; + } + + vector counts; + for (auto& p : freq) { + counts.push_back(p.second); + } + sort(counts.rbegin(), counts.rend()); + + int sumRemoved = 0; + int minSetSize = 0; + for (int count : counts) { + sumRemoved += count; + minSetSize++; + if (sumRemoved >= arr.size() / 2) { + return minSetSize; + } + } + return minSetSize; + } +}; diff --git a/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.cs b/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.cs new file mode 100644 index 00000000..2f355d11 --- /dev/null +++ b/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.cs @@ -0,0 +1,26 @@ +public class Solution { + public int MinSetSize(int[] arr) { + Dictionary freq = new Dictionary(); + foreach (int num in arr) { + if (freq.ContainsKey(num)) { + freq[num]++; + } else { + freq[num] = 1; + } + } + + List counts = new List(freq.Values); + counts.Sort((a, b) => b.CompareTo(a)); + + int sumRemoved = 0; + int minSetSize = 0; + foreach (int count in counts) { + sumRemoved += count; + minSetSize++; + if (sumRemoved >= arr.Length / 2) { + return minSetSize; + } + } + return minSetSize; + } +} diff --git a/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.dart b/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.dart new file mode 100644 index 00000000..d2cde1ed --- /dev/null +++ b/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.dart @@ -0,0 +1,22 @@ +class Solution { + int minSetSize(List arr) { + final freq = {}; + for (final num in arr) { + freq[num] = (freq[num] ?? 0) + 1; + } + + final counts = freq.values.toList(); + counts.sort((a, b) => b.compareTo(a)); + + int sumRemoved = 0; + int minSetSize = 0; + for (final count in counts) { + sumRemoved += count; + minSetSize++; + if (sumRemoved >= arr.length ~/ 2) { + return minSetSize; + } + } + return minSetSize; + } +} diff --git a/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.go b/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.go new file mode 100644 index 00000000..fe5e5a18 --- /dev/null +++ b/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.go @@ -0,0 +1,25 @@ +func minSetSize(arr []int) int { + freq := make(map[int]int) + for _, num := range arr { + freq[num]++ + } + + counts := make([]int, 0, len(freq)) + for _, v := range freq { + counts = append(counts, v) + } + sort.Slice(counts, func(i, j int) bool { + return counts[i] > counts[j] + }) + + sumRemoved := 0 + minSetSize := 0 + for _, count := range counts { + sumRemoved += count + minSetSize++ + if sumRemoved >= len(arr)/2 { + return minSetSize + } + } + return minSetSize +} diff --git a/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.java b/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.java new file mode 100644 index 00000000..7de3a986 --- /dev/null +++ b/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.java @@ -0,0 +1,22 @@ +class Solution { + public int minSetSize(int[] arr) { + Map freq = new HashMap<>(); + for (int num : arr) { + freq.put(num, freq.getOrDefault(num, 0) + 1); + } + + List counts = new ArrayList<>(freq.values()); + counts.sort(Collections.reverseOrder()); + + int sumRemoved = 0; + int minSetSize = 0; + for (int count : counts) { + sumRemoved += count; + minSetSize++; + if (sumRemoved >= arr.length / 2) { + return minSetSize; + } + } + return minSetSize; + } +} diff --git a/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.kt b/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.kt new file mode 100644 index 00000000..d2c9f507 --- /dev/null +++ b/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.kt @@ -0,0 +1,21 @@ +class Solution { + fun minSetSize(arr: IntArray): Int { + val freq = mutableMapOf() + for (num in arr) { + freq[num] = freq.getOrDefault(num, 0) + 1 + } + + val counts = freq.values.sortedDescending() + + var sumRemoved = 0 + var minSetSize = 0 + for (count in counts) { + sumRemoved += count + minSetSize++ + if (sumRemoved >= arr.size / 2) { + return minSetSize + } + } + return minSetSize + } +} diff --git a/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.py b/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.py new file mode 100644 index 00000000..1287c3b0 --- /dev/null +++ b/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.py @@ -0,0 +1,18 @@ +import heapq + + +class Solution: + def minSetSize(self, arr): + freq = {} + for num in arr: + freq[num] = freq.get(num, 0) + 1 + + maxHeap = [-val for val in freq.values()] + heapq.heapify(maxHeap) + + sumRemoved = 0 + minSetSize = 0 + while sumRemoved < len(arr) // 2: + sumRemoved += -heapq.heappop(maxHeap) + minSetSize += 1 + return minSetSize diff --git a/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.py2 b/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.py2 new file mode 100644 index 00000000..19522cbd --- /dev/null +++ b/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.py2 @@ -0,0 +1,20 @@ +class Solution(object): + def minSetSize(self, arr): + """ + :type arr: List[int] + :rtype: int + """ + freq = {} + for num in arr: + freq[num] = freq.get(num, 0) + 1 + + counts = sorted(freq.values(), reverse=True) + + sum_removed = 0 + min_set_size = 0 + for count in counts: + sum_removed += count + min_set_size += 1 + if sum_removed >= len(arr) // 2: + return min_set_size + return min_set_size diff --git a/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.rb b/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.rb new file mode 100644 index 00000000..5316b5d1 --- /dev/null +++ b/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.rb @@ -0,0 +1,17 @@ +# @param {Integer[]} arr +# @return {Integer} +def min_set_size(arr) + freq = Hash.new(0) + arr.each { |num| freq[num] += 1 } + + counts = freq.values.sort.reverse + + sum_removed = 0 + min_set_size = 0 + counts.each do |count| + sum_removed += count + min_set_size += 1 + return min_set_size if sum_removed >= arr.length / 2 + end + min_set_size +end diff --git a/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.rs b/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.rs new file mode 100644 index 00000000..eee76e40 --- /dev/null +++ b/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.rs @@ -0,0 +1,23 @@ +impl Solution { + pub fn min_set_size(arr: Vec) -> i32 { + use std::collections::HashMap; + let mut freq: HashMap = HashMap::new(); + for num in &arr { + *freq.entry(*num).or_insert(0) += 1; + } + + let mut counts: Vec = freq.values().cloned().collect(); + counts.sort_by(|a, b| b.cmp(a)); + + let mut sum_removed = 0; + let mut min_set_size = 0; + for count in counts { + sum_removed += count; + min_set_size += 1; + if sum_removed >= (arr.len() / 2) as i32 { + return min_set_size; + } + } + min_set_size + } +} diff --git a/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.swift b/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.swift new file mode 100644 index 00000000..ac383fba --- /dev/null +++ b/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.swift @@ -0,0 +1,21 @@ +class Solution { + func minSetSize(_ arr: [Int]) -> Int { + var freq: [Int: Int] = [:] + for num in arr { + freq[num, default: 0] += 1 + } + + let counts = freq.values.sorted(by: >) + + var sumRemoved = 0 + var minSetSize = 0 + for count in counts { + sumRemoved += count + minSetSize += 1 + if sumRemoved >= arr.count / 2 { + return minSetSize + } + } + return minSetSize + } +} diff --git a/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.ts b/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.ts new file mode 100644 index 00000000..1380f022 --- /dev/null +++ b/tests/1001-1500/1338. reduce-array-size-to-the-half/sol.ts @@ -0,0 +1,19 @@ +function minSetSize(arr: number[]): number { + const freq: Map = new Map(); + for (const num of arr) { + freq.set(num, (freq.get(num) || 0) + 1); + } + + const counts = Array.from(freq.values()).sort((a, b) => b - a); + + let sumRemoved = 0; + let minSetSize = 0; + for (const count of counts) { + sumRemoved += count; + minSetSize++; + if (sumRemoved >= Math.floor(arr.length / 2)) { + return minSetSize; + } + } + return minSetSize; +} diff --git a/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/manifest.yaml b/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/manifest.yaml new file mode 100644 index 00000000..3e7bc077 --- /dev/null +++ b/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/manifest.yaml @@ -0,0 +1,547 @@ +entry: + id: 1339 + title: "maximum-product-of-splitted-binary-tree" + params: + root: + type: tree_node + call: + cpp: "Solution().maxProduct({root})" + rust: "Solution::max_product({root})" + python3: "Solution().maxProduct({root})" + python2: "Solution().maxProduct({root})" + ruby: "max_product({root})" + java: "new Solution().maxProduct({root})" + csharp: "new Solution().MaxProduct({root})" + kotlin: "Solution().maxProduct({root})" + go: "maxProduct({root})" + dart: "Solution().maxProduct({root})" + swift: "Solution().maxProduct({root})" + typescript: "maxProduct({root})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 300 + +oracle: + python3: + call: "Checker().maxProduct(root, {result})" + checker: | + class Checker: + def maxProduct(self, root, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + nodes = [] + queue = [] + if not root or root[0] is None: + return False + nodes.append([root[0], None, None]) + queue.append(0) + cursor = 1 + for parent in queue: + for child_slot in (1, 2): + if cursor == len(root): + break + value = root[cursor] + cursor += 1 + if value is not None: + nodes.append([value, None, None]) + child = len(nodes) - 1 + nodes[parent][child_slot] = child + queue.append(child) + sums = [0] * len(nodes) + for index in range(len(nodes) - 1, -1, -1): + value, left, right = nodes[index] + sums[index] = value + (sums[left] if left is not None else 0) + (sums[right] if right is not None else 0) + total = sums[0] + return result == max(subtotal * (total - subtotal) for subtotal in sums) % 1000000007 + +seed: 133900 + +tests: + - name: "example_one" + in: + root: [1, 2, 3, 4, 5, 6] + out: 110 + - name: "example_two" + in: + root: [1, null, 2, 3, 4, null, null, 5, 6] + out: 90 + - name: "two_nodes_equal" + in: + root: [1, 1] + out: 1 + - name: "two_nodes_unequal" + in: + root: [5, 2] + out: 10 + - name: "three_balanced" + in: + root: [1, 2, 3] + out: 9 + - name: "three_left_chain" + in: + root: [1, 2, null, 3] + out: 9 + - name: "three_right_chain" + in: + root: [1, null, 2, null, 3] + out: 9 + - name: "all_ones_seven" + in: + root: [1, 1, 1, 1, 1, 1, 1] + out: 12 + - name: "weighted_balanced" + in: + root: [10, 2, 3, 4, 5, 6, 7] + out: 336 + - name: "large_root" + in: + root: [10000, 1, 1] + out: 10001 + - name: "large_leaves" + in: + root: [1, 10000, 10000] + out: 100010000 + - name: "left_skewed_four" + in: + root: [4, 3, null, 2, null, 1] + out: 24 + - name: "right_skewed_four" + in: + root: [1, null, 2, null, 3, null, 4] + out: 24 + - name: "balanced_seven" + in: + root: [4, 2, 6, 1, 3, 5, 7] + out: 180 + - name: "balanced_fifteen" + in: + root: [8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15] + out: 3276 + - name: "mixed_values" + in: + root: [10, 5, 15, 2, 7, 12, 20] + out: 1128 + - name: "heavy_left_subtree" + in: + root: [10, 8, 1, 6, 7] + out: 231 + - name: "heavy_right_subtree" + in: + root: [10, 1, 8, null, null, 6, 7] + out: 231 + - name: "deep_left_chain" + in: + root: [6, 5, null, 4, null, 3, null, 2, null, 1] + out: 110 + - name: "deep_right_chain" + in: + root: [1, null, 2, null, 3, null, 4, null, 5, null, 6] + out: 110 + - name: "two_level_values" + in: + root: [5, 1, 9, 2, 3, 8, 10] + out: 297 + - name: "unbalanced_right" + in: + root: [2, 1, 8, null, null, 5, 9, 4, 6] + out: 300 + - name: "alternating_chain" + in: + root: [10, 5, null, null, 7, null, 8] + out: 225 + - name: "one_heavy_leaf" + in: + root: [2, 1, 100] + out: 300 + - name: "all_large_values" + in: + root: [10000, 10000, 10000, 10000, 10000, 10000, 10000] + out: 199999993 + - name: "large_balanced" + in: + root: [16, 8, 24, 4, 12, 20, 28, 2, 6, 10, 14, 18, 22, 26, 30] + out: 13104 + - name: "small_values" + in: + root: [1, 1, 2, 1, 1, 1, 1] + out: 16 + - name: "root_dominates" + in: + root: [10000, 1, 1, 1, 1, 1, 1] + out: 30009 + - name: "leaf_dominates" + in: + root: [1, 10000, 10000, 10000, 10000] + out: 300030000 + - name: "ten_node_tree" + in: + root: [10, 5, 15, 2, 7, 12, 20, 1, 3, 6] + out: 1598 + - name: "dense_weighted" + in: + root: [20, 10, 30, 5, 15, 25, 35, 2, 7, 12, 17, 22, 27, 32, 37] + out: 19968 + - name: "left_branch_near_half" + in: + root: [1, 2, 3, 4, 5] + out: 50 + - name: "two_shallow_branches" + in: + root: [100, 1, 1, 1, null, null, 1] + out: 204 + - name: "equal_half_subtree" + in: + root: [1, 4, 2, 8, 1, 3, 9] + out: 196 + - name: "stress_complete_fifteen_ones" + in: + root: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + out: 56 + - name: "stress_complete_thirty_one_ones" + in: + root: + [ + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 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: 240 + - name: "stress_complete_sixty_three_ones" + in: + root: + [ + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 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: 992 + - name: "stress_complete_one_twenty_six_ones" + in: + root: + [ + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 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: 3969 + - name: "stress_complete_thirty_one_maximum" + in: + root: + [ + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + ] + out: 999999839 + - name: "stress_complete_sixty_three_maximum" + in: + root: + [ + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + 10000, + ] + out: 199999307 diff --git a/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.cpp b/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.cpp new file mode 100644 index 00000000..5889d3e9 --- /dev/null +++ b/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.cpp @@ -0,0 +1,46 @@ +/** + * 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: + int maxProduct(TreeNode* root) { + const int MOD = 1'000'000'007; + vector nodes; + stack st; + st.push(root); + + while (!st.empty()) { + TreeNode* node = st.top(); + st.pop(); + if (node) { + nodes.push_back(node); + st.push(node->left); + st.push(node->right); + } + } + + unordered_map sums; + for (auto it = nodes.rbegin(); it != nodes.rend(); ++it) { + TreeNode* node = *it; + long long sub = node->val; + if (node->left) sub += sums[node->left]; + if (node->right) sub += sums[node->right]; + sums[node] = sub; + } + + long long total = sums[root]; + long long best = 0; + for (auto& p : sums) { + best = max(best, p.second * (total - p.second)); + } + return best % MOD; + } +}; diff --git a/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.cs b/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.cs new file mode 100644 index 00000000..f4f0a8e5 --- /dev/null +++ b/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.cs @@ -0,0 +1,46 @@ +/** + * 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 MaxProduct(TreeNode root) { + const int MOD = 1_000_000_007; + var nodes = new List(); + var stack = new Stack(); + stack.Push(root); + + while (stack.Count > 0) { + TreeNode node = stack.Pop(); + if (node != null) { + nodes.Add(node); + stack.Push(node.left); + stack.Push(node.right); + } + } + + var sums = new Dictionary(); + for (int i = nodes.Count - 1; i >= 0; i--) { + TreeNode node = nodes[i]; + long sub = node.val; + if (node.left != null) sub += sums[node.left]; + if (node.right != null) sub += sums[node.right]; + sums[node] = sub; + } + + long total = sums[root]; + long best = 0; + foreach (long sub in sums.Values) { + best = Math.Max(best, sub * (total - sub)); + } + return (int)(best % MOD); + } +} diff --git a/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.dart b/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.dart new file mode 100644 index 00000000..2d36aa7f --- /dev/null +++ b/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.dart @@ -0,0 +1,37 @@ +/** + * 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 maxProduct(TreeNode? root) { + const mod = 1000000007; + final nodes = []; + final stack = [root]; + + while (stack.isNotEmpty) { + final node = stack.removeLast(); + if (node != null) { + nodes.add(node); + stack.add(node.left); + stack.add(node.right); + } + } + + final sums = {}; + for (final node in nodes.reversed) { + sums[node] = node.val + (sums[node.left] ?? 0) + (sums[node.right] ?? 0); + } + + final total = sums[root]!; + int best = 0; + for (final sub in sums.values) { + best = best > sub * (total - sub) ? best : sub * (total - sub); + } + return best % mod; + } +} diff --git a/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.go b/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.go new file mode 100644 index 00000000..d812809a --- /dev/null +++ b/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.go @@ -0,0 +1,45 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func maxProduct(root *TreeNode) int { + const mod = 1_000_000_007 + var nodes []*TreeNode + stack := []*TreeNode{root} + + for len(stack) > 0 { + node := stack[len(stack)-1] + stack = stack[:len(stack)-1] + if node != nil { + nodes = append(nodes, node) + stack = append(stack, node.Left, node.Right) + } + } + + sums := make(map[*TreeNode]int64) + for i := len(nodes) - 1; i >= 0; i-- { + node := nodes[i] + sub := int64(node.Val) + if node.Left != nil { + sub += sums[node.Left] + } + if node.Right != nil { + sub += sums[node.Right] + } + sums[node] = sub + } + + total := sums[root] + var best int64 = 0 + for _, sub := range sums { + prod := sub * (total - sub) + if prod > best { + best = prod + } + } + return int(best % mod) +} diff --git a/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.java b/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.java new file mode 100644 index 00000000..a51559b5 --- /dev/null +++ b/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.java @@ -0,0 +1,48 @@ +/** + * 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 maxProduct(TreeNode root) { + final int MOD = 1_000_000_007; + List nodes = new ArrayList<>(); + Deque stack = new ArrayDeque<>(); + stack.push(root); + + while (!stack.isEmpty()) { + TreeNode node = stack.pop(); + if (node != null) { + nodes.add(node); + if (node.left != null) stack.push(node.left); + if (node.right != null) stack.push(node.right); + } + } + + Map sums = new HashMap<>(); + for (int i = nodes.size() - 1; i >= 0; i--) { + TreeNode node = nodes.get(i); + long sub = node.val + + sums.getOrDefault(node.left, 0L) + + sums.getOrDefault(node.right, 0L); + sums.put(node, sub); + } + + long total = sums.get(root); + long best = 0; + for (long sub : sums.values()) { + best = Math.max(best, sub * (total - sub)); + } + return (int)(best % MOD); + } +} diff --git a/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.kt b/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.kt new file mode 100644 index 00000000..f64bbca6 --- /dev/null +++ b/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.kt @@ -0,0 +1,26 @@ +/** + * 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 maxProduct(root: TreeNode?): Int { + val mod = 1_000_000_007 + fun sum(node: TreeNode?): Long = node?.let { it.`val`.toLong() + sum(it.left) + sum(it.right) } ?: 0L + val total = sum(root) + var best = 0L + fun visit(node: TreeNode?): Long { + if (node == null) return 0L + val sub = node.`val`.toLong() + visit(node.left) + visit(node.right) + best = maxOf(best, sub * (total - sub)) + return sub + } + visit(root) + return (best % mod).toInt() + } +} diff --git a/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.py b/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.py new file mode 100644 index 00000000..ddef6b67 --- /dev/null +++ b/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.py @@ -0,0 +1,24 @@ +class Solution: + def maxProduct(self, root: Optional[TreeNode]) -> int: + mod = 1_000_000_007 + nodes = [] + stack = [root] + + # Collect a parent-before-child order without relying on Python recursion. + while stack: + node = stack.pop() + if node: + nodes.append(node) + stack.append(node.left) + stack.append(node.right) + + sums = {} + best = 0 + for node in reversed(nodes): + subtotal = node.val + sums.get(node.left, 0) + sums.get(node.right, 0) + sums[node] = subtotal + + total = sums[root] + for subtotal in sums.values(): + best = max(best, subtotal * (total - subtotal)) + return best % mod diff --git a/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.py2 b/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.py2 new file mode 100644 index 00000000..0c50c08e --- /dev/null +++ b/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.py2 @@ -0,0 +1,33 @@ +# 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 maxProduct(self, root): + """ + :type root: Optional[TreeNode] + :rtype: int + """ + mod = 1000000007 + nodes = [] + stack = [root] + + while stack: + node = stack.pop() + if node: + nodes.append(node) + stack.append(node.left) + stack.append(node.right) + + sums = {} + best = 0 + for node in reversed(nodes): + subtotal = node.val + sums.get(node.left, 0) + sums.get(node.right, 0) + sums[node] = subtotal + + total = sums[root] + for subtotal in sums.values(): + best = max(best, subtotal * (total - subtotal)) + return best % mod diff --git a/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.rb b/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.rb new file mode 100644 index 00000000..6609b1a5 --- /dev/null +++ b/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.rb @@ -0,0 +1,38 @@ +# 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 {Integer} +def max_product(root) + mod = 1000000007 + nodes = [] + stack = [root] + + while stack.any? + node = stack.pop + if node + nodes.push(node) + stack.push(node.left) + stack.push(node.right) + end + end + + sums = {} + nodes.reverse_each do |node| + subtotal = node.val + (sums[node.left] || 0) + (sums[node.right] || 0) + sums[node] = subtotal + end + + total = sums[root] + best = 0 + sums.each_value do |subtotal| + best = [best, subtotal * (total - subtotal)].max + end + return best % mod +end diff --git a/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.rs b/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.rs new file mode 100644 index 00000000..4fbb4c8c --- /dev/null +++ b/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.rs @@ -0,0 +1,50 @@ +// 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 max_product(root: Option>>) -> i32 { + const MOD: i64 = 1_000_000_007; + let mut nodes: Vec>> = Vec::new(); + let mut stack: Vec>>> = vec![root.clone()]; + + while let Some(opt) = stack.pop() { + if let Some(node) = opt { + let n = node.borrow(); + stack.push(n.left.clone()); + stack.push(n.right.clone()); + drop(n); + nodes.push(node); + } + } + + let mut sums: HashMap<*const RefCell, i64> = HashMap::new(); + for node in nodes.iter().rev() { + let n = node.borrow(); + let left_sum = n.left.as_ref().map_or(0, |l| sums[&Rc::as_ptr(l)]); + let right_sum = n.right.as_ref().map_or(0, |r| sums[&Rc::as_ptr(r)]); + sums.insert(Rc::as_ptr(node), n.val as i64 + left_sum + right_sum); + } + + let total = sums[&Rc::as_ptr(root.as_ref().unwrap())]; + let mut best = 0i64; + for &sub in sums.values() { + best = best.max(sub * (total - sub)); + } + (best % MOD) as i32 + } +} diff --git a/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.swift b/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.swift new file mode 100644 index 00000000..beca1467 --- /dev/null +++ b/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.swift @@ -0,0 +1,43 @@ +/** + * 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 maxProduct(_ root: TreeNode?) -> Int { + let mod = 1_000_000_007 + var nodes: [TreeNode] = [] + var stack: [TreeNode?] = [root] + + while !stack.isEmpty { + guard let node = stack.removeLast() else { continue } + nodes.append(node) + stack.append(node.left) + stack.append(node.right) + } + + var sums: [ObjectIdentifier: Int] = [:] + for node in nodes.reversed() { + let leftSum = node.left.map { sums[ObjectIdentifier($0)] ?? 0 } ?? 0 + let rightSum = node.right.map { sums[ObjectIdentifier($0)] ?? 0 } ?? 0 + sums[ObjectIdentifier(node)] = node.val + leftSum + rightSum + } + + let total = sums[ObjectIdentifier(root!)]! + var best = 0 + for sub in sums.values { + best = max(best, sub * (total - sub)) + } + return best % mod + } +} diff --git a/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.ts b/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.ts new file mode 100644 index 00000000..8625d771 --- /dev/null +++ b/tests/1001-1500/1339. maximum-product-of-splitted-binary-tree/sol.ts @@ -0,0 +1,43 @@ +/** + * 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 maxProduct(root: TreeNode | null): number { + const MOD = 1_000_000_007; + const nodes: TreeNode[] = []; + const stack: (TreeNode | null)[] = [root]; + + while (stack.length) { + const node = stack.pop()!; + if (node) { + nodes.push(node); + stack.push(node.left); + stack.push(node.right); + } + } + + const sums = new Map(); + for (let i = nodes.length - 1; i >= 0; i--) { + const node = nodes[i]; + const sub = + node.val + (sums.get(node.left!) ?? 0) + (sums.get(node.right!) ?? 0); + sums.set(node, sub); + } + + const total = sums.get(root!)!; + let best = 0; + for (const sub of sums.values()) { + best = Math.max(best, sub * (total - sub)); + } + return best % MOD; +} diff --git a/tests/1001-1500/1340. jump-game-v/manifest.yaml b/tests/1001-1500/1340. jump-game-v/manifest.yaml new file mode 100644 index 00000000..44f5f12d --- /dev/null +++ b/tests/1001-1500/1340. jump-game-v/manifest.yaml @@ -0,0 +1,304 @@ +entry: + id: 1340 + title: "jump-game-v" + params: + arr: + type: array + items: + type: int + d: + type: int + call: + cpp: "Solution().maxJumps({arr}, {d})" + rust: "Solution::max_jumps({arr}, {d})" + python3: "Solution().maxJumps({arr}, {d})" + python2: "Solution().maxJumps({arr}, {d})" + ruby: "max_jumps({arr}, {d})" + java: "new Solution().maxJumps({arr}, {d})" + csharp: "new Solution().MaxJumps({arr}, {d})" + kotlin: "Solution().maxJumps({arr}, {d})" + go: "maxJumps({arr}, {d})" + dart: "Solution().maxJumps({arr}, {d})" + swift: "Solution().maxJumps({arr}, {d})" + typescript: "maxJumps({arr}, {d})" +judge: + type: "exact" +limits: + time_ms: 700 + memory_mb: 300 +oracle: + python3: + call: "Checker().maxJumps(arr, d, {result})" + checker: | + class Checker: + def maxJumps(self, arr, d, result): + if type(result) is not int: + return False + n = len(arr) + dp = [1] * n + for i in sorted(range(n), key=lambda index: arr[index]): + for j in range(i - 1, max(-1, i - d - 1), -1): + if arr[j] >= arr[i]: + break + dp[i] = max(dp[i], dp[j] + 1) + for j in range(i + 1, min(n, i + d + 1)): + if arr[j] >= arr[i]: + break + dp[i] = max(dp[i], dp[j] + 1) + return result == max(dp) +seed: 1340 +tests: + - name: "single_element_minimum" + in: + arr: [1] + d: 1 + out: 1 + - name: "example_one" + in: + arr: [6, 4, 14, 6, 8, 13, 9, 7, 10, 6, 12] + d: 2 + out: 4 + - name: "example_two_equal_values" + in: + arr: [3, 3, 3, 3, 3] + d: 3 + out: 1 + - name: "example_three_descending_d_one" + in: + arr: [7, 6, 5, 4, 3, 2, 1] + d: 1 + out: 7 + - name: "increasing_d_one" + in: + arr: [1, 2, 3, 4, 5, 6, 7] + d: 1 + out: 7 + - name: "descending_wide_jumps" + in: + arr: [7, 6, 5, 4, 3, 2, 1] + d: 7 + out: 7 + - name: "increasing_wide_jumps" + in: + arr: [1, 2, 3, 4, 5, 6, 7] + d: 7 + out: 7 + - name: "alternating_with_d_one" + in: + arr: [5, 1, 4, 2, 3] + d: 1 + out: 2 + - name: "central_peak" + in: + arr: [1, 10, 1] + d: 2 + out: 2 + - name: "equal_high_endpoints" + in: + arr: [10, 1, 10] + d: 2 + out: 2 + - name: "blocking_higher_value" + in: + arr: [5, 4, 6, 3, 2] + d: 3 + out: 3 + - name: "duplicate_barrier" + in: + arr: [4, 2, 2, 1, 3] + d: 2 + out: 3 + - name: "mixed_local_peaks" + in: + arr: [7, 1, 5, 2, 6, 3, 4] + d: 2 + out: 3 + - name: "symmetric_wide_peak" + in: + arr: [1, 2, 3, 10, 3, 2, 1] + d: 3 + out: 4 + - name: "short_descending" + in: + arr: [3, 2, 1] + d: 2 + out: 3 + - name: "right_peak_with_low_middle" + in: + arr: [2, 1, 3] + d: 2 + out: 3 + - name: "left_peak_then_descent" + in: + arr: [3, 1, 2] + d: 2 + out: 3 + - name: "skip_over_lower_intermediate" + in: + arr: [4, 1, 3, 2] + d: 2 + out: 3 + - name: "descending_distance_two" + in: + arr: [10, 9, 8, 7, 6] + d: 2 + out: 5 + - name: "alternating_descents" + in: + arr: [10, 1, 9, 2, 8, 3, 7] + d: 3 + out: 5 + - name: "long_descending_d_three" + in: + arr: [6, 5, 4, 3, 2, 1] + d: 3 + out: 6 + - name: "maximum_values" + in: + arr: [1, 100000, 1, 99999, 2] + d: 4 + out: 3 + - name: "separated_high_values" + in: + arr: [100000, 1, 99999, 2, 99998, 3] + d: 2 + out: 4 + - name: "jumping_over_lower_values" + in: + arr: [8, 6, 7, 5, 4, 3, 2, 1] + d: 2 + out: 7 + - name: "nonmonotonic_long_path" + in: + arr: [10, 8, 9, 7, 6, 5] + d: 2 + out: 5 + - name: "choose_nonadjacent_descent" + in: + arr: [5, 3, 4, 2, 1] + d: 3 + out: 4 + - name: "limited_distance_blocks_path" + in: + arr: [5, 1, 4, 3, 2] + d: 1 + out: 3 + - name: "wide_distance_enables_path" + in: + arr: [5, 1, 4, 3, 2] + d: 4 + out: 4 + - name: "equal_plateau_stops_scan" + in: + arr: [9, 8, 8, 7, 6] + d: 4 + out: 4 + - name: "detour_around_local_rise" + in: + arr: [9, 7, 8, 6, 5, 4] + d: 3 + out: 5 + - name: "wide_jump_then_chain" + in: + arr: [4, 5, 1, 2, 3] + d: 3 + out: 4 + - name: "rising_barriers" + in: + arr: [3, 1, 4, 2, 5] + d: 2 + out: 4 + - name: "terminal_high_barrier" + in: + arr: [10, 1, 2, 3, 4, 5, 6] + d: 1 + out: 6 + - name: "minimum_d_with_duplicate_low" + in: + arr: [2, 1, 1, 2, 1] + d: 1 + out: 2 + - name: "generated_stress_128_d_one" + seed: 1341 + in: + arr: + gen: "array" + len: 128 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + d: 1 + - name: "generated_stress_257_d_seven" + seed: 1342 + in: + arr: + gen: "array" + len: 257 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + d: 7 + - name: "generated_stress_512_d_sixty_four" + seed: 1343 + in: + arr: + gen: "array" + len: 512 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + d: 64 + - name: "generated_stress_999_max_distance" + seed: 1344 + in: + arr: + gen: "array" + len: 999 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + d: 999 + - name: "generated_stress_1000_d_one" + seed: 1345 + in: + arr: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + d: 1 + - name: "generated_stress_1000_max_distance" + seed: 1346 + in: + arr: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + d: 1000 diff --git a/tests/1001-1500/1340. jump-game-v/sol.cpp b/tests/1001-1500/1340. jump-game-v/sol.cpp new file mode 100644 index 00000000..0bd456e0 --- /dev/null +++ b/tests/1001-1500/1340. jump-game-v/sol.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + int maxJumps(vector& arr, int d) { + int n = arr.size(); + vector dp(n, -1); + + function dfs = [&](int i) -> int { + if (dp[i] != -1) return dp[i]; + + int best = 1; + + // Right scan + for (int nxt = i + 1; nxt <= min(n - 1, i + d); ++nxt) { + if (arr[nxt] >= arr[i]) break; + best = max(best, 1 + dfs(nxt)); + } + + // Left scan + for (int nxt = i - 1; nxt >= max(0, i - d); --nxt) { + if (arr[nxt] >= arr[i]) break; + best = max(best, 1 + dfs(nxt)); + } + + dp[i] = best; + return dp[i]; + }; + + int result = 0; + for (int i = 0; i < n; ++i) { + result = max(result, dfs(i)); + } + return result; + } +}; diff --git a/tests/1001-1500/1340. jump-game-v/sol.cs b/tests/1001-1500/1340. jump-game-v/sol.cs new file mode 100644 index 00000000..3863a223 --- /dev/null +++ b/tests/1001-1500/1340. jump-game-v/sol.cs @@ -0,0 +1,34 @@ +public class Solution { + public int MaxJumps(int[] arr, int d) { + int n = arr.Length; + int[] dp = new int[n]; + Array.Fill(dp, -1); + + int Dfs(int i) { + if (dp[i] != -1) return dp[i]; + + int best = 1; + + // Right scan + for (int nxt = i + 1; nxt <= Math.Min(n - 1, i + d); nxt++) { + if (arr[nxt] >= arr[i]) break; + best = Math.Max(best, 1 + Dfs(nxt)); + } + + // Left scan + for (int nxt = i - 1; nxt >= Math.Max(0, i - d); nxt--) { + if (arr[nxt] >= arr[i]) break; + best = Math.Max(best, 1 + Dfs(nxt)); + } + + dp[i] = best; + return dp[i]; + } + + int result = 0; + for (int i = 0; i < n; i++) { + result = Math.Max(result, Dfs(i)); + } + return result; + } +} diff --git a/tests/1001-1500/1340. jump-game-v/sol.dart b/tests/1001-1500/1340. jump-game-v/sol.dart new file mode 100644 index 00000000..2d11f1e0 --- /dev/null +++ b/tests/1001-1500/1340. jump-game-v/sol.dart @@ -0,0 +1,36 @@ +class Solution { + int maxJumps(List arr, int d) { + int n = arr.length; + List dp = List.filled(n, -1); + + int dfs(int i) { + if (dp[i] != -1) return dp[i]; + + int best = 1; + + // Right scan + for (int nxt = i + 1; nxt <= (n - 1 < i + d ? n - 1 : i + d); nxt++) { + if (arr[nxt] >= arr[i]) break; + int cur = 1 + dfs(nxt); + if (cur > best) best = cur; + } + + // Left scan + for (int nxt = i - 1; nxt >= (0 > i - d ? 0 : i - d); nxt--) { + if (arr[nxt] >= arr[i]) break; + int cur = 1 + dfs(nxt); + if (cur > best) best = cur; + } + + dp[i] = best; + return dp[i]; + } + + int result = 0; + for (int i = 0; i < n; i++) { + int cur = dfs(i); + if (cur > result) result = cur; + } + return result; + } +} diff --git a/tests/1001-1500/1340. jump-game-v/sol.go b/tests/1001-1500/1340. jump-game-v/sol.go new file mode 100644 index 00000000..d6812dc5 --- /dev/null +++ b/tests/1001-1500/1340. jump-game-v/sol.go @@ -0,0 +1,58 @@ +func maxJumps(arr []int, d int) int { + n := len(arr) + dp := make([]int, n) + for i := range dp { + dp[i] = -1 + } + + var dfs func(i int) int + dfs = func(i int) int { + if dp[i] != -1 { + return dp[i] + } + + best := 1 + + // Right scan + limit := i + d + if limit >= n { + limit = n - 1 + } + for nxt := i + 1; nxt <= limit; nxt++ { + if arr[nxt] >= arr[i] { + break + } + cur := 1 + dfs(nxt) + if cur > best { + best = cur + } + } + + // Left scan + limit = i - d + if limit < 0 { + limit = 0 + } + for nxt := i - 1; nxt >= limit; nxt-- { + if arr[nxt] >= arr[i] { + break + } + cur := 1 + dfs(nxt) + if cur > best { + best = cur + } + } + + dp[i] = best + return dp[i] + } + + result := 0 + for i := 0; i < n; i++ { + cur := dfs(i) + if cur > result { + result = cur + } + } + return result +} diff --git a/tests/1001-1500/1340. jump-game-v/sol.java b/tests/1001-1500/1340. jump-game-v/sol.java new file mode 100644 index 00000000..801c65ff --- /dev/null +++ b/tests/1001-1500/1340. jump-game-v/sol.java @@ -0,0 +1,37 @@ +class Solution { + public int maxJumps(int[] arr, int d) { + int n = arr.length; + int[] dp = new int[n]; + Arrays.fill(dp, -1); + + int result = 0; + for (int i = 0; i < n; i++) { + result = Math.max(result, dfs(arr, d, i, dp)); + } + return result; + } + + private int dfs(int[] arr, int d, int i, int[] dp) { + if (dp[i] != -1) { + return dp[i]; + } + + int best = 1; + int n = arr.length; + + // Right scan + for (int nxt = i + 1; nxt <= Math.min(n - 1, i + d); nxt++) { + if (arr[nxt] >= arr[i]) break; + best = Math.max(best, 1 + dfs(arr, d, nxt, dp)); + } + + // Left scan + for (int nxt = i - 1; nxt >= Math.max(0, i - d); nxt--) { + if (arr[nxt] >= arr[i]) break; + best = Math.max(best, 1 + dfs(arr, d, nxt, dp)); + } + + dp[i] = best; + return dp[i]; + } +} diff --git a/tests/1001-1500/1340. jump-game-v/sol.kt b/tests/1001-1500/1340. jump-game-v/sol.kt new file mode 100644 index 00000000..344fbe7a --- /dev/null +++ b/tests/1001-1500/1340. jump-game-v/sol.kt @@ -0,0 +1,29 @@ +class Solution { + fun maxJumps(arr: IntArray, d: Int): Int { + val n = arr.size + val dp = IntArray(n) { -1 } + + fun dfs(i: Int): Int { + if (dp[i] != -1) return dp[i] + + var best = 1 + + // Right scan + for (nxt in i + 1..minOf(n - 1, i + d)) { + if (arr[nxt] >= arr[i]) break + best = maxOf(best, 1 + dfs(nxt)) + } + + // Left scan + for (nxt in i - 1 downTo maxOf(0, i - d)) { + if (arr[nxt] >= arr[i]) break + best = maxOf(best, 1 + dfs(nxt)) + } + + dp[i] = best + return dp[i] + } + + return (0 until n).maxOf { dfs(it) } + } +} diff --git a/tests/1001-1500/1340. jump-game-v/sol.py b/tests/1001-1500/1340. jump-game-v/sol.py new file mode 100644 index 00000000..f0f39ec4 --- /dev/null +++ b/tests/1001-1500/1340. jump-game-v/sol.py @@ -0,0 +1,29 @@ +class Solution: + def maxJumps(self, arr: list[int], d: int) -> int: + n = len(arr) + dp = [-1] * n + + def dfs(i): + if dp[i] != -1: + return dp[i] + + best = 1 + + # Right scan + for nxt in range(i + 1, min(n, i + d + 1)): + if arr[nxt] >= arr[i]: + break + + best = max(best, 1 + dfs(nxt)) + + # Left scan + for nxt in range(i - 1, max(-1, i - d - 1), -1): + if arr[nxt] >= arr[i]: + break + + best = max(best, 1 + dfs(nxt)) + + dp[i] = best + return dp[i] + + return max(dfs(i) for i in range(n)) diff --git a/tests/1001-1500/1340. jump-game-v/sol.py2 b/tests/1001-1500/1340. jump-game-v/sol.py2 new file mode 100644 index 00000000..e38843db --- /dev/null +++ b/tests/1001-1500/1340. jump-game-v/sol.py2 @@ -0,0 +1,32 @@ +class Solution(object): + def maxJumps(self, arr, d): + """ + :type arr: List[int] + :type d: int + :rtype: int + """ + n = len(arr) + dp = [-1] * n + + def dfs(i): + if dp[i] != -1: + return dp[i] + + best = 1 + + # Right scan + for nxt in range(i + 1, min(n, i + d + 1)): + if arr[nxt] >= arr[i]: + break + best = max(best, 1 + dfs(nxt)) + + # Left scan + for nxt in range(i - 1, max(-1, i - d - 1), -1): + if arr[nxt] >= arr[i]: + break + best = max(best, 1 + dfs(nxt)) + + dp[i] = best + return dp[i] + + return max(dfs(i) for i in range(n)) diff --git a/tests/1001-1500/1340. jump-game-v/sol.rb b/tests/1001-1500/1340. jump-game-v/sol.rb new file mode 100644 index 00000000..39c6060a --- /dev/null +++ b/tests/1001-1500/1340. jump-game-v/sol.rb @@ -0,0 +1,30 @@ +# @param {Integer[]} arr +# @param {Integer} d +# @return {Integer} +def max_jumps(arr, d) + n = arr.length + dp = Array.new(n, -1) + + dfs = lambda do |i| + return dp[i] if dp[i] != -1 + + best = 1 + + # Right scan + (i + 1).upto([n - 1, i + d].min) do |nxt| + break if arr[nxt] >= arr[i] + best = [best, 1 + dfs.call(nxt)].max + end + + # Left scan + (i - 1).downto([0, i - d].max) do |nxt| + break if arr[nxt] >= arr[i] + best = [best, 1 + dfs.call(nxt)].max + end + + dp[i] = best + dp[i] + end + + (0...n).map { |i| dfs.call(i) }.max +end diff --git a/tests/1001-1500/1340. jump-game-v/sol.rs b/tests/1001-1500/1340. jump-game-v/sol.rs new file mode 100644 index 00000000..54235b55 --- /dev/null +++ b/tests/1001-1500/1340. jump-game-v/sol.rs @@ -0,0 +1,20 @@ +impl Solution { + pub fn max_jumps(arr: Vec, d: i32) -> i32 { + let n = arr.len(); + let d = d as usize; + let mut order: Vec = (0..n).collect(); + order.sort_by_key(|&index| arr[index]); + let mut dp = vec![1; n]; + for index in order { + for step in 1..=d { + if index < step || arr[index - step] >= arr[index] { break; } + dp[index] = dp[index].max(dp[index - step] + 1); + } + for step in 1..=d { + if index + step >= n || arr[index + step] >= arr[index] { break; } + dp[index] = dp[index].max(dp[index + step] + 1); + } + } + *dp.iter().max().unwrap() + } +} diff --git a/tests/1001-1500/1340. jump-game-v/sol.swift b/tests/1001-1500/1340. jump-game-v/sol.swift new file mode 100644 index 00000000..8943da33 --- /dev/null +++ b/tests/1001-1500/1340. jump-game-v/sol.swift @@ -0,0 +1,43 @@ +class Solution { + func maxJumps(_ arr: [Int], _ d: Int) -> Int { + let n = arr.count + var dp = [Int](repeating: -1, count: n) + + func dfs(_ i: Int) -> Int { + if dp[i] != -1 { + return dp[i] + } + + var best = 1 + + // Right scan + if i + 1 < n { + for nxt in (i + 1)...min(n - 1, i + d) { + if arr[nxt] >= arr[i] { + break + } + best = max(best, 1 + dfs(nxt)) + } + } + + // Left scan + if i > 0 { + for nxt in stride(from: i - 1, through: max(0, i - d), by: -1) { + if arr[nxt] >= arr[i] { + break + } + best = max(best, 1 + dfs(nxt)) + } + } + + dp[i] = best + return dp[i] + } + + var result = 0 + for i in 0..= arr[i]) break; + best = Math.max(best, 1 + dfs(nxt)); + } + + // Left scan + for (let nxt = i - 1; nxt >= Math.max(0, i - d); nxt--) { + if (arr[nxt] >= arr[i]) break; + best = Math.max(best, 1 + dfs(nxt)); + } + + dp[i] = best; + return dp[i]; + } + + let result = 0; + for (let i = 0; i < n; i++) { + result = Math.max(result, dfs(i)); + } + return result; +} diff --git a/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/manifest.yaml b/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/manifest.yaml new file mode 100644 index 00000000..09b2dd9e --- /dev/null +++ b/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/manifest.yaml @@ -0,0 +1,186 @@ +entry: + id: 1342 + title: "number-of-steps-to-reduce-a-number-to-zero" + params: + num: + type: int + call: + cpp: "Solution().numberOfSteps({num})" + rust: "Solution::number_of_steps({num})" + python3: "Solution().numberOfSteps({num})" + python2: "Solution().numberOfSteps({num})" + ruby: "number_of_steps({num})" + java: "new Solution().numberOfSteps({num})" + csharp: "new Solution().NumberOfSteps({num})" + kotlin: "Solution().numberOfSteps({num})" + go: "numberOfSteps({num})" + dart: "Solution().numberOfSteps({num})" + swift: "Solution().numberOfSteps({num})" + typescript: "numberOfSteps({num})" +judge: + type: exact +limits: + time_ms: 300 + memory_mb: 300 +oracle: + python3: + call: "Checker().numberOfSteps(num, {result})" + checker: | + class Checker: + def numberOfSteps(self, num, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + steps = 0 + current = num + while current > 0: + if current % 2 == 0: + current //= 2 + else: + current -= 1 + steps += 1 + return result == steps +seed: 1342 +tests: + - name: example_fourteen + in: + num: 14 + out: 6 + - name: example_eight + in: + num: 8 + out: 4 + - name: example_one_two_three + in: + num: 123 + out: 12 + - name: zero + in: + num: 0 + - name: one + in: + num: 1 + - name: two + in: + num: 2 + - name: three + in: + num: 3 + - name: power_of_two_four + in: + num: 4 + - name: power_of_two_sixteen + in: + num: 16 + - name: power_of_two_1024 + in: + num: 1024 + - name: largest_power_of_two + in: + num: 524288 + - name: one_less_than_power_of_two + in: + num: 7 + - name: dense_byte + in: + num: 255 + - name: dense_ten_bits + in: + num: 1023 + - name: alternating_low_bits + in: + num: 42 + - name: alternating_high_bits + in: + num: 699050 + - name: sparse_low_bits + in: + num: 65 + - name: sparse_high_bits + in: + num: 524289 + - name: ten + in: + num: 10 + - name: eleven + in: + num: 11 + - name: twelve + in: + num: 12 + - name: thirteen + in: + num: 13 + - name: fifteen + in: + num: 15 + - name: thirty_one + in: + num: 31 + - name: thirty_two + in: + num: 32 + - name: sixty_three + in: + num: 63 + - name: sixty_four + in: + num: 64 + - name: decimal_hundred + in: + num: 100 + - name: decimal_thousand + in: + num: 1000 + - name: decimal_ten_thousand + in: + num: 10000 + - name: dense_eighteen_bits + in: + num: 262143 + - name: three_times_large_power_of_two + in: + num: 786432 + - name: nontrivial_midrange + in: + num: 333333 + - name: max_minus_one + in: + num: 999999 + - name: maximum + in: + num: 1000000 + - name: generated_full_range_a + seed: 134201 + in: + num: + gen: int + min: 0 + max: 1000000 + - name: generated_full_range_b + seed: 134202 + in: + num: + gen: int + min: 0 + max: 1000000 + - name: generated_odd_values + seed: 134203 + in: + num: + gen: int + min: 500001 + max: 999999 + - name: generated_near_limit + seed: 134204 + in: + num: + gen: int + min: 900000 + max: 1000000 + - name: generated_small_values + seed: 134205 + in: + num: + gen: int + min: 0 + max: 1000 diff --git a/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.cpp b/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.cpp new file mode 100644 index 00000000..2168bfda --- /dev/null +++ b/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.cpp @@ -0,0 +1,7 @@ +class Solution { +public: + int numberOfSteps(int num) { + if (num == 0) return 0; + return (sizeof(int) * 8 - __builtin_clz(num)) - 1 + __builtin_popcount(num); + } +}; diff --git a/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.cs b/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.cs new file mode 100644 index 00000000..e4f19404 --- /dev/null +++ b/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.cs @@ -0,0 +1,14 @@ +public class Solution { + public int NumberOfSteps(int num) { + if (num == 0) return 0; + int bitLen = 0; + int ones = 0; + int n = num; + while (n > 0) { + bitLen++; + if ((n & 1) == 1) ones++; + n >>= 1; + } + return bitLen - 1 + ones; + } +} diff --git a/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.dart b/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.dart new file mode 100644 index 00000000..b1e323ba --- /dev/null +++ b/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.dart @@ -0,0 +1,14 @@ +class Solution { + int numberOfSteps(int num) { + if (num == 0) return 0; + int bitLen = 0; + int ones = 0; + int n = num; + while (n > 0) { + bitLen++; + if (n & 1 == 1) ones++; + n >>= 1; + } + return bitLen - 1 + ones; + } +} diff --git a/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.go b/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.go new file mode 100644 index 00000000..3d66ed79 --- /dev/null +++ b/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.go @@ -0,0 +1,14 @@ +func numberOfSteps(num int) int { + if num == 0 { + return 0 + } + bitLen := 0 + ones := 0 + for n := num; n > 0; n >>= 1 { + bitLen++ + if n&1 == 1 { + ones++ + } + } + return bitLen - 1 + ones +} diff --git a/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.java b/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.java new file mode 100644 index 00000000..4aeb83e6 --- /dev/null +++ b/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.java @@ -0,0 +1,6 @@ +class Solution { + public int numberOfSteps(int num) { + if (num == 0) return 0; + return (32 - Integer.numberOfLeadingZeros(num)) - 1 + Integer.bitCount(num); + } +} diff --git a/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.kt b/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.kt new file mode 100644 index 00000000..6d3985d8 --- /dev/null +++ b/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.kt @@ -0,0 +1,6 @@ +class Solution { + fun numberOfSteps(num: Int): Int { + if (num == 0) return 0 + return num.countLeadingZeroBits().let { 32 - it - 1 } + num.countOneBits() + } +} diff --git a/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.py b/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.py new file mode 100644 index 00000000..9274b600 --- /dev/null +++ b/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.py @@ -0,0 +1,5 @@ +class Solution: + def numberOfSteps(self, num: int) -> int: + if num == 0: + return 0 + return num.bit_length() - 1 + num.bit_count() diff --git a/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.py2 b/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.py2 new file mode 100644 index 00000000..c920f6f7 --- /dev/null +++ b/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.py2 @@ -0,0 +1,13 @@ +class Solution(object): + def numberOfSteps(self, num): + """ + :type num: int + :rtype: int + """ + if num == 0: + return 0 + steps = 0 + while num: + steps += 1 + num = num // 2 if num % 2 == 0 else num - 1 + return steps diff --git a/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.rb b/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.rb new file mode 100644 index 00000000..d4004dad --- /dev/null +++ b/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.rb @@ -0,0 +1,6 @@ +# @param {Integer} num +# @return {Integer} +def number_of_steps(num) + return 0 if num == 0 + num.bit_length - 1 + num.to_s(2).count('1') +end diff --git a/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.rs b/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.rs new file mode 100644 index 00000000..cab757d6 --- /dev/null +++ b/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.rs @@ -0,0 +1,8 @@ +impl Solution { + pub fn number_of_steps(num: i32) -> i32 { + if num == 0 { + return 0; + } + (32 - num.leading_zeros() as i32) - 1 + num.count_ones() as i32 + } +} diff --git a/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.swift b/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.swift new file mode 100644 index 00000000..77d42bc3 --- /dev/null +++ b/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.swift @@ -0,0 +1,6 @@ +class Solution { + func numberOfSteps(_ num: Int) -> Int { + if num == 0 { return 0 } + return num.bitWidth - num.leadingZeroBitCount - 1 + num.nonzeroBitCount + } +} diff --git a/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.ts b/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.ts new file mode 100644 index 00000000..e0a5375d --- /dev/null +++ b/tests/1001-1500/1342. number-of-steps-to-reduce-a-number-to-zero/sol.ts @@ -0,0 +1,6 @@ +function numberOfSteps(num: number): number { + if (num === 0) return 0; + const bitLen = Math.floor(Math.log2(num)) + 1; + const ones = num.toString(2).split("0").join("").length; + return bitLen - 1 + ones; +} diff --git a/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/manifest.yaml b/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/manifest.yaml new file mode 100644 index 00000000..a27ea883 --- /dev/null +++ b/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/manifest.yaml @@ -0,0 +1,299 @@ +entry: + id: 1343 + title: "number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold" + params: + arr: + type: array + items: + type: int + k: + type: int + threshold: + type: int + call: + cpp: "Solution().numOfSubarrays({arr}, {k}, {threshold})" + rust: "Solution::num_of_subarrays({arr}, {k}, {threshold})" + python3: "Solution().numOfSubarrays({arr}, {k}, {threshold})" + python2: "Solution().numOfSubarrays({arr}, {k}, {threshold})" + ruby: "num_of_subarrays({arr}, {k}, {threshold})" + java: "new Solution().numOfSubarrays({arr}, {k}, {threshold})" + csharp: "new Solution().NumOfSubarrays({arr}, {k}, {threshold})" + kotlin: "Solution().numOfSubarrays({arr}, {k}, {threshold})" + go: "numOfSubarrays({arr}, {k}, {threshold})" + dart: "Solution().numOfSubarrays({arr}, {k}, {threshold})" + swift: "Solution().numOfSubarrays({arr}, {k}, {threshold})" + typescript: "numOfSubarrays({arr}, {k}, {threshold})" +judge: + type: "exact" +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().numOfSubarrays(arr, k, threshold, {result})" + checker: | + class Checker: + def numOfSubarrays(self, arr, k, threshold, result): + if type(result) is not int: + return False + target = k * threshold + window_sum = sum(arr[:k]) + expected = 1 if window_sum >= target else 0 + for right in range(k, len(arr)): + window_sum += arr[right] - arr[right - k] + if window_sum >= target: + expected += 1 + return result == expected +seed: 1343 +tests: + - name: "example_one" + in: + arr: [2, 2, 2, 2, 5, 5, 5, 8] + k: 3 + threshold: 4 + - name: "example_two" + in: + arr: [11, 13, 17, 23, 29, 31, 7, 5, 2, 3] + k: 3 + threshold: 5 + - name: "single_meets_zero_threshold" + in: + arr: [1] + k: 1 + threshold: 0 + - name: "single_below_positive_threshold" + in: + arr: [1] + k: 1 + threshold: 2 + - name: "single_at_maximum_value" + in: + arr: [10000] + k: 1 + threshold: 10000 + - name: "k_one_mixed_values" + in: + arr: [1, 5, 6, 4, 10000, 5, 2] + k: 1 + threshold: 5 + - name: "full_length_exact_average" + in: + arr: [1, 2, 3, 4, 5] + k: 5 + threshold: 3 + - name: "full_length_below_threshold" + in: + arr: [9999, 10000, 9999, 10000] + k: 4 + threshold: 10000 + - name: "all_windows_qualify" + in: + arr: [7, 7, 7, 7, 7, 7] + k: 3 + threshold: 7 + - name: "no_windows_qualify" + in: + arr: [1, 1, 1, 1, 1] + k: 2 + threshold: 2 + - name: "zero_threshold" + in: + arr: [1, 10000, 1, 10000] + k: 2 + threshold: 0 + - name: "alternating_exact_boundary" + in: + arr: [1, 9, 1, 9, 1, 9] + k: 2 + threshold: 5 + - name: "alternating_below_boundary" + in: + arr: [1, 8, 1, 8, 1, 8] + k: 2 + threshold: 5 + - name: "fractional_average_qualifies" + in: + arr: [4, 5, 4, 5, 4] + k: 2 + threshold: 4 + - name: "fractional_average_fails" + in: + arr: [4, 5, 4, 5, 4] + k: 2 + threshold: 5 + - name: "first_window_only" + in: + arr: [10, 10, 1, 1, 1] + k: 3 + threshold: 7 + - name: "last_window_only" + in: + arr: [1, 1, 1, 10, 10] + k: 3 + threshold: 7 + - name: "middle_windows_only" + in: + arr: [1, 9, 9, 9, 1] + k: 3 + threshold: 7 + - name: "sliding_entry_and_exit" + in: + arr: [1, 1, 10, 10, 1, 1] + k: 3 + threshold: 5 + - name: "overlapping_spike_windows" + in: + arr: [1, 1, 10000, 1, 1] + k: 3 + threshold: 3334 + - name: "adjacent_spike_windows" + in: + arr: [1, 10000, 10000, 1, 1] + k: 3 + threshold: 3334 + - name: "increasing_sequence" + in: + arr: [1, 2, 3, 4, 5, 6, 7, 8] + k: 4 + threshold: 5 + - name: "decreasing_sequence" + in: + arr: [8, 7, 6, 5, 4, 3, 2, 1] + k: 4 + threshold: 5 + - name: "threshold_at_maximum" + in: + arr: [10000, 10000, 9999, 10000, 10000] + k: 2 + threshold: 10000 + - name: "large_sum_exact_threshold" + in: + arr: [10000, 9999, 10000, 9999, 10000, 9999] + k: 3 + threshold: 9999 + - name: "large_sum_just_above_threshold" + in: + arr: [10000, 9999, 10000, 9999, 10000, 9999] + k: 3 + threshold: 10000 + - name: "k_near_length" + in: + arr: [3, 3, 3, 3, 3, 9] + k: 5 + threshold: 4 + - name: "duplicate_plateau_transition" + in: + arr: [2, 2, 2, 8, 8, 8, 2, 2, 2] + k: 3 + threshold: 6 + - name: "many_exact_windows" + in: + arr: [3, 6, 3, 6, 3, 6, 3, 6] + k: 2 + threshold: 4 + - name: "window_size_three_boundary" + in: + arr: [4, 4, 5, 4, 4, 5, 4] + k: 3 + threshold: 4 + - name: "window_size_seven" + in: + arr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + k: 7 + threshold: 6 + - name: "two_element_boundaries" + in: + arr: [1, 10000] + k: 2 + threshold: 5000 + - name: "long_constant_low" + in: + arr: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + k: 6 + threshold: 1 + - name: "long_constant_high" + in: + arr: + [10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000] + k: 9 + threshold: 9999 + - name: "single_high_value_in_long_window" + in: + arr: [1, 1, 1, 1, 10000, 1, 1, 1, 1] + k: 5 + threshold: 2001 + - name: "generated_small" + seed: 134301 + in: + arr: + gen: "array" + len: 25 + of: + gen: "int" + min: 1 + max: 10000 + distinct: false + sorted: false + elemType: "int" + k: 7 + threshold: 5000 + - name: "generated_k_one" + seed: 134302 + in: + arr: + gen: "array" + len: 200 + of: + gen: "int" + min: 1 + max: 10000 + distinct: false + sorted: false + elemType: "int" + k: 1 + threshold: 7500 + - name: "generated_medium_window" + seed: 134303 + in: + arr: + gen: "array" + len: 4096 + of: + gen: "int" + min: 1 + max: 10000 + distinct: false + sorted: false + elemType: "int" + k: 257 + threshold: 5000 + - name: "generated_max_length_small_window" + seed: 134304 + in: + arr: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 10000 + distinct: false + sorted: false + elemType: "int" + k: 2 + threshold: 5000 + - name: "generated_max_length_full_window" + seed: 134305 + in: + arr: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 10000 + distinct: false + sorted: false + elemType: "int" + k: 100000 + threshold: 5000 diff --git a/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.cpp b/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.cpp new file mode 100644 index 00000000..4b1e13a7 --- /dev/null +++ b/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int numOfSubarrays(vector& arr, int k, int threshold) { + int res = 0; + int left = 0; + int total = 0; + for (int right = 0; right < arr.size(); right++) { + total += arr[right]; + if (right - left + 1 == k) { + if (total / k >= threshold) { + res++; + } + total -= arr[left]; + left++; + } + } + return res; + } +}; diff --git a/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.cs b/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.cs new file mode 100644 index 00000000..16021763 --- /dev/null +++ b/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.cs @@ -0,0 +1,18 @@ +public class Solution { + public int NumOfSubarrays(int[] arr, int k, int threshold) { + int res = 0; + int left = 0; + int total = 0; + for (int right = 0; right < arr.Length; right++) { + total += arr[right]; + if (right - left + 1 == k) { + if (total / k >= threshold) { + res++; + } + total -= arr[left]; + left++; + } + } + return res; + } +} diff --git a/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.dart b/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.dart new file mode 100644 index 00000000..f01ab927 --- /dev/null +++ b/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.dart @@ -0,0 +1,18 @@ +class Solution { + int numOfSubarrays(List arr, int k, int threshold) { + int res = 0; + int left = 0; + int total = 0; + for (int right = 0; right < arr.length; right++) { + total += arr[right]; + if (right - left + 1 == k) { + if (total ~/ k >= threshold) { + res++; + } + total -= arr[left]; + left++; + } + } + return res; + } +} diff --git a/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.go b/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.go new file mode 100644 index 00000000..8110182d --- /dev/null +++ b/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.go @@ -0,0 +1,16 @@ +func numOfSubarrays(arr []int, k int, threshold int) int { + res := 0 + left := 0 + total := 0 + for right := 0; right < len(arr); right++ { + total += arr[right] + if right - left + 1 == k { + if total / k >= threshold { + res++ + } + total -= arr[left] + left++ + } + } + return res +} diff --git a/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.java b/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.java new file mode 100644 index 00000000..b9f1dc95 --- /dev/null +++ b/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.java @@ -0,0 +1,18 @@ +class Solution { + public int numOfSubarrays(int[] arr, int k, int threshold) { + int res = 0; + int left = 0; + int total = 0; + for (int right = 0; right < arr.length; right++) { + total += arr[right]; + if (right - left + 1 == k) { + if (total / k >= threshold) { + res++; + } + total -= arr[left]; + left++; + } + } + return res; + } +} diff --git a/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.kt b/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.kt new file mode 100644 index 00000000..6db28609 --- /dev/null +++ b/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.kt @@ -0,0 +1,18 @@ +class Solution { + fun numOfSubarrays(arr: IntArray, k: Int, threshold: Int): Int { + var res = 0 + var left = 0 + var total = 0 + for (right in arr.indices) { + total += arr[right] + if (right - left + 1 == k) { + if (total / k >= threshold) { + res++ + } + total -= arr[left] + left++ + } + } + return res + } +} diff --git a/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.py b/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.py new file mode 100644 index 00000000..52ddb615 --- /dev/null +++ b/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.py @@ -0,0 +1,16 @@ +from typing import List + + +class Solution: + def numOfSubarrays(self, arr: List[int], k: int, threshold: int) -> int: + res = 0 + left = 0 + total = 0 + for right in range(len(arr)): + total += arr[right] + if right - left + 1 == k: + if total / k >= threshold: + res += 1 + total -= arr[left] + left += 1 + return res diff --git a/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.py2 b/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.py2 new file mode 100644 index 00000000..566f905d --- /dev/null +++ b/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.py2 @@ -0,0 +1,19 @@ +class Solution(object): + def numOfSubarrays(self, arr, k, threshold): + """ + :type arr: List[int] + :type k: int + :type threshold: int + :rtype: int + """ + res = 0 + left = 0 + total = 0 + for right in range(len(arr)): + total += arr[right] + if right - left + 1 == k: + if total // k >= threshold: + res += 1 + total -= arr[left] + left += 1 + return res diff --git a/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.rb b/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.rb new file mode 100644 index 00000000..0ed5827a --- /dev/null +++ b/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.rb @@ -0,0 +1,18 @@ +# @param {Integer[]} arr +# @param {Integer} k +# @param {Integer} threshold +# @return {Integer} +def num_of_subarrays(arr, k, threshold) + res = 0 + left = 0 + total = 0 + arr.each_with_index do |val, right| + total += val + if right - left + 1 == k + res += 1 if total / k >= threshold + total -= arr[left] + left += 1 + end + end + res +end diff --git a/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.rs b/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.rs new file mode 100644 index 00000000..2819b92f --- /dev/null +++ b/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.rs @@ -0,0 +1,19 @@ +impl Solution { + pub fn num_of_subarrays(arr: Vec, k: i32, threshold: i32) -> i32 { + let mut res = 0; + let mut left = 0; + let mut total = 0; + let k_usize = k as usize; + for right in 0..arr.len() { + total += arr[right]; + if right - left + 1 == k_usize { + if total / k >= threshold { + res += 1; + } + total -= arr[left]; + left += 1; + } + } + res + } +} diff --git a/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.swift b/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.swift new file mode 100644 index 00000000..3e04fa4d --- /dev/null +++ b/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.swift @@ -0,0 +1,18 @@ +class Solution { + func numOfSubarrays(_ arr: [Int], _ k: Int, _ threshold: Int) -> Int { + var res = 0 + var left = 0 + var total = 0 + for right in 0..= threshold { + res += 1 + } + total -= arr[left] + left += 1 + } + } + return res + } +} diff --git a/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.ts b/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.ts new file mode 100644 index 00000000..9e78964b --- /dev/null +++ b/tests/1001-1500/1343. number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/sol.ts @@ -0,0 +1,16 @@ +function numOfSubarrays(arr: number[], k: number, threshold: number): number { + let res = 0; + let left = 0; + let total = 0; + for (let right = 0; right < arr.length; right++) { + total += arr[right]; + if (right - left + 1 === k) { + if (Math.floor(total / k) >= threshold) { + res++; + } + total -= arr[left]; + left++; + } + } + return res; +} diff --git a/tests/1001-1500/1344. angle-between-hands-of-a-clock/manifest.yaml b/tests/1001-1500/1344. angle-between-hands-of-a-clock/manifest.yaml new file mode 100644 index 00000000..78664ad8 --- /dev/null +++ b/tests/1001-1500/1344. angle-between-hands-of-a-clock/manifest.yaml @@ -0,0 +1,245 @@ +entry: + id: 1344 + title: angle-between-hands-of-a-clock + params: + hour: + type: int + minutes: + type: int + call: + cpp: "Solution().angleClock({hour}, {minutes})" + rust: "Solution::angle_clock({hour}, {minutes})" + python3: "Solution().angleClock({hour}, {minutes})" + python2: "Solution().angleClock({hour}, {minutes})" + ruby: "angle_clock({hour}, {minutes})" + java: "new Solution().angleClock({hour}, {minutes})" + csharp: "new Solution().AngleClock({hour}, {minutes})" + kotlin: "Solution().angleClock({hour}, {minutes})" + go: "angleClock({hour}, {minutes})" + dart: "Solution().angleClock({hour}, {minutes})" + swift: "Solution().angleClock({hour}, {minutes})" + typescript: "angleClock({hour}, {minutes})" + +judge: + type: "exact" + +limits: + time_ms: 500 + memory_mb: 256 + +oracle: + python3: + call: "Checker().angleClock(hour, minutes, {result})" + checker: | + import math + + class Checker: + def angleClock(self, hour, minutes, result): + if not isinstance(result, (int, float)) or isinstance(result, bool): + return False + if not math.isfinite(result): + return False + hour_angle = (hour % 12) * 30.0 + minutes * 0.5 + minute_angle = minutes * 6.0 + difference = abs(hour_angle - minute_angle) + expected = min(difference, 360.0 - difference) + return abs(float(result) - expected) <= 1e-5 + +seed: 1344 + +tests: + - name: example_twelve_thirty + in: + hour: 12 + minutes: 30 + - name: example_three_thirty + in: + hour: 3 + minutes: 30 + - name: example_three_fifteen + in: + hour: 3 + minutes: 15 + - name: midnight_aligned + in: + hour: 12 + minutes: 0 + - name: one_oclock + in: + hour: 1 + minutes: 0 + - name: right_angle_at_three + in: + hour: 3 + minutes: 0 + - name: straight_angle_at_six + in: + hour: 6 + minutes: 0 + - name: right_angle_at_nine + in: + hour: 9 + minutes: 0 + - name: half_past_six + in: + hour: 6 + minutes: 30 + - name: quarter_to_three + in: + hour: 3 + minutes: 45 + - name: first_minute_after_one + in: + hour: 1 + minutes: 1 + - name: final_minute_before_twelve + in: + hour: 11 + minutes: 59 + - name: final_minute_after_twelve + in: + hour: 12 + minutes: 59 + - name: nearly_two_oclock + in: + hour: 1 + minutes: 59 + - name: two_ten + in: + hour: 2 + minutes: 10 + - name: four_twenty + in: + hour: 4 + minutes: 20 + - name: five_twenty_five + in: + hour: 5 + minutes: 25 + - name: seven_thirty_five + in: + hour: 7 + minutes: 35 + - name: eight_forty + in: + hour: 8 + minutes: 40 + - name: ten_fifty + in: + hour: 10 + minutes: 50 + - name: hands_coincide_at_one_five + in: + hour: 1 + minutes: 5 + - name: obtuse_four_oclock + in: + hour: 4 + minutes: 0 + - name: reflex_complement_seven_oclock + in: + hour: 7 + minutes: 0 + - name: exact_thirty_degrees + in: + hour: 2 + minutes: 0 + - name: exact_ninety_degrees + in: + hour: 12 + minutes: 15 + - name: fractional_ten_ten + in: + hour: 10 + minutes: 10 + - name: fractional_two_thirty_five + in: + hour: 2 + minutes: 35 + - name: fractional_nine_forty + in: + hour: 9 + minutes: 40 + - name: one_minute_after_twelve + in: + hour: 12 + minutes: 1 + - name: two_minutes_before_twelve + in: + hour: 11 + minutes: 58 + - name: midpoint_five_thirty + in: + hour: 5 + minutes: 30 + - name: six_forty + in: + hour: 6 + minutes: 40 + - name: late_evening_eleven_thirty + in: + hour: 11 + minutes: 30 + - name: early_morning_one_thirty + in: + hour: 1 + minutes: 30 + - name: maximum_minute_eight_fifty_nine + in: + hour: 8 + minutes: 59 + - name: generated_full_clock_a + seed: 134401 + in: + hour: + gen: "int" + min: 1 + max: 12 + minutes: + gen: "int" + min: 0 + max: 59 + - name: generated_full_clock_b + seed: 134402 + in: + hour: + gen: "int" + min: 1 + max: 12 + minutes: + gen: "int" + min: 0 + max: 59 + - name: generated_full_clock_c + seed: 134403 + in: + hour: + gen: "int" + min: 1 + max: 12 + minutes: + gen: "int" + min: 0 + max: 59 + - name: generated_full_clock_d + seed: 134404 + in: + hour: + gen: "int" + min: 1 + max: 12 + minutes: + gen: "int" + min: 0 + max: 59 + - name: generated_full_clock_e + seed: 134405 + in: + hour: + gen: "int" + min: 1 + max: 12 + minutes: + gen: "int" + min: 0 + max: 59 diff --git a/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.cpp b/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.cpp new file mode 100644 index 00000000..24c07bf6 --- /dev/null +++ b/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.cpp @@ -0,0 +1,6 @@ +class Solution { +public: + double angleClock(int hour, int minutes) { + return acos(cos((330.0 * hour + 5.5 * minutes) * 0.0174532925)) * 57.2957795; + } +}; diff --git a/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.cs b/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.cs new file mode 100644 index 00000000..df1ea45a --- /dev/null +++ b/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.cs @@ -0,0 +1,5 @@ +public class Solution { + public double AngleClock(int hour, int minutes) { + return Math.Acos(Math.Cos((330.0 * hour + 5.5 * minutes) * 0.0174532925)) * 57.2957795; + } +} diff --git a/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.dart b/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.dart new file mode 100644 index 00000000..14603ec2 --- /dev/null +++ b/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.dart @@ -0,0 +1,5 @@ +class Solution { + double angleClock(int hour, int minutes) { + return acos(cos((330 * hour + 5.5 * minutes) * 0.0174532925)) * 57.2957795; + } +} diff --git a/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.go b/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.go new file mode 100644 index 00000000..af8cd260 --- /dev/null +++ b/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.go @@ -0,0 +1,3 @@ +func angleClock(hour int, minutes int) float64 { + return math.Acos(math.Cos((330.0*float64(hour) + 5.5*float64(minutes)) * 0.0174532925)) * 57.2957795 +} diff --git a/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.java b/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.java new file mode 100644 index 00000000..a860221d --- /dev/null +++ b/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.java @@ -0,0 +1,5 @@ +class Solution { + public double angleClock(int hour, int minutes) { + return Math.acos(Math.cos((330 * hour + 5.5 * minutes) * 0.0174532925)) * 57.2957795; + } +} diff --git a/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.kt b/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.kt new file mode 100644 index 00000000..fe55ea5e --- /dev/null +++ b/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.kt @@ -0,0 +1,5 @@ +class Solution { + fun angleClock(hour: Int, minutes: Int): Double { + return Math.acos(Math.cos((330 * hour + 5.5 * minutes) * 0.0174532925)) * 57.2957795 + } +} diff --git a/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.py b/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.py new file mode 100644 index 00000000..5fa250ce --- /dev/null +++ b/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.py @@ -0,0 +1,6 @@ +import math + + +class Solution: + def angleClock(self, h: int, m: int) -> float: + return math.acos(math.cos((330 * h + 5.5 * m) * 0.0174532925)) * 57.2957795 diff --git a/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.py2 b/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.py2 new file mode 100644 index 00000000..d020c8c6 --- /dev/null +++ b/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.py2 @@ -0,0 +1,8 @@ +class Solution(object): + def angleClock(self, hour, minutes): + """ + :type hour: int + :type minutes: int + :rtype: float + """ + return math.acos(math.cos((330 * hour + 5.5 * minutes) * 0.0174532925)) * 57.2957795 diff --git a/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.rb b/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.rb new file mode 100644 index 00000000..201d19dc --- /dev/null +++ b/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.rb @@ -0,0 +1,6 @@ +# @param {Integer} hour +# @param {Integer} minutes +# @return {Float} +def angle_clock(hour, minutes) + Math.acos(Math.cos((330 * hour + 5.5 * minutes) * 0.0174532925)) * 57.2957795 +end diff --git a/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.rs b/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.rs new file mode 100644 index 00000000..5edcb043 --- /dev/null +++ b/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.rs @@ -0,0 +1,5 @@ +impl Solution { + pub fn angle_clock(hour: i32, minutes: i32) -> f64 { + ((330.0 * hour as f64 + 5.5 * minutes as f64) * 0.0174532925_f64).cos().acos() * 57.2957795_f64 + } +} diff --git a/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.swift b/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.swift new file mode 100644 index 00000000..a65284fc --- /dev/null +++ b/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.swift @@ -0,0 +1,5 @@ +class Solution { + func angleClock(_ hour: Int, _ minutes: Int) -> Double { + return acos(cos((330.0 * Double(hour) + 5.5 * Double(minutes)) * 0.0174532925)) * 57.2957795 + } +} diff --git a/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.ts b/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.ts new file mode 100644 index 00000000..1ee68c47 --- /dev/null +++ b/tests/1001-1500/1344. angle-between-hands-of-a-clock/sol.ts @@ -0,0 +1,6 @@ +function angleClock(hour: number, minutes: number): number { + return ( + Math.acos(Math.cos((330 * hour + 5.5 * minutes) * 0.0174532925)) * + 57.2957795 + ); +} diff --git a/tests/1001-1500/1345. jump-game-iv/manifest.yaml b/tests/1001-1500/1345. jump-game-iv/manifest.yaml new file mode 100644 index 00000000..23fd9c18 --- /dev/null +++ b/tests/1001-1500/1345. jump-game-iv/manifest.yaml @@ -0,0 +1,252 @@ +entry: + id: 1345 + title: "jump-game-iv" + params: + arr: + type: array + items: + type: int + call: + cpp: "Solution().minJumps({arr})" + rust: "Solution::min_jumps({arr})" + python3: "Solution().minJumps({arr})" + python2: "Solution().minJumps({arr})" + ruby: "min_jumps({arr})" + java: "new Solution().minJumps({arr})" + csharp: "new Solution().MinJumps({arr})" + kotlin: "Solution().minJumps({arr})" + go: "minJumps({arr})" + dart: "Solution().minJumps({arr})" + swift: "Solution().minJumps({arr})" + typescript: "minJumps({arr})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 300 + +oracle: + python3: + call: "Checker().minJumps(arr, {result})" + checker: | + from collections import deque, defaultdict + + class Checker: + def minJumps(self, arr, result): + if not isinstance(result, int) or isinstance(result, bool) or not arr: + return False + n = len(arr) + groups = defaultdict(list) + for index, value in enumerate(arr): + groups[value].append(index) + distance = [-1] * n + distance[0] = 0 + queue = deque([0]) + while queue: + index = queue.popleft() + if index == n - 1: + break + neighbors = [] + if index > 0: + neighbors.append(index - 1) + if index + 1 < n: + neighbors.append(index + 1) + neighbors.extend(groups[arr[index]]) + groups[arr[index]] = [] + for nxt in neighbors: + if distance[nxt] == -1: + distance[nxt] = distance[index] + 1 + queue.append(nxt) + return result == distance[-1] + +seed: 134500 + +tests: + - name: "example_one" + in: + arr: [100, -23, -23, 404, 100, 23, 23, 23, 3, 404] + - name: "singleton" + in: + arr: [7] + - name: "example_direct_jump" + in: + arr: [7, 6, 9, 6, 9, 6, 9, 7] + - name: "two_values" + in: + arr: [1, 2] + - name: "three_distinct" + in: + arr: [1, 2, 3] + - name: "direct_equal_ends" + in: + arr: [5, 1, 2, 3, 5] + - name: "all_equal" + in: + arr: [4, 4, 4, 4, 4] + - name: "alternating_pair" + in: + arr: [1, 2, 1, 2, 1, 2] + - name: "equal_middle_cluster" + in: + arr: [0, 1, 2, 3, 2, 1, 0] + - name: "negative_values" + in: + arr: [-1, -2, -3, -1] + - name: "extreme_values" + in: + arr: [-100000000, 1, 2, -100000000] + - name: "repeated_target_value" + in: + arr: [7, 7, 1, 2, 3, 4] + - name: "target_cluster" + in: + arr: [1, 2, 3, 4, 4, 4] + - name: "long_unique_small" + in: + arr: [1, 2, 3, 4, 5, 6, 7, 8] + - name: "duplicate_shortcut" + in: + arr: [1, 9, 9, 9, 1] + - name: "two_duplicate_groups" + in: + arr: [1, 2, 1, 2, 3, 3] + - name: "interleaved_groups" + in: + arr: [1, 2, 3, 1, 2, 3, 4] + - name: "palindrome_values" + in: + arr: [1, 2, 3, 2, 1] + - name: "large_gap_unique" + in: + arr: [10, 20, 30, 40, 50] + - name: "same_start_end" + in: + arr: [8, 1, 2, 3, 4, 8] + - name: "same_start_near_end" + in: + arr: [8, 1, 2, 8, 4, 5] + - name: "all_negative_repeat" + in: + arr: [-5, -4, -5, -3, -2] + - name: "zeros" + in: + arr: [0, 1, 0, 2, 0, 3] + - name: "many_zeros" + in: + arr: [0, 0, 1, 0, 2, 0, 3, 0] + - name: "repeated_endpoints" + in: + arr: [2, 1, 2, 3, 4, 3, 4] + - name: "cluster_at_start" + in: + arr: [9, 9, 9, 1, 2, 3, 4] + - name: "cluster_at_end" + in: + arr: [1, 2, 3, 4, 9, 9, 9] + - name: "multiple_shortcuts" + in: + arr: [1, 2, 1, 3, 2, 4, 3, 4] + - name: "large_duplicate_block" + in: + arr: [1, 2, 3, 3, 3, 3, 4, 5] + - name: "alternating_three" + in: + arr: [1, 2, 3, 1, 2, 3, 1, 2, 3] + - name: "descending_values" + in: + arr: [9, 8, 7, 6, 5, 4, 3, 2, 1] + - name: "extreme_duplicate_end" + in: + arr: [100000000, 1, 2, 3, 100000000] + - name: "backtrack_then_value_shortcut" + in: + arr: [10, 20, 30, 40, 20, 50, 60, 30, 70] + - name: "generated_small" + seed: 134501 + in: + arr: + gen: "array" + len: + gen: "int" + min: 1 + max: 20 + of: + gen: "int" + min: -10 + max: 10 + distinct: false + sorted: false + - name: "generated_medium" + seed: 134502 + in: + arr: + gen: "array" + len: 200 + of: + gen: "int" + min: -100000000 + max: 100000000 + distinct: false + sorted: false + - name: "generated_duplicate_heavy" + seed: 134503 + in: + arr: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 5 + distinct: false + sorted: false + - name: "generated_large" + seed: 134504 + in: + arr: + gen: "array" + len: 10000 + of: + gen: "int" + min: -100000000 + max: 100000000 + distinct: false + sorted: false + - name: "generated_maximum_duplicate_heavy" + seed: 134506 + in: + arr: + gen: "array" + len: 50000 + of: + gen: "int" + min: -3 + max: 3 + distinct: false + sorted: false + - name: "generated_maximum" + seed: 134505 + in: + arr: + gen: "array" + len: 50000 + of: + gen: "int" + min: -100000000 + max: 100000000 + distinct: false + sorted: false + - name: "generated_full_range_boundary" + seed: 134507 + in: + arr: + gen: "array" + len: 37 + of: + gen: "int" + min: -100000000 + max: 100000000 + distinct: false + sorted: false diff --git a/tests/1001-1500/1345. jump-game-iv/sol.cpp b/tests/1001-1500/1345. jump-game-iv/sol.cpp new file mode 100644 index 00000000..7e90e15e --- /dev/null +++ b/tests/1001-1500/1345. jump-game-iv/sol.cpp @@ -0,0 +1,40 @@ +class Solution { +public: + int minJumps(vector& arr) { + int n = arr.size(); + if (n == 1) return 0; + + unordered_map> mp; + for (int i = 0; i < n; ++i) { + mp[arr[i]].push_back(i); + } + + queue> q; + q.push({0, 0}); + vector vis(n, false); + vis[0] = true; + + while (!q.empty()) { + auto [node, dist] = q.front(); q.pop(); + if (node == n - 1) return dist; + + if (node - 1 >= 0 && !vis[node - 1]) { + vis[node - 1] = true; + q.push({node - 1, dist + 1}); + } + if (node + 1 < n && !vis[node + 1]) { + vis[node + 1] = true; + q.push({node + 1, dist + 1}); + } + + for (int nxt : mp[arr[node]]) { + if (!vis[nxt]) { + vis[nxt] = true; + q.push({nxt, dist + 1}); + } + } + mp[arr[node]].clear(); + } + return -1; + } +}; diff --git a/tests/1001-1500/1345. jump-game-iv/sol.cs b/tests/1001-1500/1345. jump-game-iv/sol.cs new file mode 100644 index 00000000..4e7520a8 --- /dev/null +++ b/tests/1001-1500/1345. jump-game-iv/sol.cs @@ -0,0 +1,44 @@ +public class Solution { + public int MinJumps(int[] arr) { + int n = arr.Length; + if (n == 1) return 0; + + Dictionary> mp = new Dictionary>(); + for (int i = 0; i < n; i++) { + if (!mp.ContainsKey(arr[i])) { + mp[arr[i]] = new List(); + } + mp[arr[i]].Add(i); + } + + Queue<(int, int)> q = new Queue<(int, int)>(); + q.Enqueue((0, 0)); + bool[] vis = new bool[n]; + vis[0] = true; + + while (q.Count > 0) { + var (node, dist) = q.Dequeue(); + if (node == n - 1) return dist; + + if (node - 1 >= 0 && !vis[node - 1]) { + vis[node - 1] = true; + q.Enqueue((node - 1, dist + 1)); + } + if (node + 1 < n && !vis[node + 1]) { + vis[node + 1] = true; + q.Enqueue((node + 1, dist + 1)); + } + + if (mp.ContainsKey(arr[node])) { + foreach (int nxt in mp[arr[node]]) { + if (!vis[nxt]) { + vis[nxt] = true; + q.Enqueue((nxt, dist + 1)); + } + } + mp[arr[node]].Clear(); + } + } + return -1; + } +} diff --git a/tests/1001-1500/1345. jump-game-iv/sol.dart b/tests/1001-1500/1345. jump-game-iv/sol.dart new file mode 100644 index 00000000..c3fe8f3f --- /dev/null +++ b/tests/1001-1500/1345. jump-game-iv/sol.dart @@ -0,0 +1,40 @@ +class Solution { + int minJumps(List arr) { + int n = arr.length; + if (n == 1) return 0; + + Map> mp = {}; + for (int i = 0; i < n; i++) { + mp.putIfAbsent(arr[i], () => []).add(i); + } + + List> q = [[0, 0]]; + List vis = List.filled(n, false); + vis[0] = true; + + int head = 0; + while (head < q.length) { + var curr = q[head++]; + int node = curr[0], dist = curr[1]; + if (node == n - 1) return dist; + + if (node - 1 >= 0 && !vis[node - 1]) { + vis[node - 1] = true; + q.add([node - 1, dist + 1]); + } + if (node + 1 < n && !vis[node + 1]) { + vis[node + 1] = true; + q.add([node + 1, dist + 1]); + } + + for (int nxt in mp[arr[node]] ?? []) { + if (!vis[nxt]) { + vis[nxt] = true; + q.add([nxt, dist + 1]); + } + } + mp[arr[node]]?.clear(); + } + return -1; + } +} diff --git a/tests/1001-1500/1345. jump-game-iv/sol.go b/tests/1001-1500/1345. jump-game-iv/sol.go new file mode 100644 index 00000000..98b17061 --- /dev/null +++ b/tests/1001-1500/1345. jump-game-iv/sol.go @@ -0,0 +1,41 @@ +func minJumps(arr []int) int { + n := len(arr) + if n == 1 { + return 0 + } + + mp := make(map[int][]int) + for i, v := range arr { + mp[v] = append(mp[v], i) + } + + q := [][]int{{0, 0}} + vis := make([]bool, n) + vis[0] = true + + for len(q) > 0 { + node, dist := q[0][0], q[0][1] + q = q[1:] + if node == n-1 { + return dist + } + + if node-1 >= 0 && !vis[node-1] { + vis[node-1] = true + q = append(q, []int{node - 1, dist + 1}) + } + if node+1 < n && !vis[node+1] { + vis[node+1] = true + q = append(q, []int{node + 1, dist + 1}) + } + + for _, nxt := range mp[arr[node]] { + if !vis[nxt] { + vis[nxt] = true + q = append(q, []int{nxt, dist + 1}) + } + } + mp[arr[node]] = nil + } + return -1 +} diff --git a/tests/1001-1500/1345. jump-game-iv/sol.java b/tests/1001-1500/1345. jump-game-iv/sol.java new file mode 100644 index 00000000..5b697b41 --- /dev/null +++ b/tests/1001-1500/1345. jump-game-iv/sol.java @@ -0,0 +1,42 @@ +import java.util.*; + +class Solution { + public int minJumps(int[] arr) { + int n = arr.length; + if (n == 1) return 0; + + Map> mp = new HashMap<>(); + for (int i = 0; i < n; i++) { + mp.computeIfAbsent(arr[i], k -> new ArrayList<>()).add(i); + } + + Queue q = new LinkedList<>(); + q.add(new int[]{0, 0}); + boolean[] vis = new boolean[n]; + vis[0] = true; + + while (!q.isEmpty()) { + int[] curr = q.poll(); + int node = curr[0], dist = curr[1]; + if (node == n - 1) return dist; + + if (node - 1 >= 0 && !vis[node - 1]) { + vis[node - 1] = true; + q.add(new int[]{node - 1, dist + 1}); + } + if (node + 1 < n && !vis[node + 1]) { + vis[node + 1] = true; + q.add(new int[]{node + 1, dist + 1}); + } + + for (int nxt : mp.getOrDefault(arr[node], Collections.emptyList())) { + if (!vis[nxt]) { + vis[nxt] = true; + q.add(new int[]{nxt, dist + 1}); + } + } + mp.get(arr[node]).clear(); + } + return -1; + } +} diff --git a/tests/1001-1500/1345. jump-game-iv/sol.kt b/tests/1001-1500/1345. jump-game-iv/sol.kt new file mode 100644 index 00000000..7ad93274 --- /dev/null +++ b/tests/1001-1500/1345. jump-game-iv/sol.kt @@ -0,0 +1,39 @@ +class Solution { + fun minJumps(arr: IntArray): Int { + val n = arr.size + if (n == 1) return 0 + + val mp = mutableMapOf>() + for (i in arr.indices) { + mp.getOrPut(arr[i]) { mutableListOf() }.add(i) + } + + val q = ArrayDeque>() + q.addLast(0 to 0) + val vis = BooleanArray(n) + vis[0] = true + + while (q.isNotEmpty()) { + val (node, dist) = q.removeFirst() + if (node == n - 1) return dist + + if (node - 1 >= 0 && !vis[node - 1]) { + vis[node - 1] = true + q.addLast(node - 1 to dist + 1) + } + if (node + 1 < n && !vis[node + 1]) { + vis[node + 1] = true + q.addLast(node + 1 to dist + 1) + } + + mp[arr[node]]?.forEach { nxt -> + if (!vis[nxt]) { + vis[nxt] = true + q.addLast(nxt to dist + 1) + } + } + mp[arr[node]]?.clear() + } + return -1 + } +} diff --git a/tests/1001-1500/1345. jump-game-iv/sol.py b/tests/1001-1500/1345. jump-game-iv/sol.py new file mode 100644 index 00000000..67d5f9ac --- /dev/null +++ b/tests/1001-1500/1345. jump-game-iv/sol.py @@ -0,0 +1,40 @@ +from collections import defaultdict, deque +from typing import List + + +class Solution: + def minJumps(self, arr: List[int]) -> int: + n = len(arr) + if n == 1: + return 0 + + mp = defaultdict(list) + for i in range(n): + mp[arr[i]].append(i) + + q = deque([(0, 0)]) + vis = [0] * n + vis[0] = 1 + + while q: + node, dist = q.popleft() + + if node == n - 1: + return dist + + if node - 1 >= 0 and not vis[node - 1]: + vis[node - 1] = 1 + q.append((node - 1, dist + 1)) + + if node + 1 < n and not vis[node + 1]: + vis[node + 1] = 1 + q.append((node + 1, dist + 1)) + + for nxt in mp[arr[node]]: + if not vis[nxt]: + vis[nxt] = 1 + q.append((nxt, dist + 1)) + + mp[arr[node]].clear() + + return -1 diff --git a/tests/1001-1500/1345. jump-game-iv/sol.py2 b/tests/1001-1500/1345. jump-game-iv/sol.py2 new file mode 100644 index 00000000..650ecd36 --- /dev/null +++ b/tests/1001-1500/1345. jump-game-iv/sol.py2 @@ -0,0 +1,35 @@ +class Solution(object): + def minJumps(self, arr): + n = len(arr) + if n == 1: + return 0 + + mp = {} + for i in range(n): + v = arr[i] + if v not in mp: + mp[v] = [] + mp[v].append(i) + + q = [(0, 0)] + vis = [0] * n + vis[0] = 1 + + head = 0 + while head < len(q): + node, dist = q[head] + head += 1 + if node == n - 1: + return dist + if node - 1 >= 0 and not vis[node - 1]: + vis[node - 1] = 1 + q.append((node - 1, dist + 1)) + if node + 1 < n and not vis[node + 1]: + vis[node + 1] = 1 + q.append((node + 1, dist + 1)) + for nxt in mp.get(arr[node], []): + if not vis[nxt]: + vis[nxt] = 1 + q.append((nxt, dist + 1)) + mp[arr[node]] = [] + return -1 diff --git a/tests/1001-1500/1345. jump-game-iv/sol.rb b/tests/1001-1500/1345. jump-game-iv/sol.rb new file mode 100644 index 00000000..08f72f44 --- /dev/null +++ b/tests/1001-1500/1345. jump-game-iv/sol.rb @@ -0,0 +1,39 @@ +# @param {Integer[]} arr +# @return {Integer} +def min_jumps(arr) + n = arr.length + return 0 if n == 1 + + mp = Hash.new { |h, k| h[k] = [] } + arr.each_with_index { |v, i| mp[v] << i } + + q = [[0, 0]] + vis = Array.new(n, 0) + vis[0] = 1 + + until q.empty? + node, dist = q.shift + return dist if node == n - 1 + + if node - 1 >= 0 && vis[node - 1] == 0 + vis[node - 1] = 1 + q << [node - 1, dist + 1] + end + + if node + 1 < n && vis[node + 1] == 0 + vis[node + 1] = 1 + q << [node + 1, dist + 1] + end + + mp[arr[node]].each do |nxt| + if vis[nxt] == 0 + vis[nxt] = 1 + q << [nxt, dist + 1] + end + end + + mp[arr[node]].clear + end + + -1 +end diff --git a/tests/1001-1500/1345. jump-game-iv/sol.rs b/tests/1001-1500/1345. jump-game-iv/sol.rs new file mode 100644 index 00000000..6aa815bb --- /dev/null +++ b/tests/1001-1500/1345. jump-game-iv/sol.rs @@ -0,0 +1,45 @@ +impl Solution { + pub fn min_jumps(arr: Vec) -> i32 { + let n = arr.len(); + if n == 1 { + return 0; + } + + use std::collections::{HashMap, VecDeque}; + let mut mp: HashMap> = HashMap::new(); + for i in 0..n { + mp.entry(arr[i]).or_insert_with(Vec::new).push(i); + } + + let mut q = VecDeque::new(); + q.push_back((0usize, 0i32)); + let mut vis = vec![false; n]; + vis[0] = true; + + while let Some((node, dist)) = q.pop_front() { + if node == n - 1 { + return dist; + } + + if node > 0 && !vis[node - 1] { + vis[node - 1] = true; + q.push_back((node - 1, dist + 1)); + } + if node + 1 < n && !vis[node + 1] { + vis[node + 1] = true; + q.push_back((node + 1, dist + 1)); + } + + if let Some(indices) = mp.get(&arr[node]) { + for &nxt in indices { + if !vis[nxt] { + vis[nxt] = true; + q.push_back((nxt, dist + 1)); + } + } + mp.get_mut(&arr[node]).unwrap().clear(); + } + } + -1 + } +} diff --git a/tests/1001-1500/1345. jump-game-iv/sol.swift b/tests/1001-1500/1345. jump-game-iv/sol.swift new file mode 100644 index 00000000..4d0952f3 --- /dev/null +++ b/tests/1001-1500/1345. jump-game-iv/sol.swift @@ -0,0 +1,40 @@ +class Solution { + func minJumps(_ arr: [Int]) -> Int { + let n = arr.count + if n == 1 { return 0 } + + var mp = [Int: [Int]]() + for i in 0..= 0 && !vis[node - 1] { + vis[node - 1] = true + q.append((node - 1, dist + 1)) + } + if node + 1 < n && !vis[node + 1] { + vis[node + 1] = true + q.append((node + 1, dist + 1)) + } + + for nxt in mp[arr[node], default: []] { + if !vis[nxt] { + vis[nxt] = true + q.append((nxt, dist + 1)) + } + } + mp[arr[node]]?.removeAll() + } + return -1 + } +} diff --git a/tests/1001-1500/1345. jump-game-iv/sol.ts b/tests/1001-1500/1345. jump-game-iv/sol.ts new file mode 100644 index 00000000..c2e80cb5 --- /dev/null +++ b/tests/1001-1500/1345. jump-game-iv/sol.ts @@ -0,0 +1,38 @@ +function minJumps(arr: number[]): number { + const n = arr.length; + if (n === 1) return 0; + + const mp: Map = new Map(); + for (let i = 0; i < n; i++) { + if (!mp.has(arr[i])) mp.set(arr[i], []); + mp.get(arr[i])!.push(i); + } + + const q: [number, number][] = [[0, 0]]; + const vis: boolean[] = new Array(n).fill(false); + vis[0] = true; + + let head = 0; + while (head < q.length) { + const [node, dist] = q[head++]; + if (node === n - 1) return dist; + + if (node - 1 >= 0 && !vis[node - 1]) { + vis[node - 1] = true; + q.push([node - 1, dist + 1]); + } + if (node + 1 < n && !vis[node + 1]) { + vis[node + 1] = true; + q.push([node + 1, dist + 1]); + } + + for (const nxt of mp.get(arr[node]) || []) { + if (!vis[nxt]) { + vis[nxt] = true; + q.push([nxt, dist + 1]); + } + } + mp.set(arr[node], []); + } + return -1; +} diff --git a/tests/1001-1500/1346. check-if-n-and-its-double-exist/manifest.yaml b/tests/1001-1500/1346. check-if-n-and-its-double-exist/manifest.yaml new file mode 100644 index 00000000..081bff7b --- /dev/null +++ b/tests/1001-1500/1346. check-if-n-and-its-double-exist/manifest.yaml @@ -0,0 +1,198 @@ +entry: + id: 1346 + title: "check-if-n-and-its-double-exist" + params: + arr: + type: array + items: + type: int + call: + cpp: "Solution().checkIfExist({arr})" + rust: "Solution::check_if_exist({arr})" + python3: "Solution().checkIfExist({arr})" + python2: "Solution().checkIfExist({arr})" + ruby: "check_if_exist({arr})" + java: "new Solution().checkIfExist({arr})" + csharp: "new Solution().CheckIfExist({arr})" + kotlin: "Solution().checkIfExist({arr})" + go: "checkIfExist({arr})" + dart: "Solution().checkIfExist({arr})" + swift: "Solution().checkIfExist({arr})" + typescript: "checkIfExist({arr})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().checkIfExist(arr, {result})" + checker: | + class Checker: + def checkIfExist(self, arr, result): + expected = any(i != j and arr[i] == 2 * arr[j] + for i in range(len(arr)) + for j in range(len(arr))) + return result == expected + +seed: 1346 + +tests: + - name: "example-one" + in: + arr: [10, 2, 5, 3] + - name: "example-two" + in: + arr: [3, 1, 7, 11] + - name: "positive-pair" + in: + arr: [2, 1] + - name: "negative-pair" + in: + arr: [-4, -2] + - name: "zero-single" + in: + arr: [0, 1] + - name: "zero-double" + in: + arr: [0, 0] + - name: "zero-with-values" + in: + arr: [0, 5, 10] + - name: "reverse-order" + in: + arr: [5, 10] + - name: "near-miss" + in: + arr: [5, 9] + - name: "negative-to-positive-miss" + in: + arr: [-5, 10] + - name: "mixed-sign-pair" + in: + arr: [-10, -5, 3, 7] + - name: "chain" + in: + arr: [1, 2, 4, 8] + - name: "reverse-chain" + in: + arr: [8, 4, 2, 1] + - name: "duplicate-nonzero" + in: + arr: [7, 7, 7, 14] + - name: "duplicate-half" + in: + arr: [6, 3, 3, 1] + - name: "all-equal-nonzero" + in: + arr: [5, 5, 5, 5] + - name: "all-zeros" + in: + arr: [0, 0, 0, 0] + - name: "minimum-values" + in: + arr: [-1000, -500] + - name: "maximum-values" + in: + arr: [500, 1000] + - name: "negative-chain" + in: + arr: [-1, -2, -4, -8] + - name: "only-odd-values" + in: + arr: [1, 3, 5, 7, 9] + - name: "even-values-no-pair" + in: + arr: [2, 6, 10, 14] + - name: "pair-among-noise" + in: + arr: [13, -7, 4, 99, 8, 21] + - name: "large-negative-pair" + in: + arr: [-1000, -500, 1, 3] + - name: "one-direction-only" + in: + arr: [16, 8, 2, 5, 11] + - name: "same-value-not-double" + in: + arr: [1, 1] + - name: "zero-and-negative" + in: + arr: [0, -1, -2] + - name: "interleaved-chain" + in: + arr: [1, 9, 2, 7, 4, 3] + - name: "maximum-no-pair" + in: + arr: [999, 1000, -999, -998] + - name: "many-duplicates" + in: + arr: [2, 2, 2, 4, 4, 9] + - name: "boundary-half" + in: + arr: [-500, -1000, 500, 1000] + - name: "minimum-without-half" + in: + arr: [-1000, -499, 37] + - name: "maximum-without-half" + in: + arr: [1000, 499, -37] + - name: "zero-needs-two-occurrences" + in: + arr: [0, -999, 501, 251] + - name: "opposite-sign-magnitudes" + in: + arr: [-512, 256, -128, 64] + - name: "generated-small" + in: + arr: + gen: "array" + len: 10 + of: + gen: "int" + min: -20 + max: 20 + elemType: "int" + - name: "generated-medium" + in: + arr: + gen: "array" + len: 100 + of: + gen: "int" + min: -1000 + max: 1000 + elemType: "int" + - name: "generated-large" + in: + arr: + gen: "array" + len: 500 + of: + gen: "int" + min: -1000 + max: 1000 + elemType: "int" + - name: "generated-narrow-domain" + in: + arr: + gen: "array" + len: 200 + of: + gen: "int" + min: -3 + max: 3 + elemType: "int" + - name: "generated-boundary-domain" + in: + arr: + gen: "array" + len: 500 + of: + gen: "int" + min: -1000 + max: 1000 + elemType: "int" diff --git a/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.cpp b/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.cpp new file mode 100644 index 00000000..29d0e94f --- /dev/null +++ b/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + bool checkIfExist(vector& arr) { + int zeroCount = 0; + for (int num : arr) { + if (num == 0) zeroCount++; + } + if (zeroCount >= 2) return true; + + for (int i : arr) { + if (i != 0) { + for (int j : arr) { + if (j == i * 2) return true; + } + } + } + return false; + } +}; diff --git a/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.cs b/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.cs new file mode 100644 index 00000000..736eecf3 --- /dev/null +++ b/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.cs @@ -0,0 +1,18 @@ +public class Solution { + public bool CheckIfExist(int[] arr) { + int zeroCount = 0; + foreach (int num in arr) { + if (num == 0) zeroCount++; + } + if (zeroCount >= 2) return true; + + foreach (int i in arr) { + if (i != 0) { + foreach (int j in arr) { + if (j == i * 2) return true; + } + } + } + return false; + } +} diff --git a/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.dart b/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.dart new file mode 100644 index 00000000..d5d14296 --- /dev/null +++ b/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.dart @@ -0,0 +1,12 @@ +class Solution { + bool checkIfExist(List arr) { + if (arr.where((e) => e == 0).length >= 2) return true; + + for (var i in arr) { + if (i != 0 && arr.contains(i * 2)) { + return true; + } + } + return false; + } +} diff --git a/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.go b/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.go new file mode 100644 index 00000000..e253ecbf --- /dev/null +++ b/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.go @@ -0,0 +1,22 @@ +func checkIfExist(arr []int) bool { + zeroCount := 0 + for _, v := range arr { + if v == 0 { + zeroCount++ + } + } + if zeroCount >= 2 { + return true + } + + for _, i := range arr { + if i != 0 { + for _, j := range arr { + if j == i*2 { + return true + } + } + } + } + return false +} diff --git a/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.java b/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.java new file mode 100644 index 00000000..cdaad79c --- /dev/null +++ b/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.java @@ -0,0 +1,18 @@ +class Solution { + public boolean checkIfExist(int[] arr) { + int zeroCount = 0; + for (int num : arr) { + if (num == 0) zeroCount++; + } + if (zeroCount >= 2) return true; + + for (int i : arr) { + if (i != 0) { + for (int j : arr) { + if (j == i * 2) return true; + } + } + } + return false; + } +} diff --git a/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.kt b/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.kt new file mode 100644 index 00000000..0b326e09 --- /dev/null +++ b/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.kt @@ -0,0 +1,12 @@ +class Solution { + fun checkIfExist(arr: IntArray): Boolean { + if (arr.count { it == 0 } >= 2) return true + + for (i in arr) { + if (i != 0 && arr.contains(i * 2)) { + return true + } + } + return false + } +} diff --git a/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.py b/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.py new file mode 100644 index 00000000..196eb47e --- /dev/null +++ b/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.py @@ -0,0 +1,10 @@ +class Solution(object): + def checkIfExist(self, arr): + if arr.count(0) >= 2: + return True + + for i in arr: + if i != 0 and i * 2 in arr: + return True + + return False diff --git a/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.py2 b/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.py2 new file mode 100644 index 00000000..196eb47e --- /dev/null +++ b/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.py2 @@ -0,0 +1,10 @@ +class Solution(object): + def checkIfExist(self, arr): + if arr.count(0) >= 2: + return True + + for i in arr: + if i != 0 and i * 2 in arr: + return True + + return False diff --git a/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.rb b/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.rb new file mode 100644 index 00000000..3c179515 --- /dev/null +++ b/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.rb @@ -0,0 +1,13 @@ +# @param {Integer[]} arr +# @return {Boolean} +def check_if_exist(arr) + return true if arr.count(0) >= 2 + + arr.each do |i| + if i != 0 && arr.include?(i * 2) + return true + end + end + + false +end diff --git a/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.rs b/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.rs new file mode 100644 index 00000000..b3c57874 --- /dev/null +++ b/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.rs @@ -0,0 +1,14 @@ +impl Solution { + pub fn check_if_exist(arr: Vec) -> bool { + if arr.iter().filter(|&&x| x == 0).count() >= 2 { + return true; + } + + for &i in &arr { + if i != 0 && arr.contains(&(i * 2)) { + return true; + } + } + false + } +} diff --git a/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.swift b/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.swift new file mode 100644 index 00000000..22db7c69 --- /dev/null +++ b/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.swift @@ -0,0 +1,14 @@ +class Solution { + func checkIfExist(_ arr: [Int]) -> Bool { + if arr.filter({ $0 == 0 }).count >= 2 { + return true + } + + for i in arr { + if i != 0 && arr.contains(i * 2) { + return true + } + } + return false + } +} diff --git a/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.ts b/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.ts new file mode 100644 index 00000000..a54b2279 --- /dev/null +++ b/tests/1001-1500/1346. check-if-n-and-its-double-exist/sol.ts @@ -0,0 +1,10 @@ +function checkIfExist(arr: number[]): boolean { + if (arr.filter((x) => x === 0).length >= 2) return true; + + for (const i of arr) { + if (i !== 0 && arr.includes(i * 2)) { + return true; + } + } + return false; +} diff --git a/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/manifest.yaml b/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/manifest.yaml new file mode 100644 index 00000000..2f3f3c81 --- /dev/null +++ b/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/manifest.yaml @@ -0,0 +1,269 @@ +entry: + id: 1347 + title: "minimum-number-of-steps-to-make-two-strings-anagram" + params: + s: + type: string + t: + type: string + call: + cpp: "Solution().minSteps({s}, {t})" + rust: "Solution::min_steps({s}, {t})" + python3: "Solution().minSteps({s}, {t})" + python2: "Solution().minSteps({s}, {t})" + ruby: "min_steps({s}, {t})" + java: "new Solution().minSteps({s}, {t})" + csharp: "new Solution().MinSteps({s}, {t})" + kotlin: "Solution().minSteps({s}, {t})" + go: "minSteps({s}, {t})" + dart: "Solution().minSteps({s}, {t})" + swift: "Solution().minSteps({s}, {t})" + typescript: "minSteps({s}, {t})" +judge: + type: exact +limits: + time_ms: 300 + memory_mb: 300 +oracle: + python3: + call: "Checker().minSteps(s, t, {result})" + checker: | + from collections import Counter + + class Checker: + def minSteps(self, s, t, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + return result == sum((Counter(t) - Counter(s)).values()) +seed: 1347 +tests: + - name: example_bab_aba + in: + s: "bab" + t: "aba" + out: 1 + - name: example_leetcode_practice + in: + s: "leetcode" + t: "practice" + out: 5 + - name: example_existing_anagrams + in: + s: "anagram" + t: "mangaar" + out: 0 + - name: minimum_same_character + in: + s: "a" + t: "a" + out: 0 + - name: minimum_different_characters + in: + s: "a" + t: "z" + out: 1 + - name: same_repeated_character + in: + s: "aaaaaa" + t: "aaaaaa" + out: 0 + - name: reordered_alphabet + in: + s: "abcdefghijklmnopqrstuvwxyz" + t: "zyxwvutsrqponmlkjihgfedcba" + out: 0 + - name: entirely_disjoint_six_letters + in: + s: "abcdef" + t: "ghijkl" + out: 6 + - name: one_replacement_needed + in: + s: "abc" + t: "abd" + out: 1 + - name: duplicate_deficit + in: + s: "aabb" + t: "bbbb" + out: 2 + - name: two_missing_copies + in: + s: "aab" + t: "bcc" + out: 2 + - name: all_t_characters_wrong + in: + s: "aaaaaaaaaa" + t: "bbbbbbbbbb" + out: 10 + - name: excess_single_vowel + in: + s: "aeiou" + t: "uuuuu" + out: 4 + - name: no_common_consonants + in: + s: "bcd" + t: "aaa" + out: 3 + - name: dominant_target_character + in: + s: "abacaba" + t: "ccccccc" + out: 6 + - name: target_overrepresents_existing_letter + in: + s: "zzzyyyxxx" + t: "xxxxxxxxx" + out: 6 + - name: permutation_with_different_order + in: + s: "qwerty" + t: "ytrewq" + out: 0 + - name: partial_overlap_hello_world + in: + s: "hello" + t: "world" + out: 3 + - name: one_unmatched_letter_banana + in: + s: "banana" + t: "ananas" + out: 1 + - name: repeated_letter_anagram + in: + s: "mississippi" + t: "ippissimiss" + out: 0 + - name: four_unmatched_letters + in: + s: "computer" + t: "terminal" + out: 4 + - name: shifted_word_anagram + in: + s: "algorithm" + t: "logarithm" + out: 0 + - name: transposed_word_anagram + in: + s: "python" + t: "typhon" + out: 0 + - name: target_lacks_two_letter_kinds + in: + s: "abcabc" + t: "aaaaaa" + out: 4 + - name: ten_distinct_source_letters + in: + s: "abcdefghij" + t: "aaaaaaaaaa" + out: 9 + - name: half_overlap_with_new_letters + in: + s: "aabbccddee" + t: "fghijabcde" + out: 5 + - name: balanced_source_target_one_letter + in: + s: "abcabcabcabc" + t: "bbbbbbbbbbbb" + out: 8 + - name: long_distinct_permutation + in: + s: "abcdefghijklmno" + t: "onmlkjihgfedcba" + out: 0 + - name: repeated_pairs_permutation + in: + s: "aabbccddeeff" + t: "ffeeddccbbaa" + out: 0 + - name: dormitory_dirtyroom + in: + s: "dormitory" + t: "dirtyroom" + out: 0 + - name: conversation_conservation + in: + s: "conversation" + t: "conservation" + out: 0 + - name: sixteen_character_target_excess + in: + s: "aabbccddeeffgghh" + t: "hhhhhhhhhhhhhhhh" + out: 14 + - name: twenty_character_reverse + in: + s: "abcdefghijklmnopqrst" + t: "tsrqponmlkjihgfedcba" + out: 0 + - name: final_counting_case + in: + s: "aabbbcccc" + t: "ccccccccc" + out: 5 + - name: complete_three_copy_deficit + in: + s: "aaabbbcccddd" + t: "aaacccdddzzz" + out: 3 + - name: generated_single_letter + seed: 13471 + in: + s: + gen: "str" + len: 1 + alphabet: "abc" + t: + gen: "str" + len: 1 + alphabet: "abc" + - name: generated_short_full_alphabet + seed: 13472 + in: + s: + gen: "str" + len: 37 + alphabet: "abcdefghijklmnopqrstuvwxyz" + t: + gen: "str" + len: 37 + alphabet: "abcdefghijklmnopqrstuvwxyz" + - name: generated_medium_two_letter_skew + seed: 13473 + in: + s: + gen: "str" + len: 1000 + alphabet: "ab" + t: + gen: "str" + len: 1000 + alphabet: "ab" + - name: generated_maximum_binary_alphabet + seed: 13474 + in: + s: + gen: "str" + len: 50000 + alphabet: "az" + t: + gen: "str" + len: 50000 + alphabet: "az" + - name: generated_maximum_full_alphabet + seed: 13475 + in: + s: + gen: "str" + len: 50000 + alphabet: "abcdefghijklmnopqrstuvwxyz" + t: + gen: "str" + len: 50000 + alphabet: "abcdefghijklmnopqrstuvwxyz" diff --git a/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.cpp b/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.cpp new file mode 100644 index 00000000..39f86fba --- /dev/null +++ b/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int minSteps(string s, string t) { + unordered_map dic; + for (char ch : t) { + dic[ch]++; + } + for (char ch : s) { + if (dic.count(ch) && dic[ch] > 0) { + dic[ch]--; + } + } + int sum = 0; + for (auto& [key, val] : dic) { + sum += val; + } + return sum; + } +}; diff --git a/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.cs b/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.cs new file mode 100644 index 00000000..c18d0f03 --- /dev/null +++ b/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.cs @@ -0,0 +1,19 @@ +public class Solution { + public int MinSteps(string s, string t) { + var dic = new Dictionary(); + foreach (char ch in t) { + if (dic.ContainsKey(ch)) dic[ch]++; + else dic[ch] = 1; + } + foreach (char ch in s) { + if (dic.ContainsKey(ch) && dic[ch] > 0) { + dic[ch]--; + } + } + int sum = 0; + foreach (var val in dic.Values) { + sum += val; + } + return sum; + } +} diff --git a/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.dart b/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.dart new file mode 100644 index 00000000..64bd112e --- /dev/null +++ b/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.dart @@ -0,0 +1,14 @@ +class Solution { + int minSteps(String s, String t) { + var dic = {}; + for (var ch in t.split('')) { + dic[ch] = (dic[ch] ?? 0) + 1; + } + for (var ch in s.split('')) { + if (dic.containsKey(ch) && dic[ch]! > 0) { + dic[ch] = dic[ch]! - 1; + } + } + return dic.values.fold(0, (a, b) => a + b); + } +} diff --git a/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.go b/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.go new file mode 100644 index 00000000..b6d91f09 --- /dev/null +++ b/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.go @@ -0,0 +1,16 @@ +func minSteps(s string, t string) int { + dic := make(map[rune]int) + for _, ch := range t { + dic[ch]++ + } + for _, ch := range s { + if val, ok := dic[ch]; ok && val > 0 { + dic[ch]-- + } + } + sum := 0 + for _, val := range dic { + sum += val + } + return sum +} diff --git a/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.java b/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.java new file mode 100644 index 00000000..dc2888cf --- /dev/null +++ b/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.java @@ -0,0 +1,18 @@ +class Solution { + public int minSteps(String s, String t) { + java.util.Map dic = new java.util.HashMap<>(); + for (char ch : t.toCharArray()) { + dic.put(ch, dic.getOrDefault(ch, 0) + 1); + } + for (char ch : s.toCharArray()) { + if (dic.containsKey(ch) && dic.get(ch) > 0) { + dic.put(ch, dic.get(ch) - 1); + } + } + int sum = 0; + for (int val : dic.values()) { + sum += val; + } + return sum; + } +} diff --git a/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.kt b/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.kt new file mode 100644 index 00000000..586e0ae3 --- /dev/null +++ b/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.kt @@ -0,0 +1,14 @@ +class Solution { + fun minSteps(s: String, t: String): Int { + val dic = mutableMapOf() + for (ch in t) { + dic[ch] = dic.getOrDefault(ch, 0) + 1 + } + for (ch in s) { + if (dic.containsKey(ch) && dic[ch]!! > 0) { + dic[ch] = dic[ch]!! - 1 + } + } + return dic.values.sum() + } +} diff --git a/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.py b/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.py new file mode 100644 index 00000000..c8d386dc --- /dev/null +++ b/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.py @@ -0,0 +1,12 @@ +class Solution: + def minSteps(self, s: str, t: str) -> int: + dic = {} + + for ch in t: + dic[ch] = dic.get(ch, 0) + 1 + + for ch in s: + if ch in dic and dic[ch] > 0: + dic[ch] -= 1 + + return sum(dic.values()) diff --git a/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.py2 b/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.py2 new file mode 100644 index 00000000..448c6fc7 --- /dev/null +++ b/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.py2 @@ -0,0 +1,14 @@ +class Solution(object): + def minSteps(self, s, t): + """ + :type s: str + :type t: str + :rtype: int + """ + dic = {} + for ch in t: + dic[ch] = dic.get(ch, 0) + 1 + for ch in s: + if ch in dic and dic[ch] > 0: + dic[ch] -= 1 + return sum(dic.values()) diff --git a/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.rb b/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.rb new file mode 100644 index 00000000..547f4102 --- /dev/null +++ b/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.rb @@ -0,0 +1,9 @@ +# @param {String} s +# @param {String} t +# @return {Integer} +def min_steps(s, t) + dic = Hash.new(0) + t.each_char { |ch| dic[ch] += 1 } + s.each_char { |ch| dic[ch] -= 1 if dic[ch] > 0 } + dic.values.sum +end diff --git a/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.rs b/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.rs new file mode 100644 index 00000000..daafec35 --- /dev/null +++ b/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.rs @@ -0,0 +1,17 @@ +impl Solution { + pub fn min_steps(s: String, t: String) -> i32 { + use std::collections::HashMap; + let mut dic = HashMap::new(); + for ch in t.chars() { + *dic.entry(ch).or_insert(0) += 1; + } + for ch in s.chars() { + if let Some(count) = dic.get_mut(&ch) { + if *count > 0 { + *count -= 1; + } + } + } + dic.values().sum() + } +} diff --git a/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.swift b/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.swift new file mode 100644 index 00000000..bcb1f5f0 --- /dev/null +++ b/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.swift @@ -0,0 +1,14 @@ +class Solution { + func minSteps(_ s: String, _ t: String) -> Int { + var dic = [Character: Int]() + for ch in t { + dic[ch, default: 0] += 1 + } + for ch in s { + if let count = dic[ch], count > 0 { + dic[ch] = count - 1 + } + } + return dic.values.reduce(0, +) + } +} diff --git a/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.ts b/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.ts new file mode 100644 index 00000000..335cdfde --- /dev/null +++ b/tests/1001-1500/1347. minimum-number-of-steps-to-make-two-strings-anagram/sol.ts @@ -0,0 +1,12 @@ +function minSteps(s: string, t: string): number { + const dic: { [key: string]: number } = {}; + for (const ch of t) { + dic[ch] = (dic[ch] || 0) + 1; + } + for (const ch of s) { + if (dic[ch] && dic[ch] > 0) { + dic[ch]--; + } + } + return Object.values(dic).reduce((sum, val) => sum + val, 0); +} diff --git a/tests/1001-1500/1349. maximum-students-taking-exam/manifest.yaml b/tests/1001-1500/1349. maximum-students-taking-exam/manifest.yaml new file mode 100644 index 00000000..2f6d08fc --- /dev/null +++ b/tests/1001-1500/1349. maximum-students-taking-exam/manifest.yaml @@ -0,0 +1,386 @@ +entry: + id: 1349 + title: "maximum-students-taking-exam" + params: + seats: + type: array + items: + type: array + items: + type: char + call: + cpp: "Solution().maxStudents({seats})" + rust: "Solution::max_students({seats})" + python3: "Solution().maxStudents({seats})" + python2: "Solution().maxStudents({seats})" + ruby: "max_students({seats})" + java: "new Solution().maxStudents({seats})" + csharp: "new Solution().MaxStudents({seats})" + kotlin: "Solution().maxStudents({seats})" + go: "maxStudents({seats})" + dart: "Solution().maxStudents({seats})" + swift: "Solution().maxStudents({seats})" + typescript: "maxStudents({seats})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().maxStudents(seats, {result})" + checker: | + class Checker: + def maxStudents(self, seats, result): + m, n = len(seats), len(seats[0]) + masks = [] + for row in seats: + allowed = [] + for mask in range(1 << n): + if mask & (mask << 1): + continue + if any(row[c] == '#' and (mask >> c) & 1 for c in range(n)): + continue + allowed.append(mask) + masks.append(allowed) + dp = {0: 0} + for r in range(m): + nxt = {} + for mask in masks[r]: + best = 0 + for prev, value in dp.items(): + if mask & (prev << 1) or mask & (prev >> 1): + continue + best = max(best, value + mask.bit_count()) + nxt[mask] = best + dp = nxt + return result == max(dp.values(), default=0) + +seed: 1349 + +tests: + - name: "example-one" + in: + seats: + - ["#", ".", "#", "#", ".", "#"] + - [".", "#", "#", "#", "#", "."] + - ["#", ".", "#", "#", ".", "#"] + - name: "example-two" + in: + seats: + - [".", "#"] + - ["#", "#"] + - ["#", "."] + - ["#", "#"] + - [".", "#"] + - name: "example-three" + in: + seats: + - ["#", ".", ".", ".", "#"] + - [".", "#", ".", "#", "."] + - [".", ".", "#", ".", "."] + - [".", "#", ".", "#", "."] + - ["#", ".", ".", ".", "#"] + - name: "single-good" + in: + seats: + - ["."] + - name: "single-broken" + in: + seats: + - ["#"] + - name: "one-row-open" + in: + seats: + - [".", ".", ".", ".", "."] + - name: "one-row-broken" + in: + seats: + - ["#", "#", "#", "#"] + - name: "one-row-alternating" + in: + seats: + - [".", "#", ".", "#", ".", "#", "."] + - name: "two-by-two-open" + in: + seats: + - [".", "."] + - [".", "."] + - name: "generated-large-01" + seed: 134901 + in: + seats: + gen: "array" + len: 8 + elemType: "char" + of: + gen: "array" + len: 8 + elemType: "char" + of: + gen: "char" + variety: [".", "#"] + - name: "two-by-five-checker" + in: + seats: + - [".", "#", ".", "#", "."] + - ["#", ".", "#", ".", "#"] + - name: "two-by-six-middle-broken" + in: + seats: + - [".", ".", "#", "#", ".", "."] + - [".", ".", ".", ".", ".", "."] + - name: "generated-large-02" + seed: 134902 + in: + seats: + gen: "array" + len: 8 + elemType: "char" + of: + gen: "array" + len: 8 + elemType: "char" + of: + gen: "char" + variety: [".", "#"] + - name: "three-by-three-center" + in: + seats: + - [".", ".", "."] + - [".", "#", "."] + - [".", ".", "."] + - name: "three-by-three-diagonal" + in: + seats: + - [".", "#", "#"] + - ["#", ".", "#"] + - ["#", "#", "."] + - name: "three-by-four-stripes" + in: + seats: + - [".", ".", "#", "#"] + - ["#", "#", ".", "."] + - [".", ".", "#", "#"] + - name: "three-by-five-sparse" + in: + seats: + - [".", "#", ".", "#", "."] + - [".", ".", "#", ".", "."] + - ["#", ".", ".", ".", "#"] + - name: "generated-large-03" + seed: 134903 + in: + seats: + gen: "array" + len: 8 + elemType: "char" + of: + gen: "array" + len: 8 + elemType: "char" + of: + gen: "char" + variety: [".", "#"] + - name: "four-by-four-broken-border" + in: + seats: + - ["#", ".", ".", "#"] + - [".", ".", ".", "."] + - [".", ".", ".", "."] + - ["#", ".", ".", "#"] + - name: "four-by-five-alternating" + in: + seats: + - [".", "#", ".", "#", "."] + - ["#", ".", "#", ".", "#"] + - [".", "#", ".", "#", "."] + - ["#", ".", "#", ".", "#"] + - name: "four-by-six-middle" + in: + seats: + - [".", ".", ".", ".", ".", "."] + - [".", "#", "#", "#", "#", "."] + - [".", ".", ".", ".", ".", "."] + - [".", "#", "#", "#", "#", "."] + - name: "generated-large-04" + seed: 134904 + in: + seats: + gen: "array" + len: 8 + elemType: "char" + of: + gen: "array" + len: 8 + elemType: "char" + of: + gen: "char" + variety: [".", "#"] + - name: "five-by-five-cross" + in: + seats: + - [".", ".", "#", ".", "."] + - [".", ".", "#", ".", "."] + - ["#", "#", "#", "#", "#"] + - [".", ".", "#", ".", "."] + - [".", ".", "#", ".", "."] + - name: "five-by-six-random" + in: + seats: + - ["#", ".", ".", "#", ".", "."] + - [".", ".", "#", ".", ".", "#"] + - [".", "#", ".", ".", "#", "."] + - ["#", ".", ".", "#", ".", "."] + - [".", ".", "#", ".", ".", "#"] + - name: "generated-large-05" + seed: 134905 + in: + seats: + gen: "array" + len: 8 + elemType: "char" + of: + gen: "array" + len: 8 + elemType: "char" + of: + gen: "char" + variety: [".", "#"] + - name: "six-by-seven-blocked" + in: + seats: + - [".", ".", "#", "#", ".", ".", "."] + - [".", "#", "#", "#", "#", ".", "."] + - [".", ".", ".", ".", ".", ".", "."] + - [".", "#", ".", "#", ".", "#", "."] + - [".", ".", ".", ".", ".", ".", "."] + - ["#", ".", "#", ".", "#", ".", "#"] + - name: "seven-by-seven-sparse" + in: + seats: + - [".", "#", ".", "#", ".", "#", "."] + - ["#", ".", "#", ".", "#", ".", "#"] + - [".", ".", ".", ".", ".", ".", "."] + - ["#", "#", ".", ".", ".", "#", "#"] + - [".", ".", ".", ".", ".", ".", "."] + - ["#", ".", "#", ".", "#", ".", "#"] + - [".", "#", ".", "#", ".", "#", "."] + - name: "eight-by-eight-open" + in: + seats: + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - name: "eight-by-eight-broken" + in: + seats: + - ["#", "#", "#", "#", "#", "#", "#", "#"] + - ["#", ".", ".", ".", ".", ".", ".", "#"] + - ["#", ".", "#", "#", "#", "#", ".", "#"] + - ["#", ".", "#", ".", ".", "#", ".", "#"] + - ["#", ".", "#", ".", ".", "#", ".", "#"] + - ["#", ".", "#", "#", "#", "#", ".", "#"] + - ["#", ".", ".", ".", ".", ".", ".", "#"] + - ["#", "#", "#", "#", "#", "#", "#", "#"] + - name: "one-by-eight-alternating" + in: + seats: + - [".", "#", ".", "#", ".", "#", ".", "#"] + - name: "generated-large-06" + seed: 134906 + in: + seats: + gen: "array" + len: 8 + elemType: "char" + of: + gen: "array" + len: 8 + elemType: "char" + of: + gen: "char" + variety: [".", "#"] + - name: "three-by-eight-center-wall" + in: + seats: + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", "#", "#", "#", "#", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - name: "seven-by-three-open" + in: + seats: + - [".", ".", "."] + - [".", ".", "."] + - [".", ".", "."] + - [".", ".", "."] + - [".", ".", "."] + - [".", ".", "."] + - [".", ".", "."] + - name: "eight-by-two-alternating" + in: + seats: + - [".", "#"] + - ["#", "."] + - [".", "#"] + - ["#", "."] + - [".", "#"] + - ["#", "."] + - [".", "#"] + - ["#", "."] + - name: "one-by-eight-open" + in: + seats: + - [".", ".", ".", ".", ".", ".", ".", "."] + - name: "eight-by-one-open" + in: + seats: + - ["."] + - ["."] + - ["."] + - ["."] + - ["."] + - ["."] + - ["."] + - ["."] + - name: "eight-by-eight-all-broken" + in: + seats: + - ["#", "#", "#", "#", "#", "#", "#", "#"] + - ["#", "#", "#", "#", "#", "#", "#", "#"] + - ["#", "#", "#", "#", "#", "#", "#", "#"] + - ["#", "#", "#", "#", "#", "#", "#", "#"] + - ["#", "#", "#", "#", "#", "#", "#", "#"] + - ["#", "#", "#", "#", "#", "#", "#", "#"] + - ["#", "#", "#", "#", "#", "#", "#", "#"] + - ["#", "#", "#", "#", "#", "#", "#", "#"] + - name: "eight-by-eight-single-diagonal" + in: + seats: + - [".", "#", "#", "#", "#", "#", "#", "#"] + - ["#", ".", "#", "#", "#", "#", "#", "#"] + - ["#", "#", ".", "#", "#", "#", "#", "#"] + - ["#", "#", "#", ".", "#", "#", "#", "#"] + - ["#", "#", "#", "#", ".", "#", "#", "#"] + - ["#", "#", "#", "#", "#", ".", "#", "#"] + - ["#", "#", "#", "#", "#", "#", ".", "#"] + - ["#", "#", "#", "#", "#", "#", "#", "."] + - name: "eight-by-eight-offset-zigzag" + in: + seats: + - [".", ".", "#", "#", "#", "#", "#", "#"] + - ["#", ".", ".", "#", "#", "#", "#", "#"] + - ["#", "#", ".", ".", "#", "#", "#", "#"] + - ["#", "#", "#", ".", ".", "#", "#", "#"] + - ["#", "#", "#", "#", ".", ".", "#", "#"] + - ["#", "#", "#", "#", "#", ".", ".", "#"] + - ["#", "#", "#", "#", "#", "#", ".", "."] + - [".", "#", "#", "#", "#", "#", "#", "."] diff --git a/tests/1001-1500/1349. maximum-students-taking-exam/sol.cpp b/tests/1001-1500/1349. maximum-students-taking-exam/sol.cpp new file mode 100644 index 00000000..8f2150c6 --- /dev/null +++ b/tests/1001-1500/1349. maximum-students-taking-exam/sol.cpp @@ -0,0 +1,44 @@ +class Solution { +public: + int maxStudents(vector>& seats) { + int m = seats.size(); + int n = seats[0].size(); + vector available(m); + for (int i = 0; i < m; i++) { + int mask = 0; + for (int j = 0; j < n; j++) { + if (seats[i][j] == '.') { + mask |= 1 << j; + } + } + available[i] = mask; + } + + vector validMasks; + for (int mask = 0; mask < (1 << n); mask++) { + if ((mask & (mask << 1)) == 0) { + validMasks.push_back(mask); + } + } + + unordered_map dp{{0, 0}}; + for (int row = 0; row < m; row++) { + unordered_map nextDp; + for (int current : validMasks) { + if (current & ~available[row]) continue; + int count = __builtin_popcount(current); + for (auto& [previous, total] : dp) { + if (current & ((previous << 1) | (previous >> 1))) continue; + nextDp[current] = max(nextDp[current], total + count); + } + } + dp = nextDp; + } + + int maxVal = 0; + for (auto& [_, val] : dp) { + maxVal = max(maxVal, val); + } + return maxVal; + } +}; diff --git a/tests/1001-1500/1349. maximum-students-taking-exam/sol.cs b/tests/1001-1500/1349. maximum-students-taking-exam/sol.cs new file mode 100644 index 00000000..0e00dfa4 --- /dev/null +++ b/tests/1001-1500/1349. maximum-students-taking-exam/sol.cs @@ -0,0 +1,54 @@ +public class Solution { + private int PopCount(int value) { + int count = 0; + while (value != 0) { value &= value - 1; count++; } + return count; + } + public int MaxStudents(char[][] seats) { + int m = seats.Length; + int n = seats[0].Length; + int[] available = new int[m]; + for (int i = 0; i < m; i++) { + int mask = 0; + for (int j = 0; j < n; j++) { + if (seats[i][j] == '.') { + mask |= 1 << j; + } + } + available[i] = mask; + } + + var validMasks = new System.Collections.Generic.List(); + for (int mask = 0; mask < (1 << n); mask++) { + if ((mask & (mask << 1)) == 0) { + validMasks.Add(mask); + } + } + + var dp = new System.Collections.Generic.Dictionary { { 0, 0 } }; + for (int row = 0; row < m; row++) { + var nextDp = new System.Collections.Generic.Dictionary(); + foreach (int current in validMasks) { + if ((current & ~available[row]) != 0) continue; + int count = PopCount(current); + foreach (var pair in dp) { + int previous = pair.Key; + int total = pair.Value; + if ((current & ((previous << 1) | (previous >> 1))) != 0) continue; + if (nextDp.ContainsKey(current)) { + nextDp[current] = Math.Max(nextDp[current], total + count); + } else { + nextDp[current] = total + count; + } + } + } + dp = nextDp; + } + + int maxVal = 0; + foreach (int val in dp.Values) { + maxVal = Math.Max(maxVal, val); + } + return maxVal; + } +} diff --git a/tests/1001-1500/1349. maximum-students-taking-exam/sol.dart b/tests/1001-1500/1349. maximum-students-taking-exam/sol.dart new file mode 100644 index 00000000..0099ffad --- /dev/null +++ b/tests/1001-1500/1349. maximum-students-taking-exam/sol.dart @@ -0,0 +1,44 @@ +class Solution { + int maxStudents(List> seats) { + int m = seats.length; + int n = seats[0].length; + List available = []; + for (var row in seats) { + int mask = 0; + for (int col = 0; col < n; col++) { + if (row[col] == ".") { + mask |= 1 << col; + } + } + available.add(mask); + } + + List validMasks = []; + for (int mask = 0; mask < (1 << n); mask++) { + if ((mask & (mask << 1)) == 0) { + validMasks.add(mask); + } + } + + Map dp = {0: 0}; + for (int row = 0; row < m; row++) { + Map nextDp = {}; + for (var current in validMasks) { + if ((current & ~available[row]) != 0) continue; + int count = current.toRadixString(2).split('').where((c) => c == '1').length; + dp.forEach((previous, total) { + if ((current & ((previous << 1) | (previous >> 1))) != 0) return; + nextDp[current] = nextDp.containsKey(current) + ? max(nextDp[current]!, total + count) + : total + count; + }); + } + dp = nextDp; + } + + if (dp.isEmpty) return 0; + return dp.values.reduce((a, b) => a > b ? a : b); + } + + int max(int a, int b) => a > b ? a : b; +} diff --git a/tests/1001-1500/1349. maximum-students-taking-exam/sol.go b/tests/1001-1500/1349. maximum-students-taking-exam/sol.go new file mode 100644 index 00000000..fe6c563b --- /dev/null +++ b/tests/1001-1500/1349. maximum-students-taking-exam/sol.go @@ -0,0 +1,58 @@ +func maxStudents(seats [][]byte) int { + m := len(seats) + n := len(seats[0]) + available := make([]int, m) + for i := 0; i < m; i++ { + mask := 0 + for j := 0; j < n; j++ { + if seats[i][j] == '.' { + mask |= 1 << j + } + } + available[i] = mask + } + + var validMasks []int + for mask := 0; mask < (1 << n); mask++ { + if mask&(mask<<1) == 0 { + validMasks = append(validMasks, mask) + } + } + + dp := map[int]int{0: 0} + for row := 0; row < m; row++ { + nextDp := map[int]int{} + for _, current := range validMasks { + if current & ^available[row] != 0 { + continue + } + count := bits.OnesCount(uint(current)) + for previous, total := range dp { + if current&((previous<<1)|(previous>>1)) != 0 { + continue + } + if val, ok := nextDp[current]; ok { + nextDp[current] = max(val, total+count) + } else { + nextDp[current] = total + count + } + } + } + dp = nextDp + } + + maxVal := 0 + for _, val := range dp { + if val > maxVal { + maxVal = val + } + } + return maxVal +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} diff --git a/tests/1001-1500/1349. maximum-students-taking-exam/sol.java b/tests/1001-1500/1349. maximum-students-taking-exam/sol.java new file mode 100644 index 00000000..a438ec7e --- /dev/null +++ b/tests/1001-1500/1349. maximum-students-taking-exam/sol.java @@ -0,0 +1,46 @@ +class Solution { + public int maxStudents(char[][] seats) { + int m = seats.length; + int n = seats[0].length; + int[] available = new int[m]; + for (int i = 0; i < m; i++) { + int mask = 0; + for (int j = 0; j < n; j++) { + if (seats[i][j] == '.') { + mask |= 1 << j; + } + } + available[i] = mask; + } + + java.util.List validMasks = new java.util.ArrayList<>(); + for (int mask = 0; mask < (1 << n); mask++) { + if ((mask & (mask << 1)) == 0) { + validMasks.add(mask); + } + } + + java.util.Map dp = new java.util.HashMap<>(); + dp.put(0, 0); + for (int row = 0; row < m; row++) { + java.util.Map nextDp = new java.util.HashMap<>(); + for (int current : validMasks) { + if ((current & ~available[row]) != 0) continue; + int count = Integer.bitCount(current); + for (java.util.Map.Entry entry : dp.entrySet()) { + int previous = entry.getKey(); + int total = entry.getValue(); + if ((current & ((previous << 1) | (previous >> 1))) != 0) continue; + nextDp.put(current, Math.max(nextDp.getOrDefault(current, 0), total + count)); + } + } + dp = nextDp; + } + + int maxVal = 0; + for (int val : dp.values()) { + maxVal = Math.max(maxVal, val); + } + return maxVal; + } +} diff --git a/tests/1001-1500/1349. maximum-students-taking-exam/sol.kt b/tests/1001-1500/1349. maximum-students-taking-exam/sol.kt new file mode 100644 index 00000000..b8aa1dbb --- /dev/null +++ b/tests/1001-1500/1349. maximum-students-taking-exam/sol.kt @@ -0,0 +1,33 @@ +class Solution { + fun maxStudents(seats: Array): Int { + val m = seats.size + val n = seats[0].size + val available = IntArray(m) + for (i in 0 until m) { + var mask = 0 + for (j in 0 until n) { + if (seats[i][j] == '.') { + mask = mask or (1 shl j) + } + } + available[i] = mask + } + + val validMasks = (0 until (1 shl n)).filter { it and (it shl 1) == 0 } + var dp = mapOf(0 to 0) + for (row in 0 until m) { + val nextDp = mutableMapOf() + for (current in validMasks) { + if (current and available[row].inv() != 0) continue + val count = current.countOneBits() + for ((previous, total) in dp) { + if (current and ((previous shl 1) or (previous shr 1)) != 0) continue + nextDp[current] = maxOf(nextDp.getOrDefault(current, 0), total + count) + } + } + dp = nextDp + } + + return dp.values.maxOrNull() ?: 0 + } +} diff --git a/tests/1001-1500/1349. maximum-students-taking-exam/sol.py b/tests/1001-1500/1349. maximum-students-taking-exam/sol.py new file mode 100644 index 00000000..04218e46 --- /dev/null +++ b/tests/1001-1500/1349. maximum-students-taking-exam/sol.py @@ -0,0 +1,29 @@ +from typing import List + + +class Solution: + def maxStudents(self, seats: List[List[str]]) -> int: + m, n = len(seats), len(seats[0]) + available = [] + for row in seats: + mask = 0 + for col, seat in enumerate(row): + if seat == ".": + mask |= 1 << col + available.append(mask) + + valid_masks = [mask for mask in range(1 << n) if not (mask & (mask << 1))] + dp = {0: 0} + for row in range(m): + next_dp = {} + for current in valid_masks: + if current & ~available[row]: + continue + count = current.bit_count() + for previous, total in dp.items(): + if current & ((previous << 1) | (previous >> 1)): + continue + next_dp[current] = max(next_dp.get(current, 0), total + count) + dp = next_dp + + return max(dp.values(), default=0) diff --git a/tests/1001-1500/1349. maximum-students-taking-exam/sol.py2 b/tests/1001-1500/1349. maximum-students-taking-exam/sol.py2 new file mode 100644 index 00000000..a637236e --- /dev/null +++ b/tests/1001-1500/1349. maximum-students-taking-exam/sol.py2 @@ -0,0 +1,30 @@ +class Solution(object): + def maxStudents(self, seats): + """ + :type seats: List[List[str]] + :rtype: int + """ + m, n = len(seats), len(seats[0]) + available = [] + for row in seats: + mask = 0 + for col, seat in enumerate(row): + if seat == ".": + mask |= 1 << col + available.append(mask) + + valid_masks = [mask for mask in range(1 << n) if not (mask & (mask << 1))] + dp = {0: 0} + for row in range(m): + next_dp = {} + for current in valid_masks: + if current & ~available[row]: + continue + count = bin(current).count("1") + for previous, total in dp.items(): + if current & ((previous << 1) | (previous >> 1)): + continue + next_dp[current] = max(next_dp.get(current, 0), total + count) + dp = next_dp + + return max(dp.values()) if dp else 0 diff --git a/tests/1001-1500/1349. maximum-students-taking-exam/sol.rb b/tests/1001-1500/1349. maximum-students-taking-exam/sol.rb new file mode 100644 index 00000000..ba65bd3e --- /dev/null +++ b/tests/1001-1500/1349. maximum-students-taking-exam/sol.rb @@ -0,0 +1,33 @@ +# @param {Character[][]} seats +# @return {Integer} +def max_students(seats) + m = seats.length + n = seats[0].length + available = [] + seats.each do |row| + mask = 0 + row.each_with_index do |seat, col| + if seat == "." + mask |= 1 << col + end + end + available << mask + end + + valid_masks = (0...(1 << n)).select { |mask| (mask & (mask << 1)) == 0 } + dp = {0 => 0} + m.times do |row| + next_dp = {} + valid_masks.each do |current| + next if current & ~available[row] != 0 + count = current.to_s(2).count("1") + dp.each do |previous, total| + next if current & ((previous << 1) | (previous >> 1)) != 0 + next_dp[current] = [next_dp.fetch(current, 0), total + count].max + end + end + dp = next_dp + end + + dp.values.max || 0 +end diff --git a/tests/1001-1500/1349. maximum-students-taking-exam/sol.rs b/tests/1001-1500/1349. maximum-students-taking-exam/sol.rs new file mode 100644 index 00000000..fdd56311 --- /dev/null +++ b/tests/1001-1500/1349. maximum-students-taking-exam/sol.rs @@ -0,0 +1,45 @@ +impl Solution { + pub fn max_students(seats: Vec>) -> i32 { + let m = seats.len(); + let n = seats[0].len(); + let mut available = Vec::with_capacity(m); + for row in &seats { + let mut mask: i32 = 0; + for (col, &seat) in row.iter().enumerate() { + if seat == '.' { + mask |= 1 << col; + } + } + available.push(mask); + } + + let mut valid_masks = Vec::new(); + for mask in 0i32..(1i32 << n) { + if mask & (mask << 1) == 0 { + valid_masks.push(mask); + } + } + + let mut dp: HashMap = HashMap::new(); + dp.insert(0, 0); + for row in 0..m { + let mut next_dp: HashMap = HashMap::new(); + for ¤t in &valid_masks { + if current & !available[row] != 0 { + continue; + } + let count = current.count_ones() as i32; + for (&previous, &total) in &dp { + if current & ((previous << 1) | (previous >> 1)) != 0 { + continue; + } + let entry = next_dp.entry(current).or_insert(0); + *entry = (*entry).max(total + count); + } + } + dp = next_dp; + } + + dp.values().max().cloned().unwrap_or(0) + } +} diff --git a/tests/1001-1500/1349. maximum-students-taking-exam/sol.swift b/tests/1001-1500/1349. maximum-students-taking-exam/sol.swift new file mode 100644 index 00000000..01783c3c --- /dev/null +++ b/tests/1001-1500/1349. maximum-students-taking-exam/sol.swift @@ -0,0 +1,39 @@ +class Solution { + func maxStudents(_ seats: [[Character]]) -> Int { + let m = seats.count + let n = seats[0].count + var available = [Int]() + for row in seats { + var mask = 0 + for (col, seat) in row.enumerated() { + if seat == "." { + mask |= 1 << col + } + } + available.append(mask) + } + + var validMasks = [Int]() + for mask in 0..<(1 << n) { + if (mask & (mask << 1)) == 0 { + validMasks.append(mask) + } + } + + var dp = [0: 0] + for row in 0..> 1))) != 0 { continue } + nextDp[current] = max(nextDp[current, default: 0], total + count) + } + } + dp = nextDp + } + + return dp.values.max() ?? 0 + } +} diff --git a/tests/1001-1500/1349. maximum-students-taking-exam/sol.ts b/tests/1001-1500/1349. maximum-students-taking-exam/sol.ts new file mode 100644 index 00000000..b5000f91 --- /dev/null +++ b/tests/1001-1500/1349. maximum-students-taking-exam/sol.ts @@ -0,0 +1,38 @@ +function maxStudents(seats: string[][]): number { + const m = seats.length; + const n = seats[0].length; + const available: number[] = []; + for (const row of seats) { + let mask = 0; + for (let col = 0; col < n; col++) { + if (row[col] === ".") { + mask |= 1 << col; + } + } + available.push(mask); + } + + const validMasks: number[] = []; + for (let mask = 0; mask < 1 << n; mask++) { + if ((mask & (mask << 1)) === 0) { + validMasks.push(mask); + } + } + + let dp: Map = new Map(); + dp.set(0, 0); + for (let row = 0; row < m; row++) { + const nextDp: Map = new Map(); + for (const current of validMasks) { + if ((current & ~available[row]) !== 0) continue; + const count = current.toString(2).split("1").length - 1; + for (const [previous, total] of dp) { + if ((current & ((previous << 1) | (previous >> 1))) !== 0) continue; + nextDp.set(current, Math.max(nextDp.get(current) ?? 0, total + count)); + } + } + dp = nextDp; + } + + return Math.max(...dp.values()); +} diff --git a/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/manifest.yaml b/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/manifest.yaml new file mode 100644 index 00000000..4b5eb7b2 --- /dev/null +++ b/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/manifest.yaml @@ -0,0 +1,540 @@ +entry: + id: 1351 + title: count-negative-numbers-in-a-sorted-matrix + params: + grid: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().countNegatives({grid})" + rust: "Solution::count_negatives({grid})" + python3: "Solution().countNegatives({grid})" + python2: "Solution().countNegatives({grid})" + ruby: "count_negatives({grid})" + java: "new Solution().countNegatives({grid})" + csharp: "new Solution().CountNegatives({grid})" + kotlin: "Solution().countNegatives({grid})" + go: "countNegatives({grid})" + dart: "Solution().countNegatives({grid})" + swift: "Solution().countNegatives({grid})" + typescript: "countNegatives({grid})" +judge: + type: exact +limits: + time_ms: 500 + memory_mb: 256 +oracle: + python3: + call: "Checker().countNegatives(grid, {result})" + checker: | + class Checker: + def countNegatives(self, grid, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if not isinstance(grid, list) or not 1 <= len(grid) <= 100: + return False + if not all(isinstance(row, list) for row in grid): + return False + cols = len(grid[0]) + if not 1 <= cols <= 100 or any(len(row) != cols for row in grid): + return False + if any(not isinstance(v, int) or isinstance(v, bool) or not -100 <= v <= 100 for row in grid for v in row): + return False + if any(row[c] > row[c - 1] for row in grid for c in range(1, cols)): + return False + if any(grid[r][c] > grid[r - 1][c] for r in range(1, len(grid)) for c in range(cols)): + return False + return result == sum(v < 0 for row in grid for v in row) +seed: 1351 +tests: + - name: example_one + in: + grid: + - [4, 3, 2, -1] + - [3, 2, 1, -1] + - [1, 1, -1, -2] + - [-1, -1, -2, -3] + out: 8 + - name: example_two + in: + grid: + - [3, 2] + - [1, 0] + out: 0 + - name: one_positive + in: + grid: + - [100] + out: 0 + - name: one_zero + in: + grid: + - [0] + out: 0 + - name: one_negative + in: + grid: + - [-100] + out: 1 + - name: one_row_mixed + in: + grid: + - [100, 4, 0, -1, -99] + out: 2 + - name: one_column_mixed + in: + grid: + - [100] + - [0] + - [-1] + - [-100] + out: 2 + - name: all_positive + in: + grid: + - [5, 4, 3] + - [4, 3, 2] + out: 0 + - name: all_zero + in: + grid: + - [0, 0, 0] + - [0, 0, 0] + out: 0 + - name: all_negative + in: + grid: + - [-1, -2, -3] + - [-2, -3, -4] + out: 6 + - name: single_negative_bottom_right + in: + grid: + - [5, 4, 3] + - [4, 3, 2] + - [3, 2, -1] + out: 1 + - name: negative_top_right_only + in: + grid: + - [2, -1] + - [-1, -2] + out: 3 + - name: diagonal_boundary + in: + grid: + - [3, 2, 1] + - [2, 1, 0] + - [1, 0, -1] + out: 1 + - name: zero_boundary + in: + grid: + - [2, 1, 0, 0, -1] + - [1, 0, 0, -1, -2] + out: 3 + - name: repeated_rows + in: + grid: + - [2, 1, 0, -1] + - [2, 1, 0, -1] + - [2, 1, 0, -1] + out: 3 + - name: repeated_columns + in: + grid: + - [3, 3, 3] + - [1, 1, 1] + - [-1, -1, -1] + out: 3 + - name: duplicate_transition_values + in: + grid: + - [3, 3, 0, -1, -1] + - [3, 2, 0, -1, -2] + - [2, 1, -1, -2, -2] + out: 7 + - name: two_by_four + in: + grid: + - [8, 4, 0, -4] + - [4, 0, -4, -8] + out: 3 + - name: four_by_two + in: + grid: + - [5, -1] + - [4, -2] + - [3, -3] + - [2, -4] + out: 4 + - name: wide_sparse_tail + in: + grid: + - [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + - [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] + - [8, 7, 6, 5, 4, 3, 2, 1, 0, -1] + out: 1 + - name: tall_staircase + in: + grid: + - [5, 4, 3] + - [4, 3, 2] + - [3, 2, 1] + - [2, 1, 0] + - [1, 0, -1] + - [0, -1, -2] + out: 3 + - name: broad_staircase + in: + grid: + - [7, 6, 5, 4, 3, 2, -1] + - [6, 5, 4, 3, 2, -1, -2] + - [5, 4, 3, 2, -1, -2, -3] + - [4, 3, 2, -1, -2, -3, -4] + out: 10 + - name: first_row_all_negative + in: + grid: + - [-1, -2, -3, -4] + - [-2, -3, -4, -5] + - [-3, -4, -5, -6] + out: 12 + - name: exact_minimum_values + in: + grid: + - [0, -100, -100] + - [-100, -100, -100] + out: 5 + - name: exact_maximum_values + in: + grid: + - [100, 100, 99] + - [100, 99, 0] + out: 0 + - name: two_negative_each_row + in: + grid: + - [5, 0, -1, -2] + - [4, -1, -2, -3] + - [3, -2, -3, -4] + out: 8 + - name: varying_cutoffs + in: + grid: + - [8, 7, 6, 5, -1] + - [7, 6, 5, -1, -2] + - [6, 5, -1, -2, -3] + - [5, -1, -2, -3, -4] + - [-1, -2, -3, -4, -5] + out: 15 + - name: zeroes_before_negative_column + in: + grid: + - [3, 0, 0, -1] + - [0, 0, -1, -2] + - [0, -1, -2, -3] + out: 6 + - name: negative_count_fourteen + in: + grid: + - [5, 4, 3, 2, 1, -1] + - [4, 3, 2, 1, -1, -2] + - [3, 2, 1, -1, -2, -3] + - [2, 1, -1, -2, -3, -4] + out: 10 + - name: mixed_extremes + in: + grid: + - [100, 50, 0, -50, -100] + - [50, 0, -50, -100, -100] + - [0, -50, -100, -100, -100] + out: 9 + - name: narrow_dense_negative + in: + grid: + - [1, 0, -1, -2] + - [0, -1, -2, -3] + - [-1, -2, -3, -4] + out: 9 + - name: isolated_zero_corner + in: + grid: + - [0, -1, -2] + - [-1, -2, -3] + - [-2, -3, -4] + out: 8 + - name: five_square_positive + in: + grid: + - [9, 8, 7, 6, 5] + - [8, 7, 6, 5, 4] + - [7, 6, 5, 4, 3] + - [6, 5, 4, 3, 2] + - [5, 4, 3, 2, 1] + out: 0 + - name: five_square_negative + in: + grid: + - [-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] + out: 25 + - name: irregular_frontier + in: + grid: + - [9, 8, 7, 6, 5, 4] + - [8, 7, 6, 5, -1, -2] + - [7, 6, 5, -1, -2, -3] + - [6, -1, -2, -3, -4, -5] + out: 10 + - name: max_rows_single_column + in: + grid: + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [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] + - [-1] + - [-1] + - [-1] + - [-1] + - [-1] + - [-1] + - [-1] + - [-1] + - [-1] + - [-1] + - [-1] + - [-1] + - [-1] + - [-1] + - [-1] + - [-1] + - [-1] + - [-1] + - [-1] + - [-1] + - [-1] + - [-1] + - [-1] + - [-1] + - [-1] + - [-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: 50 + - name: max_columns_single_row + in: + grid: + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 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, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -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: 50 + - name: three_by_three_partial_frontier + in: + grid: + - [4, 0, -1] + - [0, -1, -2] + - [-1, -2, -3] + out: 6 + - name: hundred_by_hundred_all_negative + 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] + out: 100 + - name: ten_by_ten_zero_negative_frontier + in: + grid: + - [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] + - [8, 7, 6, 5, 4, 3, 2, 1, 0, -1] + - [7, 6, 5, 4, 3, 2, 1, 0, -1, -2] + - [6, 5, 4, 3, 2, 1, 0, -1, -2, -3] + - [5, 4, 3, 2, 1, 0, -1, -2, -3, -4] + - [4, 3, 2, 1, 0, -1, -2, -3, -4, -5] + - [3, 2, 1, 0, -1, -2, -3, -4, -5, -6] + - [2, 1, 0, -1, -2, -3, -4, -5, -6, -7] + - [1, 0, -1, -2, -3, -4, -5, -6, -7, -8] + - [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] + out: 45 diff --git a/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.cpp b/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.cpp new file mode 100644 index 00000000..07e90ab8 --- /dev/null +++ b/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int countNegatives(vector>& grid) { + int count = 0; + for (const auto& row : grid) { + for (int num : row) { + if (num < 0) count++; + } + } + return count; + } +}; diff --git a/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.cs b/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.cs new file mode 100644 index 00000000..d5a029e7 --- /dev/null +++ b/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.cs @@ -0,0 +1,11 @@ +public class Solution { + public int CountNegatives(int[][] grid) { + int count = 0; + foreach (var row in grid) { + foreach (int num in row) { + if (num < 0) count++; + } + } + return count; + } +} diff --git a/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.dart b/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.dart new file mode 100644 index 00000000..bb04f04c --- /dev/null +++ b/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.dart @@ -0,0 +1,11 @@ +class Solution { + int countNegatives(List> grid) { + int count = 0; + for (var row in grid) { + for (var num in row) { + if (num < 0) count++; + } + } + return count; + } +} diff --git a/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.go b/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.go new file mode 100644 index 00000000..6460580c --- /dev/null +++ b/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.go @@ -0,0 +1,11 @@ +func countNegatives(grid [][]int) int { + count := 0 + for _, row := range grid { + for _, num := range row { + if num < 0 { + count++ + } + } + } + return count +} diff --git a/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.java b/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.java new file mode 100644 index 00000000..800d3fa4 --- /dev/null +++ b/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.java @@ -0,0 +1,11 @@ +class Solution { + public int countNegatives(int[][] grid) { + int count = 0; + for (int[] row : grid) { + for (int num : row) { + if (num < 0) count++; + } + } + return count; + } +} diff --git a/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.kt b/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.kt new file mode 100644 index 00000000..a09695cc --- /dev/null +++ b/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.kt @@ -0,0 +1,11 @@ +class Solution { + fun countNegatives(grid: Array): Int { + var count = 0 + for (row in grid) { + for (num in row) { + if (num < 0) count++ + } + } + return count + } +} diff --git a/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.py b/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.py new file mode 100644 index 00000000..e4a51984 --- /dev/null +++ b/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.py @@ -0,0 +1,9 @@ +class Solution: + def countNegatives(self, grid): + count = 0 + + for row in grid: + for num in row: + count += num < 0 + + return count diff --git a/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.py2 b/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.py2 new file mode 100644 index 00000000..26952993 --- /dev/null +++ b/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.py2 @@ -0,0 +1,7 @@ +class Solution(object): + def countNegatives(self, grid): + count = 0 + for row in grid: + for num in row: + count += (num < 0) + return count diff --git a/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.rb b/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.rb new file mode 100644 index 00000000..22f567ce --- /dev/null +++ b/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.rb @@ -0,0 +1,11 @@ +# @param {Integer[][]} grid +# @return {Integer} +def count_negatives(grid) + count = 0 + grid.each do |row| + row.each do |num| + count += 1 if num < 0 + end + end + count +end diff --git a/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.rs b/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.rs new file mode 100644 index 00000000..c77aa340 --- /dev/null +++ b/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.rs @@ -0,0 +1,13 @@ +impl Solution { + pub fn count_negatives(grid: Vec>) -> i32 { + let mut count = 0; + for row in &grid { + for &num in row { + if num < 0 { + count += 1; + } + } + } + count + } +} diff --git a/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.swift b/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.swift new file mode 100644 index 00000000..1e6707d6 --- /dev/null +++ b/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.swift @@ -0,0 +1,13 @@ +class Solution { + func countNegatives(_ grid: [[Int]]) -> Int { + var count = 0 + for row in grid { + for num in row { + if num < 0 { + count += 1 + } + } + } + return count + } +} diff --git a/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.ts b/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.ts new file mode 100644 index 00000000..f9de0d7f --- /dev/null +++ b/tests/1001-1500/1351. count-negative-numbers-in-a-sorted-matrix/sol.ts @@ -0,0 +1,9 @@ +function countNegatives(grid: number[][]): number { + let count = 0; + for (const row of grid) { + for (const num of row) { + if (num < 0) count++; + } + } + return count; +} diff --git a/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/manifest.yaml b/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/manifest.yaml new file mode 100644 index 00000000..30e6efa4 --- /dev/null +++ b/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/manifest.yaml @@ -0,0 +1,633 @@ +entry: + id: 1353 + title: "maximum-number-of-events-that-can-be-attended" + params: + events: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().maxEvents({events})" + rust: "Solution::max_events({events})" + python3: "Solution().maxEvents({events})" + python2: "Solution().maxEvents({events})" + ruby: "max_events({events})" + java: "new Solution().maxEvents({events})" + csharp: "new Solution().MaxEvents({events})" + kotlin: "Solution().maxEvents({events})" + go: "maxEvents({events})" + dart: "Solution().maxEvents({events})" + swift: "Solution().maxEvents({events})" + typescript: "maxEvents({events})" +judge: + type: "exact" +limits: + time_ms: 1000 + memory_mb: 256 +oracle: + python3: + call: "Checker().maxEvents(events, {result})" + checker: | + class Checker: + def maxEvents(self, events, result): + if isinstance(result, bool) or not isinstance(result, int): + return False + parent = {} + + def find(day): + trail = [] + while day in parent: + trail.append(day) + day = parent[day] + for seen in trail: + parent[seen] = day + return day + + attended = 0 + for start, end in sorted(events, key=lambda event: event[1]): + day = find(start) + if day <= end: + attended += 1 + parent[day] = find(day + 1) + return result == attended +seed: 1353 +tests: + - name: "example_chain" + in: + events: + elemType: "int" + value: + - [1, 2] + - [2, 3] + - [3, 4] + out: 3 + - name: "example_duplicate_window" + in: + events: + elemType: "int" + value: + - [1, 2] + - [2, 3] + - [3, 4] + - [1, 2] + out: 4 + - name: "single_one_day_event" + in: + events: + elemType: "int" + value: + - [1, 1] + out: 1 + - name: "many_events_one_day" + in: + events: + elemType: "int" + value: + - [42, 42] + - [42, 42] + - [42, 42] + - [42, 42] + - [42, 42] + - [42, 42] + out: 1 + - name: "all_share_wide_window" + in: + events: + elemType: "int" + value: + - [1, 100000] + - [1, 100000] + - [1, 100000] + - [1, 100000] + - [1, 100000] + - [1, 100000] + - [1, 100000] + out: 7 + - name: "fully_disjoint_gaps" + in: + events: + elemType: "int" + value: + - [1, 1] + - [3, 3] + - [100, 100] + - [99999, 99999] + - [100000, 100000] + out: 5 + - name: "nested_windows" + in: + events: + elemType: "int" + value: + - [1, 10] + - [2, 9] + - [3, 8] + - [4, 7] + - [5, 6] + out: 5 + - name: "touching_boundaries" + in: + events: + elemType: "int" + value: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + out: 5 + - name: "unsorted_complete_schedule" + in: + events: + elemType: "int" + value: + - [5, 5] + - [1, 2] + - [2, 2] + - [1, 1] + - [3, 4] + - [4, 4] + out: 5 + - name: "earliest_expiry_priority" + in: + events: + elemType: "int" + value: + - [1, 1] + - [1, 2] + - [1, 3] + - [2, 2] + - [2, 3] + - [3, 3] + out: 3 + - name: "separated_clusters" + in: + events: + elemType: "int" + value: + - [1, 2] + - [1, 2] + - [10, 11] + - [10, 11] + - [50, 51] + - [50, 51] + out: 6 + - name: "identical_three_day_window" + in: + events: + elemType: "int" + value: + - [10, 12] + - [10, 12] + - [10, 12] + - [10, 12] + - [10, 12] + out: 3 + - name: "same_start_varying_end" + in: + events: + elemType: "int" + value: + - [1, 1] + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [1, 5] + out: 5 + - name: "same_end_varying_start" + in: + events: + elemType: "int" + value: + - [1, 5] + - [2, 5] + - [3, 5] + - [4, 5] + - [5, 5] + out: 5 + - name: "upper_day_boundary" + in: + events: + elemType: "int" + value: + - [99997, 99998] + - [99998, 99999] + - [99999, 100000] + - [100000, 100000] + out: 4 + - name: "paired_fixed_days_with_flexible_events" + in: + events: + elemType: "int" + value: + - [1, 4] + - [1, 4] + - [2, 2] + - [2, 2] + - [3, 3] + - [3, 3] + - [4, 4] + - [4, 4] + out: 4 + - name: "wide_event_fills_missing_day" + in: + events: + elemType: "int" + value: + - [1, 1] + - [2, 2] + - [4, 4] + - [5, 5] + - [1, 5] + out: 5 + - name: "late_start_dense" + in: + events: + elemType: "int" + value: + - [99995, 100000] + - [99995, 100000] + - [99996, 99996] + - [99997, 99997] + - [99998, 99998] + - [99999, 99999] + - [100000, 100000] + out: 6 + - name: "long_event_with_singletons" + in: + events: + elemType: "int" + value: + - [1, 100000] + - [100, 100] + - [200, 200] + - [300, 300] + - [400, 400] + - [500, 500] + out: 6 + - name: "overlapping_staircase" + in: + events: + elemType: "int" + value: + - [1, 3] + - [1, 3] + - [2, 4] + - [2, 4] + - [3, 5] + - [3, 5] + - [4, 6] + - [4, 6] + out: 6 + - name: "sparse_large_calendar" + in: + events: + elemType: "int" + value: + - [1, 100000] + - [1000, 1000] + - [10000, 10000] + - [20000, 20000] + - [40000, 40000] + - [60000, 60000] + - [80000, 80000] + out: 7 + - name: "ten_days_many_duplicates" + in: + events: + elemType: "int" + value: + - [1, 10] + - [1, 10] + - [1, 10] + - [1, 10] + - [1, 10] + - [1, 10] + - [1, 10] + - [1, 10] + - [1, 10] + - [1, 10] + - [1, 10] + - [1, 10] + out: 10 + - name: "five_days_repeated_singletons" + in: + events: + elemType: "int" + value: + - [1, 1] + - [1, 1] + - [2, 2] + - [2, 2] + - [3, 3] + - [3, 3] + - [4, 4] + - [4, 4] + - [5, 5] + - [5, 5] + out: 5 + - name: "flexibility_preserves_all" + in: + events: + elemType: "int" + value: + - [1, 5] + - [1, 1] + - [2, 2] + - [3, 3] + - [4, 4] + - [5, 5] + out: 5 + - name: "two_independent_windows" + in: + events: + elemType: "int" + value: + - [1, 3] + - [1, 3] + - [1, 3] + - [10, 12] + - [10, 12] + - [10, 12] + - [10, 12] + out: 6 + - name: "oracle_mixed_expirations" + in: + events: + elemType: "int" + value: + - [4, 6] + - [1, 4] + - [2, 2] + - [2, 5] + - [3, 3] + - [5, 7] + - [6, 6] + - [1, 1] + - name: "oracle_crossing_intervals" + in: + events: + elemType: "int" + value: + - [8, 10] + - [1, 8] + - [4, 4] + - [2, 6] + - [3, 5] + - [7, 9] + - [5, 8] + - [6, 7] + - [9, 9] + - name: "oracle_duplicate_and_gaps" + in: + events: + elemType: "int" + value: + - [20, 22] + - [20, 20] + - [20, 20] + - [21, 21] + - [22, 22] + - [30, 31] + - [30, 31] + - [32, 35] + - [34, 34] + - name: "oracle_reverse_ordered_ranges" + in: + events: + elemType: "int" + value: + - [90, 100] + - [80, 89] + - [70, 79] + - [60, 69] + - [50, 59] + - [40, 49] + - [30, 39] + - [20, 29] + - [10, 19] + - [1, 9] + - name: "oracle_competing_deadlines" + in: + events: + elemType: "int" + value: + - [1, 2] + - [1, 2] + - [1, 3] + - [2, 3] + - [2, 4] + - [3, 4] + - [3, 5] + - [4, 5] + - [4, 6] + - [5, 6] + - name: "oracle_far_boundary_mix" + in: + events: + elemType: "int" + value: + - [1, 100000] + - [1, 1] + - [99999, 100000] + - [100000, 100000] + - [50000, 50000] + - [49999, 50001] + - [2, 3] + - [3, 3] + - name: "oracle_dense_twelve_days" + in: + events: + elemType: "int" + value: + - [1, 12] + - [1, 3] + - [2, 6] + - [2, 2] + - [3, 9] + - [4, 4] + - [5, 8] + - [6, 6] + - [7, 12] + - [8, 10] + - [9, 9] + - [10, 12] + - [11, 11] + - [12, 12] + - name: "oracle_many_same_end" + in: + events: + elemType: "int" + value: + - [1, 8] + - [2, 8] + - [3, 8] + - [4, 8] + - [5, 8] + - [6, 8] + - [7, 8] + - [8, 8] + - [1, 4] + - [2, 5] + - [3, 6] + - name: "oracle_many_same_start" + in: + events: + elemType: "int" + value: + - [25, 25] + - [25, 26] + - [25, 27] + - [25, 28] + - [25, 29] + - [25, 30] + - [25, 31] + - [26, 26] + - [27, 27] + - [28, 28] + - [29, 29] + - [30, 30] + - name: "oracle_large_dense_range" + in: + events: + elemType: "int" + value: + - [1, 30] + - [1, 30] + - [1, 30] + - [1, 30] + - [1, 30] + - [1, 30] + - [1, 30] + - [1, 30] + - [1, 30] + - [1, 30] + - [1, 30] + - [1, 30] + - [1, 30] + - [1, 30] + - [1, 30] + - [1, 30] + - [1, 30] + - [1, 30] + - [1, 30] + - [1, 30] + - [1, 30] + - [1, 30] + - [1, 30] + - [1, 30] + - [1, 30] + - [1, 30] + - [1, 30] + - [1, 30] + - [1, 30] + - [1, 30] + - [5, 5] + - [10, 10] + - [15, 15] + - [20, 20] + - [25, 25] + - [30, 30] + - name: "oracle_large_sparse_range" + in: + events: + elemType: "int" + value: + - [1, 100000] + - [10000, 90000] + - [20000, 80000] + - [30000, 70000] + - [40000, 60000] + - [1, 1] + - [10000, 10000] + - [20000, 20000] + - [30000, 30000] + - [40000, 40000] + - [50000, 50000] + - [60000, 60000] + - [70000, 70000] + - [80000, 80000] + - [90000, 90000] + - [100000, 100000] + - name: "oracle_interleaved_components" + in: + events: + elemType: "int" + value: + - [1, 2] + - [10, 13] + - [2, 4] + - [11, 11] + - [3, 3] + - [12, 14] + - [4, 5] + - [13, 13] + - [5, 6] + - [14, 15] + - [6, 6] + - [15, 15] + - name: "oracle_long_nested_descending" + in: + events: + elemType: "int" + value: + - [1, 50] + - [2, 49] + - [3, 48] + - [4, 47] + - [5, 46] + - [6, 45] + - [7, 44] + - [8, 43] + - [9, 42] + - [10, 41] + - [11, 40] + - [12, 39] + - [13, 38] + - [14, 37] + - [15, 36] + - [16, 35] + - [17, 34] + - [18, 33] + - [19, 32] + - [20, 31] + - name: "oracle_alternating_fixed_and_flexible" + in: + events: + elemType: "int" + value: + - [1, 8] + - [1, 1] + - [2, 8] + - [2, 2] + - [3, 8] + - [3, 3] + - [4, 8] + - [4, 4] + - [5, 8] + - [5, 5] + - [6, 8] + - [6, 6] + - [7, 8] + - [7, 7] + - [8, 8] + - name: "oracle_short_windows_around_gaps" + in: + events: + elemType: "int" + value: + - [1, 2] + - [1, 4] + - [2, 2] + - [4, 5] + - [4, 7] + - [5, 5] + - [7, 8] + - [7, 10] + - [8, 8] + - [10, 11] + - [10, 12] + - [11, 11] diff --git a/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.cpp b/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.cpp new file mode 100644 index 00000000..71a30499 --- /dev/null +++ b/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int maxEvents(vector>& events) { + sort(events.begin(), events.end()); + priority_queue, greater> minHeap; + int day = 0, i = 0, n = events.size(), result = 0; + + while (!minHeap.empty() || i < n) { + if (minHeap.empty()) { + day = events[i][0]; + } + while (i < n && events[i][0] <= day) { + minHeap.push(events[i][1]); + i++; + } + minHeap.pop(); + result++; + day++; + while (!minHeap.empty() && minHeap.top() < day) { + minHeap.pop(); + } + } + return result; + } +}; diff --git a/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.cs b/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.cs new file mode 100644 index 00000000..d0686881 --- /dev/null +++ b/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.cs @@ -0,0 +1,17 @@ +public class Solution { + public int MaxEvents(int[][] events) { + Array.Sort(events, (a, b) => a[1] != b[1] ? a[1].CompareTo(b[1]) : a[0].CompareTo(b[0])); + int maxDay = 0; + foreach (var item in events) maxDay = Math.Max(maxDay, item[1]); + int[] parent = new int[maxDay + 2]; + for (int day = 0; day < parent.Length; day++) parent[day] = day; + Func find = null; + find = day => parent[day] == day ? day : parent[day] = find(parent[day]); + int result = 0; + foreach (var item in events) { + int day = find(item[0]); + if (day <= item[1]) { result++; parent[day] = find(day + 1); } + } + return result; + } +} diff --git a/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.dart b/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.dart new file mode 100644 index 00000000..c28fa274 --- /dev/null +++ b/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.dart @@ -0,0 +1,26 @@ +import 'package:collection/collection.dart'; + +class Solution { + int maxEvents(List> events) { + events.sort((a, b) => a[0].compareTo(b[0])); + final minHeap = HeapPriorityQueue(); + int day = 0, i = 0, n = events.length, result = 0; + + while (minHeap.isNotEmpty || i < n) { + if (minHeap.isEmpty) { + day = events[i][0]; + } + while (i < n && events[i][0] <= day) { + minHeap.add(events[i][1]); + i++; + } + minHeap.removeFirst(); + result++; + day++; + while (minHeap.isNotEmpty && minHeap.first < day) { + minHeap.removeFirst(); + } + } + return result; + } +} diff --git a/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.go b/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.go new file mode 100644 index 00000000..58148e45 --- /dev/null +++ b/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.go @@ -0,0 +1,41 @@ +func maxEvents(events [][]int) int { + sort.Slice(events, func(i, j int) bool { + return events[i][0] < events[j][0] + }) + minHeap := &IntHeap{} + heap.Init(minHeap) + day := 0 + i := 0 + n := len(events) + result := 0 + + for minHeap.Len() > 0 || i < n { + if minHeap.Len() == 0 { + day = events[i][0] + } + for i < n && events[i][0] <= day { + heap.Push(minHeap, events[i][1]) + i++ + } + heap.Pop(minHeap) + result++ + day++ + for minHeap.Len() > 0 && (*minHeap)[0] < day { + heap.Pop(minHeap) + } + } + return result +} + +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[:n-1] + return x +} diff --git a/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.java b/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.java new file mode 100644 index 00000000..9ced14ca --- /dev/null +++ b/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.java @@ -0,0 +1,24 @@ +class Solution { + public int maxEvents(int[][] events) { + Arrays.sort(events, (a, b) -> Integer.compare(a[0], b[0])); + PriorityQueue minHeap = new PriorityQueue<>(); + int day = 0, i = 0, n = events.length, result = 0; + + while (!minHeap.isEmpty() || i < n) { + if (minHeap.isEmpty()) { + day = events[i][0]; + } + while (i < n && events[i][0] <= day) { + minHeap.offer(events[i][1]); + i++; + } + minHeap.poll(); + result++; + day++; + while (!minHeap.isEmpty() && minHeap.peek() < day) { + minHeap.poll(); + } + } + return result; + } +} diff --git a/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.kt b/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.kt new file mode 100644 index 00000000..e1d59780 --- /dev/null +++ b/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.kt @@ -0,0 +1,27 @@ +class Solution { + fun maxEvents(events: Array): Int { + events.sortBy { it[0] } + val minHeap = java.util.PriorityQueue() + var day = 0 + var i = 0 + val n = events.size + var result = 0 + + while (minHeap.isNotEmpty() || i < n) { + if (minHeap.isEmpty()) { + day = events[i][0] + } + while (i < n && events[i][0] <= day) { + minHeap.offer(events[i][1]) + i++ + } + minHeap.poll() + result++ + day++ + while (minHeap.isNotEmpty() && minHeap.peek() < day) { + minHeap.poll() + } + } + return result + } +} diff --git a/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.py b/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.py new file mode 100644 index 00000000..163e4d7f --- /dev/null +++ b/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.py @@ -0,0 +1,29 @@ +import heapq +from typing import List + + +class Solution: + def maxEvents(self, events: List[List[int]]) -> int: + # Sort events based on start day + events.sort() + + min_heap = [] + day = 0 + index = 0 + n = len(events) + result = 0 + + while min_heap or index < n: + if not min_heap: + day = events[index][0] + while index < n and events[index][0] <= day: + heapq.heappush(min_heap, events[index][1]) + index += 1 + heapq.heappop(min_heap) + result += 1 + day += 1 + + while min_heap and min_heap[0] < day: + heapq.heappop(min_heap) + + return result diff --git a/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.py2 b/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.py2 new file mode 100644 index 00000000..dc9659ac --- /dev/null +++ b/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.py2 @@ -0,0 +1,26 @@ +class Solution(object): + def maxEvents(self, events): + """ + :type events: List[List[int]] + :rtype: int + """ + events.sort() + import heapq + min_heap = [] + day = 0 + i = 0 + n = len(events) + result = 0 + + while min_heap or i < n: + if not min_heap: + day = events[i][0] + while i < n and events[i][0] <= day: + heapq.heappush(min_heap, events[i][1]) + i += 1 + heapq.heappop(min_heap) + result += 1 + day += 1 + while min_heap and min_heap[0] < day: + heapq.heappop(min_heap) + return result diff --git a/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.rb b/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.rb new file mode 100644 index 00000000..4dfbba8e --- /dev/null +++ b/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.rb @@ -0,0 +1,28 @@ +# @param {Integer[][]} events +# @return {Integer} +require 'algorithms' +def max_events(events) + events.sort_by! { |e| e[0] } + min_heap = Containers::MinHeap.new + day = 0 + i = 0 + n = events.length + result = 0 + + while !min_heap.empty? || i < n + if min_heap.empty? + day = events[i][0] + end + while i < n && events[i][0] <= day + min_heap.push(events[i][1]) + i += 1 + end + min_heap.pop + result += 1 + day += 1 + while !min_heap.empty? && min_heap.next < day + min_heap.pop + end + end + result +end diff --git a/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.rs b/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.rs new file mode 100644 index 00000000..d244d7cc --- /dev/null +++ b/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.rs @@ -0,0 +1,35 @@ +use std::collections::BinaryHeap; +use std::cmp::Reverse; + +impl Solution { + pub fn max_events(events: Vec>) -> i32 { + let mut events = events; + events.sort_by_key(|e| e[0]); + let mut min_heap = BinaryHeap::new(); + let mut day = 0; + let mut i = 0; + let n = events.len(); + let mut result = 0; + + while !min_heap.is_empty() || i < n { + if min_heap.is_empty() { + day = events[i][0]; + } + while i < n && events[i][0] <= day { + min_heap.push(Reverse(events[i][1])); + i += 1; + } + min_heap.pop(); + result += 1; + day += 1; + while let Some(&Reverse(top)) = min_heap.peek() { + if top < day { + min_heap.pop(); + } else { + break; + } + } + } + result + } +} diff --git a/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.swift b/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.swift new file mode 100644 index 00000000..eeecd8ac --- /dev/null +++ b/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.swift @@ -0,0 +1,28 @@ +class Solution { + func maxEvents(_ events: [[Int]]) -> Int { + let events = events.sorted { $0[0] < $1[0] } + var minHeap = [Int]() + var day = 0 + var i = 0 + let n = events.count + var result = 0 + + while !minHeap.isEmpty || i < n { + if minHeap.isEmpty { + day = events[i][0] + } + while i < n && events[i][0] <= day { + minHeap.append(events[i][1]) + minHeap.sort(by: >) + i += 1 + } + minHeap.removeLast() + result += 1 + day += 1 + while !minHeap.isEmpty && minHeap.last! < day { + minHeap.removeLast() + } + } + return result + } +} diff --git a/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.ts b/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.ts new file mode 100644 index 00000000..459d533e --- /dev/null +++ b/tests/1001-1500/1353. maximum-number-of-events-that-can-be-attended/sol.ts @@ -0,0 +1,16 @@ +function maxEvents(events: number[][]): number { + events.sort((a, b) => a[1] - b[1] || a[0] - b[0]); + const maxDay = Math.max(...events.map((event) => event[1])); + const parent = Array.from({ length: maxDay + 2 }, (_, day) => day); + const find = (day: number): number => + parent[day] === day ? day : (parent[day] = find(parent[day])); + let result = 0; + for (const [start, end] of events) { + const day = find(start); + if (day <= end) { + result++; + parent[day] = find(day + 1); + } + } + return result; +} diff --git a/tests/1001-1500/1354. construct-target-array-with-multiple-sums/manifest.yaml b/tests/1001-1500/1354. construct-target-array-with-multiple-sums/manifest.yaml new file mode 100644 index 00000000..468ebed9 --- /dev/null +++ b/tests/1001-1500/1354. construct-target-array-with-multiple-sums/manifest.yaml @@ -0,0 +1,262 @@ +entry: + id: 1354 + title: "construct-target-array-with-multiple-sums" + params: + target: + type: array + items: + type: int + call: + cpp: "Solution().isPossible({target})" + rust: "Solution::is_possible({target})" + python3: "Solution().isPossible({target})" + python2: "Solution().isPossible({target})" + ruby: "is_possible({target})" + java: "new Solution().isPossible({target})" + csharp: "new Solution().IsPossible({target})" + kotlin: "Solution().isPossible({target})" + go: "isPossible({target})" + dart: "Solution().isPossible({target})" + swift: "Solution().isPossible({target})" + typescript: "isPossible({target})" +judge: + type: exact +limits: + time_ms: 1000 + memory_mb: 256 +oracle: + python3: + call: "Checker().isPossible(target, {result})" + checker: | + import heapq + + class Checker: + def isPossible(self, target, result): + if type(result) is not bool: + return False + total = sum(target) + heap = [-value for value in target] + heapq.heapify(heap) + + while True: + largest = -heapq.heappop(heap) + rest = total - largest + if largest == 1 or rest == 1: + return result is True + if rest == 0 or rest >= largest: + return result is False + + previous = largest % rest + if previous == 0: + return result is False + total = rest + previous + heapq.heappush(heap, -previous) +seed: 1354 +tests: + - name: example_three_elements + in: + target: [9, 3, 5] + out: true + - name: example_impossible_four_elements + in: + target: [1, 1, 1, 2] + out: false + - name: example_two_elements + in: + target: [8, 5] + out: true + - name: singleton_starting_value + in: + target: [1] + out: true + - name: singleton_non_starting_value + in: + target: [1000000000] + out: false + - name: all_ones_three + in: + target: [1, 1, 1] + - name: all_ones_seven + in: + target: [1, 1, 1, 1, 1, 1, 1] + - name: pair_first_operation + in: + target: [1, 2] + - name: pair_large_repeated_updates + in: + target: [1, 999999999] + - name: pair_coprime_chain + in: + target: [55, 89] + - name: pair_non_coprime + in: + target: [1000000000, 999999998] + - name: pair_equal_values + in: + target: [2, 2] + - name: pair_valid_nontrivial + in: + target: [2, 3] + - name: triple_single_operation + in: + target: [3, 1, 1] + - name: triple_forward_chain + in: + target: [9, 5, 1] + - name: triple_permuted_chain + in: + target: [5, 1, 9] + - name: triple_equal_largest + in: + target: [3, 3, 1] + - name: triple_sum_equals_largest + in: + target: [1, 2, 3] + - name: triple_zero_remainder + in: + target: [1, 1, 4] + - name: triple_remainder_progression + in: + target: [1, 1, 1000000000] + - name: four_element_single_operation + in: + target: [4, 1, 1, 1] + - name: four_element_chain + in: + target: [4, 7, 13, 1] + - name: four_element_long_chain + in: + target: [25, 7, 13, 1] + - name: four_element_invalid_remainder + in: + target: [1, 1, 1, 6] + - name: four_element_valid_remainder_one + in: + target: [1, 1, 1, 9] + - name: four_element_equal_maximums + in: + target: [1, 1, 4, 4] + - name: five_element_single_operation + in: + target: [1, 1, 1, 1, 5] + - name: five_element_invalid_second_step + in: + target: [1, 1, 1, 1, 10] + - name: five_element_forward_chain + in: + target: [9, 5, 15, 1, 1] + - name: five_element_permuted_chain + in: + target: [1, 15, 9, 1, 5] + - name: six_element_single_operation + in: + target: [1, 1, 1, 1, 1, 6] + - name: six_element_impossible_increment + in: + target: [1, 1, 1, 1, 1, 7] + - name: maximum_value_with_rest_one + in: + target: [1000000000, 1] + - name: generated_small_values + seed: 135401 + in: + target: + gen: array + len: + gen: int + min: 2 + max: 12 + of: + gen: int + min: 1 + max: 100 + distinct: false + sorted: false + elemType: int + - name: generated_medium_values + seed: 135402 + in: + target: + gen: array + len: + gen: int + min: 100 + max: 500 + of: + gen: int + min: 1 + max: 1000000000 + distinct: false + sorted: false + elemType: int + - name: generated_duplicate_heavy + seed: 135403 + in: + target: + gen: array + len: + gen: int + min: 20 + max: 100 + of: + gen: int + min: 1 + max: 4 + distinct: false + sorted: false + elemType: int + - name: generated_large_random + seed: 135404 + in: + target: + gen: array + len: 50000 + of: + gen: int + min: 1 + max: 1000000000 + distinct: false + sorted: false + elemType: int + - name: generated_large_ones + seed: 135405 + in: + target: + gen: array + len: 50000 + of: + gen: int + min: 1 + max: 1 + distinct: false + sorted: false + elemType: int + - name: generated_large_low_range + seed: 135406 + in: + target: + gen: array + len: 40000 + of: + gen: int + min: 1 + max: 1000 + distinct: false + sorted: false + elemType: int + - name: generated_near_maximum_values + seed: 135407 + in: + target: + gen: array + len: + gen: int + min: 50 + max: 200 + of: + gen: int + min: 999999000 + max: 1000000000 + distinct: false + sorted: false + elemType: int diff --git a/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.cpp b/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.cpp new file mode 100644 index 00000000..668ab34e --- /dev/null +++ b/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.cpp @@ -0,0 +1,31 @@ +#include +#include + +class Solution { +public: + bool isPossible(vector& target) { + priority_queue heap; + long long total = 0; + for (int v : target) { + heap.push(v); + total += v; + } + while (true) { + long long largest = heap.top(); + heap.pop(); + long long rest = total - largest; + if (largest == 1 || rest == 1) { + return true; + } + if (rest == 0 || rest >= largest) { + return false; + } + long long previous = largest % rest; + if (previous == 0) { + return false; + } + total = rest + previous; + heap.push(previous); + } + } +}; diff --git a/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.cs b/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.cs new file mode 100644 index 00000000..ba6504af --- /dev/null +++ b/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.cs @@ -0,0 +1,17 @@ +public class Solution { + public bool IsPossible(int[] target) { + var values = new System.Collections.Generic.List(); + long total = 0; + foreach (int value in target) { values.Add(value); total += value; } + while (true) { + values.Sort((a, b) => b.CompareTo(a)); + long largest = values[0], rest = total - largest; + if (largest == 1 || rest == 1) return true; + if (rest == 0 || rest >= largest) return false; + long previous = largest % rest; + if (previous == 0) return false; + values[0] = previous; + total = rest + previous; + } + } +} diff --git a/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.dart b/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.dart new file mode 100644 index 00000000..60d5f64d --- /dev/null +++ b/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.dart @@ -0,0 +1,28 @@ +import 'dart:collection'; + +class Solution { + bool isPossible(List target) { + var heap = HeapPriorityQueue((a, b) => b.compareTo(a)); + int total = 0; + for (var v in target) { + heap.add(v); + total += v; + } + while (true) { + int largest = heap.removeFirst(); + int rest = total - largest; + if (largest == 1 || rest == 1) { + return true; + } + if (rest == 0 || rest >= largest) { + return false; + } + int previous = largest % rest; + if (previous == 0) { + return false; + } + total = rest + previous; + heap.add(previous); + } + } +} diff --git a/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.go b/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.go new file mode 100644 index 00000000..4d63031c --- /dev/null +++ b/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.go @@ -0,0 +1,39 @@ +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[:n-1] + return x +} + +func isPossible(target []int) bool { + h := &IntHeap{} + heap.Init(h) + total := 0 + for _, v := range target { + heap.Push(h, v) + total += v + } + for { + largest := heap.Pop(h).(int) + rest := total - largest + if largest == 1 || rest == 1 { + return true + } + if rest == 0 || rest >= largest { + return false + } + previous := largest % rest + if previous == 0 { + return false + } + total = rest + previous + heap.Push(h, previous) + } +} diff --git a/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.java b/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.java new file mode 100644 index 00000000..c1cc6992 --- /dev/null +++ b/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.java @@ -0,0 +1,28 @@ +import java.util.PriorityQueue; + +class Solution { + public boolean isPossible(int[] target) { + PriorityQueue heap = new PriorityQueue<>((a, b) -> Long.compare(b, a)); + long total = 0; + for (int v : target) { + heap.offer((long) v); + total += v; + } + while (true) { + long largest = heap.poll(); + long rest = total - largest; + if (largest == 1 || rest == 1) { + return true; + } + if (rest == 0 || rest >= largest) { + return false; + } + long previous = largest % rest; + if (previous == 0) { + return false; + } + total = rest + previous; + heap.offer(previous); + } + } +} diff --git a/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.kt b/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.kt new file mode 100644 index 00000000..202b04f5 --- /dev/null +++ b/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.kt @@ -0,0 +1,28 @@ +import java.util.PriorityQueue + +class Solution { + fun isPossible(target: IntArray): Boolean { + val heap = PriorityQueue(compareByDescending { it }) + var total = 0L + for (v in target) { + heap.offer(v.toLong()) + total += v + } + while (true) { + val largest = heap.poll() + val rest = total - largest + if (largest == 1L || rest == 1L) { + return true + } + if (rest == 0L || rest >= largest) { + return false + } + val previous = largest % rest + if (previous == 0L) { + return false + } + total = rest + previous + heap.offer(previous) + } + } +} diff --git a/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.py b/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.py new file mode 100644 index 00000000..afb1e451 --- /dev/null +++ b/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.py @@ -0,0 +1,23 @@ +import heapq + + +class Solution: + def isPossible(self, target: List[int]) -> bool: + total = sum(target) + heap = [-value for value in target] + heapq.heapify(heap) + + while True: + largest = -heapq.heappop(heap) + rest = total - largest + if largest == 1 or rest == 1: + return True + if rest == 0 or rest >= largest: + return False + + previous = largest % rest + if previous == 0: + return False + + total = rest + previous + heapq.heappush(heap, -previous) diff --git a/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.py2 b/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.py2 new file mode 100644 index 00000000..13f43ab2 --- /dev/null +++ b/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.py2 @@ -0,0 +1,22 @@ +class Solution(object): + def isPossible(self, target): + """ + :type target: List[int] + :rtype: bool + """ + import heapq + total = sum(target) + heap = [-x for x in target] + heapq.heapify(heap) + while True: + largest = -heapq.heappop(heap) + rest = total - largest + if largest == 1 or rest == 1: + return True + if rest == 0 or rest >= largest: + return False + previous = largest % rest + if previous == 0: + return False + total = rest + previous + heapq.heappush(heap, -previous) diff --git a/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.rb b/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.rb new file mode 100644 index 00000000..88461801 --- /dev/null +++ b/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.rb @@ -0,0 +1,24 @@ +# @param {Integer[]} target +# @return {Boolean} +def is_possible(target) + total = target.sum + heap = target.map { |x| -x } + heap.sort! + while true + largest = -heap.shift + rest = total - largest + if largest == 1 || rest == 1 + return true + end + if rest == 0 || rest >= largest + return false + end + previous = largest % rest + if previous == 0 + return false + end + total = rest + previous + heap << -previous + heap.sort! + end +end diff --git a/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.rs b/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.rs new file mode 100644 index 00000000..609eb762 --- /dev/null +++ b/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.rs @@ -0,0 +1,28 @@ +use std::collections::BinaryHeap; + +impl Solution { + pub fn is_possible(target: Vec) -> bool { + let mut heap: BinaryHeap = BinaryHeap::new(); + let mut total: i64 = 0; + for &v in &target { + heap.push(v as i64); + total += v as i64; + } + loop { + let largest = heap.pop().unwrap(); + let rest = total - largest; + if largest == 1 || rest == 1 { + return true; + } + if rest == 0 || rest >= largest { + return false; + } + let previous = largest % rest; + if previous == 0 { + return false; + } + total = rest + previous; + heap.push(previous); + } + } +} diff --git a/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.swift b/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.swift new file mode 100644 index 00000000..8eb1df0f --- /dev/null +++ b/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.swift @@ -0,0 +1,25 @@ +import Collections + +class Solution { + func isPossible(_ target: [Int]) -> Bool { + var heap = Heap(target) + var total = target.reduce(0, +) + while true { + guard let largest = heap.popMax() else { break } + let rest = total - largest + if largest == 1 || rest == 1 { + return true + } + if rest == 0 || rest >= largest { + return false + } + let previous = largest % rest + if previous == 0 { + return false + } + total = rest + previous + heap.insert(previous) + } + return false + } +} diff --git a/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.ts b/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.ts new file mode 100644 index 00000000..c972235c --- /dev/null +++ b/tests/1001-1500/1354. construct-target-array-with-multiple-sums/sol.ts @@ -0,0 +1,15 @@ +function isPossible(target: number[]): boolean { + const values = target.slice(); + let total = values.reduce((sum, value) => sum + value, 0); + while (true) { + values.sort((a, b) => b - a); + const largest = values[0], + rest = total - largest; + if (largest === 1 || rest === 1) return true; + if (rest === 0 || rest >= largest) return false; + const previous = largest % rest; + if (previous === 0) return false; + values[0] = previous; + total = rest + previous; + } +} diff --git a/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/manifest.yaml b/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/manifest.yaml new file mode 100644 index 00000000..ed3cf219 --- /dev/null +++ b/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/manifest.yaml @@ -0,0 +1,252 @@ +entry: + id: 1356 + title: "sort-integers-by-the-number-of-1-bits" + params: + arr: + type: array + items: + type: int + call: + cpp: "Solution().sortByBits({arr})" + rust: "Solution::sort_by_bits({arr})" + python3: "Solution().sortByBits({arr})" + python2: "Solution().sortByBits({arr})" + ruby: "sort_by_bits({arr})" + java: "new Solution().sortByBits({arr})" + csharp: "new Solution().SortByBits({arr})" + kotlin: "Solution().sortByBits({arr})" + go: "sortByBits({arr})" + dart: "Solution().sortByBits({arr})" + swift: "Solution().sortByBits({arr})" + typescript: "sortByBits({arr})" + +judge: + type: "exact" + +limits: + time_ms: 300 + memory_mb: 300 + +oracle: + python3: + call: "Checker().sortByBits(arr, {result})" + checker: | + class Checker: + def sortByBits(self, arr, result): + if not isinstance(result, list) or len(result) != len(arr): + return False + if sorted(result) != sorted(arr): + return False + def ones(value): + total = 0 + while value: + total += value & 1 + value >>= 1 + return total + for index in range(1, len(result)): + if (ones(result[index - 1]), result[index - 1]) > (ones(result[index]), result[index]): + return False + return True + +seed: 1356001 + +tests: + - name: "example_1" + in: + arr: [0, 1, 2, 3, 4, 5, 6, 7, 8] + out: [0, 1, 2, 4, 8, 3, 5, 6, 7] + - name: "example_2" + in: + arr: [1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1] + out: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] + - name: "single_zero" + in: + arr: [0] + out: [0] + - name: "single_upper_bound" + in: + arr: [10000] + out: [10000] + - name: "two_values" + in: + arr: [10000, 0] + out: [0, 10000] + - name: "all_same_popcount" + in: + arr: [15, 3, 5, 9, 10, 12, 6] + out: [3, 5, 6, 9, 10, 12, 15] + - name: "duplicates_across_groups" + in: + arr: [7, 3, 7, 0, 3, 1, 0, 7] + out: [0, 0, 1, 3, 3, 7, 7, 7] + - name: "all_zeroes" + in: + arr: [0, 0, 0, 0, 0] + out: [0, 0, 0, 0, 0] + - name: "zero_and_powers" + in: + arr: [16, 0, 8, 4, 2, 1] + out: [0, 1, 2, 4, 8, 16] + - name: "two_bit_ties" + in: + arr: [192, 33, 6, 129, 3, 18, 9] + out: [3, 6, 9, 18, 33, 129, 192] + - name: "high_bit_values" + in: + arr: [8191, 8192, 8193, 9999, 10000] + out: [8192, 8193, 10000, 9999, 8191] + - name: "boundary_mix" + in: + arr: [10000, 0, 9999, 1, 4096, 8192, 1023, 1024] + out: [0, 1, 1024, 4096, 8192, 10000, 9999, 1023] + - name: "alternating_patterns" + in: + arr: [682, 341, 170, 85, 255, 256] + out: [256, 85, 170, 341, 682, 255] + - name: "small_duplicates" + in: + arr: [2, 2, 2, 1, 1, 3, 3, 0] + out: [0, 1, 1, 2, 2, 2, 3, 3] + - name: "valid_ten_thousand_patterns" + in: + arr: [8192, 5461, 4096, 8191, 2730, 10000] + out: [4096, 8192, 10000, 2730, 5461, 8191] + - name: "mixed_small" + in: + arr: [14, 11, 13, 10, 12, 8, 7, 4] + out: [4, 8, 10, 12, 7, 11, 13, 14] + - name: "near_upper_bound" + in: + arr: [9990, 9991, 9992, 9993, 9994, 9995, 9996, 9997, 9998, 9999, 10000] + out: [9992, 10000, 9990, 9993, 9994, 9996, 9991, 9995, 9997, 9998, 9999] + - name: "powers_and_masks" + in: + arr: [512, 511, 256, 255, 128, 127, 64, 63] + out: [64, 128, 256, 512, 63, 127, 255, 511] + - name: "single_bit_scattered" + in: + arr: [4096, 32, 2048, 2, 8192, 128, 1] + out: [1, 2, 32, 128, 2048, 4096, 8192] + - name: "popcount_three" + in: + arr: [28, 25, 22, 21, 14, 13, 11, 7] + out: [7, 11, 13, 14, 21, 22, 25, 28] + - name: "popcount_four" + in: + arr: [43, 39, 30, 29, 27, 23, 15] + out: [15, 23, 27, 29, 30, 39, 43] + - name: "repeated_upper_values" + in: + arr: [10000, 10000, 9999, 9999] + out: [10000, 10000, 9999, 9999] + - name: "low_range_reverse" + in: + arr: [31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16] + out: [16, 17, 18, 20, 24, 19, 21, 22, 25, 26, 28, 23, 27, 29, 30, 31] + - name: "equal_values_and_ties" + in: + arr: [42, 7, 42, 7, 0, 15] + out: [0, 7, 7, 42, 42, 15] + - name: "upper_boundary_ties" + in: + arr: [8191, 4095, 2047, 1023, 10000, 9999] + out: [10000, 9999, 1023, 2047, 4095, 8191] + - name: "consecutive_zero_to_fifteen" + in: + arr: [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] + out: [0, 1, 2, 4, 8, 3, 5, 6, 9, 10, 12, 7, 11, 13, 14, 15] + - name: "maximum_popcount_in_range" + in: + arr: [8191, 4095, 2047, 1023, 511, 255, 127, 63] + out: [63, 127, 255, 511, 1023, 2047, 4095, 8191] + - name: "sparse_high_and_low" + in: + arr: [9999, 8192, 5000, 4097, 2049, 1025, 513, 257, 129, 65, 33, 17] + out: [8192, 17, 33, 65, 129, 257, 513, 1025, 2049, 4097, 5000, 9999] + - name: "input_already_correct" + in: + arr: [0, 1, 2, 4, 8, 3, 5, 6, 7] + out: [0, 1, 2, 4, 8, 3, 5, 6, 7] + - name: "input_reverse_correct_order" + in: + arr: [7, 6, 5, 3, 8, 4, 2, 1, 0] + out: [0, 1, 2, 4, 8, 3, 5, 6, 7] + - name: "mixed_zeroes_and_upper_bound" + in: + arr: [0, 10000, 0, 8192, 9999, 1, 1, 4096] + out: [0, 0, 1, 1, 4096, 8192, 10000, 9999] + - name: "bit_count_transition" + in: + arr: [255, 256, 257, 511, 512, 513, 1023, 1024] + out: [256, 512, 1024, 257, 513, 255, 511, 1023] + - name: "selected_five_bit_values" + in: + arr: [31, 47, 55, 59, 61, 62, 992, 961] + out: [31, 47, 55, 59, 61, 62, 961, 992] + - name: "one_four_and_five_bit_groups" + in: + arr: [47, 32, 31, 23, 16, 15] + out: [16, 32, 15, 23, 31, 47] + - name: "nine_bit_masks_and_powers" + in: + arr: [1023, 512, 511, 256, 255, 128, 127, 64] + out: [64, 128, 256, 512, 127, 255, 511, 1023] + - name: "generated_small" + seed: 135601 + in: + arr: + gen: "array" + len: + gen: "int" + min: 1 + max: 30 + of: + gen: "int" + min: 0 + max: 10000 + - name: "generated_medium" + seed: 135602 + in: + arr: + gen: "array" + len: + gen: "int" + min: 50 + max: 150 + of: + gen: "int" + min: 0 + max: 10000 + - name: "generated_duplicate_heavy" + seed: 135603 + in: + arr: + gen: "array" + len: + gen: "int" + min: 100 + max: 200 + of: + gen: "int" + min: 0 + max: 31 + - name: "generated_maximum_length" + seed: 135604 + in: + arr: + gen: "array" + len: 500 + of: + gen: "int" + min: 0 + max: 10000 + - name: "generated_maximum_length_low_domain" + seed: 135605 + in: + arr: + gen: "array" + len: 500 + of: + gen: "int" + min: 0 + max: 255 diff --git a/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.cpp b/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.cpp new file mode 100644 index 00000000..b5d71ffb --- /dev/null +++ b/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + vector sortByBits(vector& arr) { + sort(arr.begin(), arr.end(), [](int a, int b) { + int ca = __builtin_popcount(a); + int cb = __builtin_popcount(b); + if (ca != cb) return ca < cb; + return a < b; + }); + return arr; + } +}; diff --git a/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.cs b/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.cs new file mode 100644 index 00000000..98ff63c2 --- /dev/null +++ b/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.cs @@ -0,0 +1,16 @@ +public class Solution { + private int PopCount(int value) { + int count = 0; + while (value != 0) { value &= value - 1; count++; } + return count; + } + public int[] SortByBits(int[] arr) { + Array.Sort(arr, (a, b) => { + int ca = PopCount(a); + int cb = PopCount(b); + if (ca != cb) return ca - cb; + return a - b; + }); + return arr; + } +} diff --git a/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.dart b/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.dart new file mode 100644 index 00000000..10e89b59 --- /dev/null +++ b/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.dart @@ -0,0 +1,11 @@ +class Solution { + List sortByBits(List arr) { + arr.sort((a, b) { + int ca = a.bitLength == 0 ? 0 : a.toRadixString(2).replaceAll('0', '').length; + int cb = b.bitLength == 0 ? 0 : b.toRadixString(2).replaceAll('0', '').length; + if (ca != cb) return ca - cb; + return a - b; + }); + return arr; + } +} diff --git a/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.go b/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.go new file mode 100644 index 00000000..ed47bf32 --- /dev/null +++ b/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.go @@ -0,0 +1,11 @@ +func sortByBits(arr []int) []int { + sort.Slice(arr, func(i, j int) bool { + ci := bits.OnesCount(uint(arr[i])) + cj := bits.OnesCount(uint(arr[j])) + if ci != cj { + return ci < cj + } + return arr[i] < arr[j] + }) + return arr +} diff --git a/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.java b/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.java new file mode 100644 index 00000000..be5b9109 --- /dev/null +++ b/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.java @@ -0,0 +1,12 @@ +class Solution { + public int[] sortByBits(int[] arr) { + Integer[] boxed = Arrays.stream(arr).boxed().toArray(Integer[]::new); + Arrays.sort(boxed, (a, b) -> { + int ca = Integer.bitCount(a); + int cb = Integer.bitCount(b); + if (ca != cb) return ca - cb; + return a - b; + }); + return Arrays.stream(boxed).mapToInt(Integer::intValue).toArray(); + } +} diff --git a/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.kt b/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.kt new file mode 100644 index 00000000..8b65dbe9 --- /dev/null +++ b/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.kt @@ -0,0 +1,5 @@ +class Solution { + fun sortByBits(arr: IntArray): IntArray { + return arr.sortedWith(compareBy { it.countOneBits() }.thenBy { it }).toIntArray() + } +} diff --git a/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.py b/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.py new file mode 100644 index 00000000..ad072478 --- /dev/null +++ b/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.py @@ -0,0 +1,3 @@ +class Solution: + def sortByBits(self, arr): + return sorted(arr, key=lambda x: (x.bit_count(), x)) diff --git a/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.py2 b/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.py2 new file mode 100644 index 00000000..4e58d034 --- /dev/null +++ b/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.py2 @@ -0,0 +1,7 @@ +class Solution(object): + def sortByBits(self, arr): + """ + :type arr: List[int] + :rtype: List[int] + """ + return sorted(arr, key=lambda x: (bin(x).count('1'), x)) diff --git a/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.rb b/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.rb new file mode 100644 index 00000000..1b9f8a7a --- /dev/null +++ b/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.rb @@ -0,0 +1,5 @@ +# @param {Integer[]} arr +# @return {Integer[]} +def sort_by_bits(arr) + arr.sort_by { |x| [x.to_s(2).count('1'), x] } +end diff --git a/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.rs b/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.rs new file mode 100644 index 00000000..92082ebb --- /dev/null +++ b/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn sort_by_bits(arr: Vec) -> Vec { + let mut arr = arr; + arr.sort_by(|a, b| { + let ca = a.count_ones(); + let cb = b.count_ones(); + if ca != cb { + ca.cmp(&cb) + } else { + a.cmp(b) + } + }); + arr + } +} diff --git a/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.swift b/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.swift new file mode 100644 index 00000000..d4ecf8b7 --- /dev/null +++ b/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.swift @@ -0,0 +1,10 @@ +class Solution { + func sortByBits(_ arr: [Int]) -> [Int] { + return arr.sorted { + let c0 = $0.nonzeroBitCount + let c1 = $1.nonzeroBitCount + if c0 != c1 { return c0 < c1 } + return $0 < $1 + } + } +} diff --git a/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.ts b/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.ts new file mode 100644 index 00000000..c50cdfeb --- /dev/null +++ b/tests/1001-1500/1356. sort-integers-by-the-number-of-1-bits/sol.ts @@ -0,0 +1,8 @@ +function sortByBits(arr: number[]): number[] { + return arr.sort((a, b) => { + const ca = a.toString(2).split("1").length - 1; + const cb = b.toString(2).split("1").length - 1; + if (ca !== cb) return ca - cb; + return a - b; + }); +} diff --git a/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/manifest.yaml b/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/manifest.yaml new file mode 100644 index 00000000..3334fac3 --- /dev/null +++ b/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/manifest.yaml @@ -0,0 +1,205 @@ +entry: + id: 1358 + title: "number-of-substrings-containing-all-three-characters" + params: + s: + type: string + call: + cpp: "Solution().numberOfSubstrings({s})" + rust: "Solution::number_of_substrings({s})" + python3: "Solution().numberOfSubstrings({s})" + python2: "Solution().numberOfSubstrings({s})" + ruby: "number_of_substrings({s})" + java: "new Solution().numberOfSubstrings({s})" + csharp: "new Solution().NumberOfSubstrings({s})" + kotlin: "Solution().numberOfSubstrings({s})" + go: "numberOfSubstrings({s})" + dart: "Solution().numberOfSubstrings({s})" + swift: "Solution().numberOfSubstrings({s})" + typescript: "numberOfSubstrings({s})" + +judge: + type: "exact" + +limits: + time_ms: 500 + memory_mb: 300 + +oracle: + python3: + call: "Checker().numberOfSubstrings(s, {result})" + checker: | + class Checker: + def numberOfSubstrings(self, s, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + counts = [0, 0, 0] + left = 0 + expected = 0 + for right, ch in enumerate(s): + counts[ord(ch) - ord('a')] += 1 + while counts[0] and counts[1] and counts[2]: + expected += len(s) - right + counts[ord(s[left]) - ord('a')] -= 1 + left += 1 + return result == expected + +seed: 1358 + +tests: + - name: "example_abcabc" + in: + s: "abcabc" + - name: "example_aaacb" + in: + s: "aaacb" + - name: "example_minimum" + in: + s: "abc" + - name: "minimum_reverse_order" + in: + s: "cba" + - name: "minimum_permuted_order" + in: + s: "bac" + - name: "all_a_missing_b_c" + in: + s: "aaa" + - name: "missing_c" + in: + s: "aabbab" + - name: "missing_b" + in: + s: "acacaa" + - name: "missing_a" + in: + s: "cbcbcc" + - name: "valid_only_at_end" + in: + s: "aaaaabbbbbc" + - name: "valid_only_at_start" + in: + s: "caaaaabbbbb" + - name: "repeated_a_prefix" + in: + s: "aaaaabc" + - name: "repeated_b_middle" + in: + s: "abbbbbc" + - name: "repeated_c_suffix" + in: + s: "abccccc" + - name: "four_char_boundary" + in: + s: "abca" + - name: "five_char_overlap" + in: + s: "cabac" + - name: "three_complete_cycles" + in: + s: "abcabcabc" + - name: "reverse_cycles" + in: + s: "cbacba" + - name: "palindromic_mix" + in: + s: "abccba" + - name: "alternating_windows" + in: + s: "abacbc" + - name: "clustered_letters" + in: + s: "aaabbbccc" + - name: "blocks_reverse" + in: + s: "cccbbbaaa" + - name: "first_c_late" + in: + s: "aababbabbc" + - name: "first_a_late" + in: + s: "cbcbcbcbca" + - name: "dense_mixed" + in: + s: "cbacbbacacba" + - name: "overlapping_long_windows" + in: + s: "abcaaabbbccc" + - name: "all_blocks_then_cycle" + in: + s: "aaacccbbbabc" + - name: "frequent_left_shrinks" + in: + s: "abcabcabcabc" + - name: "sparse_restarts" + in: + s: "aaccbbaac" + - name: "single_each_separated" + in: + s: "abbbbbbbbbc" + - name: "duplicate_first_and_last" + in: + s: "aabcbca" + - name: "large_a_b_c_blocks" + in: + s: "aaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbcccccccccccccccccccc" + - name: "large_periodic_static" + in: + s: "abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc" + - name: "generated_short_uniform" + seed: 101 + in: + s: + gen: "str" + len: + gen: "int" + min: 3 + max: 30 + alphabet: "abc" + - name: "generated_medium_uniform" + seed: 202 + in: + s: + gen: "str" + len: + gen: "int" + min: 500 + max: 1000 + alphabet: "abc" + - name: "generated_a_heavy" + seed: 303 + in: + s: + gen: "str" + len: + gen: "int" + min: 1000 + max: 3000 + alphabet: "aaaabc" + - name: "generated_c_heavy" + seed: 404 + in: + s: + gen: "str" + len: + gen: "int" + min: 1000 + max: 3000 + alphabet: "abcccc" + - name: "generated_max_uniform" + seed: 505 + in: + s: + gen: "str" + len: 50000 + alphabet: "abc" + - name: "generated_max_biased" + seed: 606 + in: + s: + gen: "str" + len: 50000 + alphabet: "aaaabc" + - name: "long_prefix_then_dense_tail" + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbcabccabccabccabccabccabccabcc" diff --git a/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.cpp b/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.cpp new file mode 100644 index 00000000..d2d5b05f --- /dev/null +++ b/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int numberOfSubstrings(string s) { + int res = 0; + int p[4] = {50000, -1, -1, -1}; + for (int i = 0; i < s.size(); i++) { + p[s[i] & 31] = i; + res += min({p[1], p[2], p[3]}) + 1; + } + return res; + } +}; diff --git a/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.cs b/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.cs new file mode 100644 index 00000000..fd01b078 --- /dev/null +++ b/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.cs @@ -0,0 +1,11 @@ +public class Solution { + public int NumberOfSubstrings(string s) { + int res = 0; + int[] p = {50000, -1, -1, -1}; + for (int i = 0; i < s.Length; i++) { + p[s[i] & 31] = i; + res += Math.Min(Math.Min(p[1], p[2]), p[3]) + 1; + } + return res; + } +} diff --git a/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.dart b/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.dart new file mode 100644 index 00000000..1985f6ac --- /dev/null +++ b/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.dart @@ -0,0 +1,14 @@ +class Solution { + int numberOfSubstrings(String s) { + int res = 0; + List p = [50000, -1, -1, -1]; + for (int i = 0; i < s.length; i++) { + p[s.codeUnitAt(i) & 31] = i; + int min = p[1]; + if (p[2] < min) min = p[2]; + if (p[3] < min) min = p[3]; + res += min + 1; + } + return res; + } +} diff --git a/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.go b/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.go new file mode 100644 index 00000000..50721211 --- /dev/null +++ b/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.go @@ -0,0 +1,12 @@ +func numberOfSubstrings(s string) int { + res := 0 + p := [4]int{50000, -1, -1, -1} + for i, ch := range s { + p[ch&31] = i + min := p[1] + if p[2] < min { min = p[2] } + if p[3] < min { min = p[3] } + res += min + 1 + } + return res +} diff --git a/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.java b/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.java new file mode 100644 index 00000000..2e6edfe8 --- /dev/null +++ b/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.java @@ -0,0 +1,11 @@ +class Solution { + public int numberOfSubstrings(String s) { + int res = 0; + int[] p = {50000, -1, -1, -1}; + for (int i = 0; i < s.length(); i++) { + p[s.charAt(i) & 31] = i; + res += Math.min(Math.min(p[1], p[2]), p[3]) + 1; + } + return res; + } +} diff --git a/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.kt b/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.kt new file mode 100644 index 00000000..949235d8 --- /dev/null +++ b/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.kt @@ -0,0 +1,11 @@ +class Solution { + fun numberOfSubstrings(s: String): Int { + var res = 0 + val p = intArrayOf(50000, -1, -1, -1) + for (i in s.indices) { + p[s[i].code and 31] = i + res += minOf(p[1], p[2], p[3]) + 1 + } + return res + } +} diff --git a/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.py b/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.py new file mode 100644 index 00000000..dc2db8d4 --- /dev/null +++ b/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.py @@ -0,0 +1,9 @@ +class Solution: + def numberOfSubstrings(self, s: str) -> int: + res, p = 0, [5e4, -1, -1, -1] + + for i, ch in enumerate(s): + p[ord(ch) & 31] = i + res += min(p) + 1 + + return res diff --git a/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.py2 b/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.py2 new file mode 100644 index 00000000..93b7304c --- /dev/null +++ b/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.py2 @@ -0,0 +1,12 @@ +class Solution(object): + def numberOfSubstrings(self, s): + """ + :type s: str + :rtype: int + """ + res = 0 + p = [50000, -1, -1, -1] + for i, ch in enumerate(s): + p[ord(ch) & 31] = i + res += min(p) + 1 + return res diff --git a/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.rb b/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.rb new file mode 100644 index 00000000..8876820f --- /dev/null +++ b/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.rb @@ -0,0 +1,11 @@ +# @param {String} s +# @return {Integer} +def number_of_substrings(s) + res = 0 + p = [50000, -1, -1, -1] + s.each_char.with_index do |ch, i| + p[ch.ord & 31] = i + res += p.min + 1 + end + res +end diff --git a/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.rs b/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.rs new file mode 100644 index 00000000..1afbc6b2 --- /dev/null +++ b/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.rs @@ -0,0 +1,11 @@ +impl Solution { + pub fn number_of_substrings(s: String) -> i32 { + let mut res = 0; + let mut p = [50000i32, -1, -1, -1]; + for (i, ch) in s.bytes().enumerate() { + p[(ch & 31) as usize] = i as i32; + res += p[1].min(p[2]).min(p[3]) + 1; + } + res + } +} diff --git a/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.swift b/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.swift new file mode 100644 index 00000000..31a2b54d --- /dev/null +++ b/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.swift @@ -0,0 +1,11 @@ +class Solution { + func numberOfSubstrings(_ s: String) -> Int { + var res = 0 + var p = [50000, -1, -1, -1] + for (i, ch) in s.enumerated() { + p[Int(ch.asciiValue! & 31)] = i + res += min(p[1], p[2], p[3]) + 1 + } + return res + } +} diff --git a/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.ts b/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.ts new file mode 100644 index 00000000..1df53cc8 --- /dev/null +++ b/tests/1001-1500/1358. number-of-substrings-containing-all-three-characters/sol.ts @@ -0,0 +1,9 @@ +function numberOfSubstrings(s: string): number { + let res = 0; + const p: number[] = [50000, -1, -1, -1]; + for (let i = 0; i < s.length; i++) { + p[s.charCodeAt(i) & 31] = i; + res += Math.min(p[1], p[2], p[3]) + 1; + } + return res; +} diff --git a/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/manifest.yaml b/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/manifest.yaml new file mode 100644 index 00000000..17fd88ea --- /dev/null +++ b/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/manifest.yaml @@ -0,0 +1,221 @@ +entry: + id: 1359 + title: "count-all-valid-pickup-and-delivery-options" + params: + n: + type: int + call: + cpp: "Solution().countOrders({n})" + rust: "Solution::count_orders({n})" + python3: "Solution().countOrders({n})" + python2: "Solution().countOrders({n})" + ruby: "count_orders({n})" + java: "new Solution().countOrders({n})" + csharp: "new Solution().CountOrders({n})" + kotlin: "Solution().countOrders({n})" + go: "countOrders({n})" + dart: "Solution().countOrders({n})" + swift: "Solution().countOrders({n})" + typescript: "countOrders({n})" + +judge: + type: "exact" + +limits: + time_ms: 200 + memory_mb: 300 + +oracle: + python3: + call: "Checker().countOrders(n, {result})" + checker: | + class Checker: + def countOrders(self, n, result): + if not isinstance(n, int) or not 1 <= n <= 500: + return False + if not isinstance(result, int) or isinstance(result, bool): + return False + modulo = 10 ** 9 + 7 + factorial = 1 + for value in range(2, 2 * n + 1): + factorial = factorial * value % modulo + expected = factorial * pow(pow(2, n, modulo), modulo - 2, modulo) % modulo + return result == expected + +seed: 1359 + +tests: + - name: "n_1_minimum" + in: + n: 1 + out: 1 + - name: "n_2_example" + in: + n: 2 + out: 6 + - name: "n_3_example" + in: + n: 3 + out: 90 + - name: "n_4" + in: + n: 4 + out: 2520 + - name: "n_5" + in: + n: 5 + out: 113400 + - name: "n_6" + in: + n: 6 + out: 7484400 + - name: "n_7" + in: + n: 7 + out: 681080400 + - name: "n_8_modulo" + in: + n: 8 + out: 729647433 + - name: "n_9" + in: + n: 9 + out: 636056472 + - name: "n_10" + in: + n: 10 + out: 850728840 + - name: "n_11" + in: + n: 11 + out: 518360668 + - name: "n_12" + in: + n: 12 + out: 67543367 + - name: "n_13" + in: + n: 13 + out: 951594128 + - name: "n_14" + in: + n: 14 + out: 702577871 + - name: "n_15" + in: + n: 15 + out: 621371750 + - name: "n_16" + in: + n: 16 + out: 200385844 + - name: "n_17" + in: + n: 17 + out: 416457700 + - name: "n_18" + in: + n: 18 + out: 368349166 + - name: "n_19" + in: + n: 19 + out: 949461892 + - name: "n_20" + in: + n: 20 + out: 580270580 + - name: "n_25" + in: + n: 25 + out: 586091532 + - name: "n_33" + in: + n: 33 + out: 292697959 + - name: "n_50" + in: + n: 50 + out: 784760423 + - name: "n_64" + in: + n: 64 + out: 989640570 + - name: "n_75" + in: + n: 75 + out: 149163518 + - name: "n_100" + in: + n: 100 + out: 14159051 + - name: "n_125" + in: + n: 125 + out: 129345050 + - name: "n_128" + in: + n: 128 + out: 761756041 + - name: "n_200" + in: + n: 200 + out: 880584563 + - name: "n_250" + in: + n: 250 + out: 418733499 + - name: "n_300" + in: + n: 300 + out: 234038968 + - name: "n_350_oracle" + in: + n: 350 + - name: "n_400" + in: + n: 400 + out: 467993882 + - name: "n_499_boundary" + in: + n: 499 + out: 496638171 + - name: "n_500_maximum" + in: + n: 500 + out: 764678010 + - name: "generated_small" + seed: 101 + in: + n: + gen: "int" + min: 1 + max: 10 + - name: "generated_mid" + seed: 202 + in: + n: + gen: "int" + min: 11 + max: 100 + - name: "generated_upper_mid" + seed: 303 + in: + n: + gen: "int" + min: 101 + max: 300 + - name: "generated_large" + seed: 404 + in: + n: + gen: "int" + min: 301 + max: 499 + - name: "generated_full_range" + seed: 505 + in: + n: + gen: "int" + min: 1 + max: 500 diff --git a/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.cpp b/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.cpp new file mode 100644 index 00000000..b3caaadc --- /dev/null +++ b/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + int countOrders(int n) { + const int MOD = 1000000007; + long long count = 1; + for (int i = 2; i <= n; i++) { + count = (count * (2LL * i - 1) * i) % MOD; + } + return (int) count; + } +}; diff --git a/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.cs b/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.cs new file mode 100644 index 00000000..e5382fa3 --- /dev/null +++ b/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.cs @@ -0,0 +1,10 @@ +public class Solution { + public int CountOrders(int n) { + const int MOD = 1000000007; + long count = 1; + for (int i = 2; i <= n; i++) { + count = (count * (2L * i - 1) * i) % MOD; + } + return (int) count; + } +} diff --git a/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.dart b/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.dart new file mode 100644 index 00000000..c8e7b46d --- /dev/null +++ b/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.dart @@ -0,0 +1,10 @@ +class Solution { + int countOrders(int n) { + const MOD = 1000000007; + int count = 1; + for (int i = 2; i <= n; i++) { + count = (count * (2 * i - 1) * i) % MOD; + } + return count; + } +} diff --git a/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.go b/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.go new file mode 100644 index 00000000..5fbae937 --- /dev/null +++ b/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.go @@ -0,0 +1,8 @@ +func countOrders(n int) int { + const MOD = 1000000007 + count := 1 + for i := 2; i <= n; i++ { + count = (count * (2*i - 1) * i) % MOD + } + return count +} diff --git a/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.java b/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.java new file mode 100644 index 00000000..7eb58ead --- /dev/null +++ b/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.java @@ -0,0 +1,10 @@ +class Solution { + public int countOrders(int n) { + final int MOD = 1000000007; + long count = 1; + for (int i = 2; i <= n; i++) { + count = (count * (2L * i - 1) * i) % MOD; + } + return (int) count; + } +} diff --git a/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.kt b/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.kt new file mode 100644 index 00000000..a87d485e --- /dev/null +++ b/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.kt @@ -0,0 +1,10 @@ +class Solution { + fun countOrders(n: Int): Int { + val MOD = 1000000007 + var count = 1L + for (i in 2..n) { + count = (count * (2L * i - 1) * i) % MOD + } + return count.toInt() + } +} diff --git a/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.py b/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.py new file mode 100644 index 00000000..ce3f908e --- /dev/null +++ b/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.py @@ -0,0 +1,9 @@ +MOD = 10**9 + 7 + + +class Solution: + def countOrders(self, n: int) -> int: + count = 1 + for i in range(2, n + 1): + count = (count * (2 * i - 1) * i) % MOD + return count diff --git a/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.py2 b/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.py2 new file mode 100644 index 00000000..66ce5603 --- /dev/null +++ b/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.py2 @@ -0,0 +1,11 @@ +class Solution(object): + def countOrders(self, n): + """ + :type n: int + :rtype: int + """ + MOD = 10**9 + 7 + count = 1 + for i in range(2, n + 1): + count = (count * (2 * i - 1) * i) % MOD + return count diff --git a/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.rb b/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.rb new file mode 100644 index 00000000..148b96c9 --- /dev/null +++ b/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.rb @@ -0,0 +1,10 @@ +# @param {Integer} n +# @return {Integer} +def count_orders(n) + mod = 10**9 + 7 + count = 1 + (2..n).each do |i| + count = (count * (2 * i - 1) * i) % mod + end + count +end diff --git a/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.rs b/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.rs new file mode 100644 index 00000000..d82bbef4 --- /dev/null +++ b/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.rs @@ -0,0 +1,10 @@ +impl Solution { + pub fn count_orders(n: i32) -> i32 { + const MOD: i64 = 1_000_000_007; + let mut count: i64 = 1; + for i in 2..=n as i64 { + count = (count * (2 * i - 1) * i) % MOD; + } + count as i32 + } +} diff --git a/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.swift b/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.swift new file mode 100644 index 00000000..ef23b56c --- /dev/null +++ b/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.swift @@ -0,0 +1,12 @@ +class Solution { + func countOrders(_ n: Int) -> Int { + let MOD = 1000000007 + var count = 1 + if n >= 2 { + for i in 2...n { + count = (count * (2 * i - 1) * i) % MOD + } + } + return count + } +} diff --git a/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.ts b/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.ts new file mode 100644 index 00000000..21431f0f --- /dev/null +++ b/tests/1001-1500/1359. count-all-valid-pickup-and-delivery-options/sol.ts @@ -0,0 +1,8 @@ +function countOrders(n: number): number { + const MOD = 1000000007; + let count = 1; + for (let i = 2; i <= n; i++) { + count = (count * (2 * i - 1) * i) % MOD; + } + return count; +} diff --git a/tests/1001-1500/1360. number-of-days-between-two-dates/manifest.yaml b/tests/1001-1500/1360. number-of-days-between-two-dates/manifest.yaml new file mode 100644 index 00000000..0739e960 --- /dev/null +++ b/tests/1001-1500/1360. number-of-days-between-two-dates/manifest.yaml @@ -0,0 +1,205 @@ +entry: + id: 1360 + title: "number-of-days-between-two-dates" + params: + date1: + type: string + date2: + type: string + call: + python3: "Solution().daysBetweenDates({date1}, {date2})" + python2: "Solution().daysBetweenDates({date1}, {date2})" + cpp: "Solution().daysBetweenDates({date1}, {date2})" + rust: "Solution::days_between_dates({date1}, {date2})" + ruby: "days_between_dates({date1}, {date2})" + java: "new Solution().daysBetweenDates({date1}, {date2})" + csharp: "new Solution().DaysBetweenDates({date1}, {date2})" + kotlin: "Solution().daysBetweenDates({date1}, {date2})" + go: "daysBetweenDates({date1}, {date2})" + dart: "Solution().daysBetweenDates({date1}, {date2})" + swift: "Solution().daysBetweenDates({date1}, {date2})" + typescript: "daysBetweenDates({date1}, {date2})" +judge: + type: "exact" +limits: + time_ms: 300 + memory_mb: 300 +oracle: + python3: + call: "Checker().daysBetweenDates(date1, date2, {result})" + checker: | + class Checker: + def _ordinal(self, date): + year, month, day = map(int, date.split('-')) + years_before = year - 1 + total = 365 * years_before + years_before // 4 - years_before // 100 + years_before // 400 + month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + total += sum(month_days[:month - 1]) + day + if month > 2 and (year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)): + total += 1 + return total + + def daysBetweenDates(self, date1, date2, result): + return isinstance(result, int) and not isinstance(result, bool) and result == abs(self._ordinal(date1) - self._ordinal(date2)) +seed: 1360 +tests: + - name: "example_one_adjacent_days" + in: + date1: "2019-06-29" + date2: "2019-06-30" + - name: "example_two_reverse_across_year" + in: + date1: "2020-01-15" + date2: "2019-12-31" + - name: "same_minimum_date" + in: + date1: "1971-01-01" + date2: "1971-01-01" + - name: "same_maximum_date" + in: + date1: "2100-12-31" + date2: "2100-12-31" + - name: "minimum_year_full_span" + in: + date1: "1971-01-01" + date2: "1971-12-31" + - name: "maximum_year_full_span" + in: + date1: "2100-01-01" + date2: "2100-12-31" + - name: "entire_allowed_range" + in: + date1: "1971-01-01" + date2: "2100-12-31" + - name: "entire_allowed_range_reverse" + in: + date1: "2100-12-31" + date2: "1971-01-01" + - name: "non_leap_february_transition" + in: + date1: "2019-02-28" + date2: "2019-03-01" + - name: "leap_february_two_day_transition" + in: + date1: "2020-02-28" + date2: "2020-03-01" + - name: "leap_day_to_march" + in: + date1: "2024-02-29" + date2: "2024-03-01" + - name: "leap_day_same_date" + in: + date1: "2000-02-29" + date2: "2000-02-29" + - name: "divisible_by_400_leap_year" + in: + date1: "2000-02-28" + date2: "2000-03-01" + - name: "non_leap_century_2100" + in: + date1: "2100-02-28" + date2: "2100-03-01" + - name: "year_end_adjacent" + in: + date1: "2019-12-31" + date2: "2020-01-01" + - name: "leap_year_end_adjacent" + in: + date1: "2020-12-31" + date2: "2021-01-01" + - name: "january_length" + in: + date1: "2021-01-01" + date2: "2021-02-01" + - name: "april_length" + in: + date1: "2021-04-01" + date2: "2021-05-01" + - name: "august_to_september" + in: + date1: "2022-08-31" + date2: "2022-09-01" + - name: "september_to_october" + in: + date1: "2022-09-30" + date2: "2022-10-01" + - name: "one_week" + in: + date1: "2022-05-01" + date2: "2022-05-08" + - name: "two_weeks_reverse" + in: + date1: "2022-05-15" + date2: "2022-05-01" + - name: "same_month_span" + in: + date1: "2021-08-10" + date2: "2021-08-25" + - name: "same_year_reverse" + in: + date1: "2021-11-30" + date2: "2021-03-15" + - name: "quarter_span" + in: + date1: "2023-01-01" + date2: "2023-04-01" + - name: "half_year_span" + in: + date1: "2022-01-01" + date2: "2022-07-01" + - name: "seasonal_span" + in: + date1: "2023-03-20" + date2: "2023-06-20" + - name: "summer_to_winter" + in: + date1: "2022-06-21" + date2: "2022-12-21" + - name: "leap_year_before_february" + in: + date1: "2020-01-31" + date2: "2020-02-29" + - name: "leap_year_after_february" + in: + date1: "2020-03-01" + date2: "2021-03-01" + - name: "four_year_interval_including_leap" + in: + date1: "2016-01-01" + date2: "2020-01-01" + - name: "leap_day_anniversary" + in: + date1: "2020-02-29" + date2: "2024-02-29" + - name: "multiple_leap_years" + in: + date1: "1996-06-15" + date2: "2004-06-15" + - name: "early_range_cross_month" + in: + date1: "1971-02-01" + date2: "1971-03-01" + - name: "late_range_cross_year" + in: + date1: "2099-12-30" + date2: "2100-01-02" + - name: "millennium_boundary" + in: + date1: "1999-12-31" + date2: "2000-01-01" + - name: "century_boundary_reverse" + in: + date1: "2001-01-01" + date2: "2000-12-31" + - name: "ordinary_february_month_span" + in: + date1: "2023-02-01" + date2: "2023-03-01" + - name: "leap_february_month_span" + in: + date1: "2024-02-01" + date2: "2024-03-01" + - name: "long_irregular_span" + in: + date1: "1987-07-14" + date2: "2053-11-26" diff --git a/tests/1001-1500/1360. number-of-days-between-two-dates/sol.cpp b/tests/1001-1500/1360. number-of-days-between-two-dates/sol.cpp new file mode 100644 index 00000000..358fc304 --- /dev/null +++ b/tests/1001-1500/1360. number-of-days-between-two-dates/sol.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int daysBetweenDates(string date1, string date2) { + int y1, m1, d1, y2, m2, d2; + sscanf(date1.c_str(), "%d-%d-%d", &y1, &m1, &d1); + sscanf(date2.c_str(), "%d-%d-%d", &y2, &m2, &d2); + return abs(daysSince1970(y1, m1, d1) - daysSince1970(y2, m2, d2)); + } + +private: + int daysSince1970(int y, int m, int d) { + if (m < 3) { + y--; + m += 12; + } + return 365 * y + y / 4 - y / 100 + y / 400 + (153 * m - 457) / 5 + d - 306 - 719468; + } +}; diff --git a/tests/1001-1500/1360. number-of-days-between-two-dates/sol.cs b/tests/1001-1500/1360. number-of-days-between-two-dates/sol.cs new file mode 100644 index 00000000..fd62c7d4 --- /dev/null +++ b/tests/1001-1500/1360. number-of-days-between-two-dates/sol.cs @@ -0,0 +1,17 @@ +public class Solution { + public int DaysBetweenDates(string date1, string date2) { + var parts1 = date1.Split('-').Select(int.Parse).ToArray(); + var parts2 = date2.Split('-').Select(int.Parse).ToArray(); + int y1 = parts1[0], m1 = parts1[1], d1 = parts1[2]; + int y2 = parts2[0], m2 = parts2[1], d2 = parts2[2]; + return Math.Abs(DaysSince1970(y1, m1, d1) - DaysSince1970(y2, m2, d2)); + } + + private int DaysSince1970(int y, int m, int d) { + if (m < 3) { + y--; + m += 12; + } + return 365 * y + y / 4 - y / 100 + y / 400 + (153 * m - 457) / 5 + d - 306 - 719468; + } +} diff --git a/tests/1001-1500/1360. number-of-days-between-two-dates/sol.dart b/tests/1001-1500/1360. number-of-days-between-two-dates/sol.dart new file mode 100644 index 00000000..77ff47ff --- /dev/null +++ b/tests/1001-1500/1360. number-of-days-between-two-dates/sol.dart @@ -0,0 +1,17 @@ +class Solution { + int daysBetweenDates(String date1, String date2) { + var parts1 = date1.split('-').map(int.parse).toList(); + var parts2 = date2.split('-').map(int.parse).toList(); + int y1 = parts1[0], m1 = parts1[1], d1 = parts1[2]; + int y2 = parts2[0], m2 = parts2[1], d2 = parts2[2]; + return (daysSince1970(y1, m1, d1) - daysSince1970(y2, m2, d2)).abs(); + } + + int daysSince1970(int y, int m, int d) { + if (m < 3) { + y--; + m += 12; + } + return 365 * y + y ~/ 4 - y ~/ 100 + y ~/ 400 + (153 * m - 457) ~/ 5 + d - 306 - 719468; + } +} diff --git a/tests/1001-1500/1360. number-of-days-between-two-dates/sol.go b/tests/1001-1500/1360. number-of-days-between-two-dates/sol.go new file mode 100644 index 00000000..318cb72f --- /dev/null +++ b/tests/1001-1500/1360. number-of-days-between-two-dates/sol.go @@ -0,0 +1,25 @@ +func daysBetweenDates(date1 string, date2 string) int { + y1, m1, d1 := parseDate(date1) + y2, m2, d2 := parseDate(date2) + diff := daysSince1970(y1, m1, d1) - daysSince1970(y2, m2, d2) + if diff < 0 { + return -diff + } + return diff +} + +func parseDate(date string) (int, int, int) { + parts := strings.Split(date, "-") + y, _ := strconv.Atoi(parts[0]) + m, _ := strconv.Atoi(parts[1]) + d, _ := strconv.Atoi(parts[2]) + return y, m, d +} + +func daysSince1970(y int, m int, d int) int { + if m < 3 { + y-- + m += 12 + } + return 365*y + y/4 - y/100 + y/400 + (153*m - 457)/5 + d - 306 - 719468 +} diff --git a/tests/1001-1500/1360. number-of-days-between-two-dates/sol.java b/tests/1001-1500/1360. number-of-days-between-two-dates/sol.java new file mode 100644 index 00000000..39c3066c --- /dev/null +++ b/tests/1001-1500/1360. number-of-days-between-two-dates/sol.java @@ -0,0 +1,21 @@ +class Solution { + public int daysBetweenDates(String date1, String date2) { + String[] parts1 = date1.split("-"); + String[] parts2 = date2.split("-"); + int y1 = Integer.parseInt(parts1[0]); + int m1 = Integer.parseInt(parts1[1]); + int d1 = Integer.parseInt(parts1[2]); + int y2 = Integer.parseInt(parts2[0]); + int m2 = Integer.parseInt(parts2[1]); + int d2 = Integer.parseInt(parts2[2]); + return Math.abs(daysSince1970(y1, m1, d1) - daysSince1970(y2, m2, d2)); + } + + private int daysSince1970(int y, int m, int d) { + if (m < 3) { + y--; + m += 12; + } + return 365 * y + y / 4 - y / 100 + y / 400 + (153 * m - 457) / 5 + d - 306 - 719468; + } +} diff --git a/tests/1001-1500/1360. number-of-days-between-two-dates/sol.kt b/tests/1001-1500/1360. number-of-days-between-two-dates/sol.kt new file mode 100644 index 00000000..5346dee0 --- /dev/null +++ b/tests/1001-1500/1360. number-of-days-between-two-dates/sol.kt @@ -0,0 +1,17 @@ +class Solution { + fun daysBetweenDates(date1: String, date2: String): Int { + val (y1, m1, d1) = date1.split("-").map { it.toInt() } + val (y2, m2, d2) = date2.split("-").map { it.toInt() } + return Math.abs(daysSince1970(y1, m1, d1) - daysSince1970(y2, m2, d2)) + } + + private fun daysSince1970(y: Int, m: Int, d: Int): Int { + var year = y + var month = m + if (month < 3) { + year-- + month += 12 + } + return 365 * year + year / 4 - year / 100 + year / 400 + (153 * month - 457) / 5 + d - 306 - 719468 + } +} diff --git a/tests/1001-1500/1360. number-of-days-between-two-dates/sol.py b/tests/1001-1500/1360. number-of-days-between-two-dates/sol.py new file mode 100644 index 00000000..9daa3dba --- /dev/null +++ b/tests/1001-1500/1360. number-of-days-between-two-dates/sol.py @@ -0,0 +1,8 @@ +import datetime + + +class Solution: + def daysBetweenDates(self, date1: str, date2: str) -> int: + y1, m1, d1 = map(int, date1.split("-")) + y2, m2, d2 = map(int, date2.split("-")) + return abs((datetime.date(y1, m1, d1) - datetime.date(y2, m2, d2)).days) diff --git a/tests/1001-1500/1360. number-of-days-between-two-dates/sol.py2 b/tests/1001-1500/1360. number-of-days-between-two-dates/sol.py2 new file mode 100644 index 00000000..23280736 --- /dev/null +++ b/tests/1001-1500/1360. number-of-days-between-two-dates/sol.py2 @@ -0,0 +1,11 @@ +class Solution(object): + def daysBetweenDates(self, date1, date2): + """ + :type date1: str + :type date2: str + :rtype: int + """ + import datetime + y1, m1, d1 = map(int, date1.split('-')) + y2, m2, d2 = map(int, date2.split('-')) + return abs((datetime.date(y1, m1, d1) - datetime.date(y2, m2, d2)).days) diff --git a/tests/1001-1500/1360. number-of-days-between-two-dates/sol.rb b/tests/1001-1500/1360. number-of-days-between-two-dates/sol.rb new file mode 100644 index 00000000..7b6dfea8 --- /dev/null +++ b/tests/1001-1500/1360. number-of-days-between-two-dates/sol.rb @@ -0,0 +1,9 @@ +# @param {String} date1 +# @param {String} date2 +# @return {Integer} +def days_between_dates(date1, date2) + require 'date' + y1, m1, d1 = date1.split('-').map(&:to_i) + y2, m2, d2 = date2.split('-').map(&:to_i) + (Date.new(y1, m1, d1) - Date.new(y2, m2, d2)).to_i.abs +end diff --git a/tests/1001-1500/1360. number-of-days-between-two-dates/sol.rs b/tests/1001-1500/1360. number-of-days-between-two-dates/sol.rs new file mode 100644 index 00000000..10c4c61d --- /dev/null +++ b/tests/1001-1500/1360. number-of-days-between-two-dates/sol.rs @@ -0,0 +1,21 @@ +impl Solution { + pub fn days_between_dates(date1: String, date2: String) -> i32 { + let (y1, m1, d1) = Self::parse(&date1); + let (y2, m2, d2) = Self::parse(&date2); + (Self::days_since_1970(y1, m1, d1) - Self::days_since_1970(y2, m2, d2)).abs() + } + + fn parse(date: &str) -> (i32, i32, i32) { + let parts: Vec = date.split('-').map(|s| s.parse().unwrap()).collect(); + (parts[0], parts[1], parts[2]) + } + + fn days_since_1970(y: i32, m: i32, d: i32) -> i32 { + let (mut y, mut m) = (y, m); + if m < 3 { + y -= 1; + m += 12; + } + 365 * y + y / 4 - y / 100 + y / 400 + (153 * m - 457) / 5 + d - 306 - 719468 + } +} diff --git a/tests/1001-1500/1360. number-of-days-between-two-dates/sol.swift b/tests/1001-1500/1360. number-of-days-between-two-dates/sol.swift new file mode 100644 index 00000000..76c3c030 --- /dev/null +++ b/tests/1001-1500/1360. number-of-days-between-two-dates/sol.swift @@ -0,0 +1,19 @@ +class Solution { + func daysBetweenDates(_ date1: String, _ date2: String) -> Int { + let parts1 = date1.split(separator: "-").compactMap { Int($0) } + let parts2 = date2.split(separator: "-").compactMap { Int($0) } + let (y1, m1, d1) = (parts1[0], parts1[1], parts1[2]) + let (y2, m2, d2) = (parts2[0], parts2[1], parts2[2]) + return abs(daysSince1970(y1, m1, d1) - daysSince1970(y2, m2, d2)) + } + + private func daysSince1970(_ y: Int, _ m: Int, _ d: Int) -> Int { + var year = y + var month = m + if month < 3 { + year -= 1 + month += 12 + } + return 365 * year + year / 4 - year / 100 + year / 400 + (153 * month - 457) / 5 + d - 306 - 719468 + } +} diff --git a/tests/1001-1500/1360. number-of-days-between-two-dates/sol.ts b/tests/1001-1500/1360. number-of-days-between-two-dates/sol.ts new file mode 100644 index 00000000..14ae3d7a --- /dev/null +++ b/tests/1001-1500/1360. number-of-days-between-two-dates/sol.ts @@ -0,0 +1,22 @@ +function daysBetweenDates(date1: string, date2: string): number { + const [y1, m1, d1] = date1.split("-").map(Number); + const [y2, m2, d2] = date2.split("-").map(Number); + return Math.abs(daysSince1970(y1, m1, d1) - daysSince1970(y2, m2, d2)); +} + +function daysSince1970(y: number, m: number, d: number): number { + if (m < 3) { + y--; + m += 12; + } + return ( + 365 * y + + Math.floor(y / 4) - + Math.floor(y / 100) + + Math.floor(y / 400) + + Math.floor((153 * m - 457) / 5) + + d - + 306 - + 719468 + ); +} diff --git a/tests/1001-1500/1361. validate-binary-tree-nodes/manifest.yaml b/tests/1001-1500/1361. validate-binary-tree-nodes/manifest.yaml new file mode 100644 index 00000000..25a29040 --- /dev/null +++ b/tests/1001-1500/1361. validate-binary-tree-nodes/manifest.yaml @@ -0,0 +1,562 @@ +entry: + id: 1361 + title: validate-binary-tree-nodes + params: + n: + type: int + leftChild: + type: array + items: + type: int + rightChild: + type: array + items: + type: int + call: + cpp: "Solution().validateBinaryTreeNodes({n}, {leftChild}, {rightChild})" + rust: "Solution::validate_binary_tree_nodes({n}, {leftChild}, {rightChild})" + python3: "Solution().validateBinaryTreeNodes({n}, {leftChild}, {rightChild})" + python2: "Solution().validateBinaryTreeNodes({n}, {leftChild}, {rightChild})" + ruby: "validate_binary_tree_nodes({n}, {leftChild}, {rightChild})" + java: "new Solution().validateBinaryTreeNodes({n}, {leftChild}, {rightChild})" + csharp: "new Solution().ValidateBinaryTreeNodes({n}, {leftChild}, {rightChild})" + kotlin: "Solution().validateBinaryTreeNodes({n}, {leftChild}, {rightChild})" + go: "validateBinaryTreeNodes({n}, {leftChild}, {rightChild})" + dart: "Solution().validateBinaryTreeNodes({n}, {leftChild}, {rightChild})" + swift: "Solution().validateBinaryTreeNodes({n}, {leftChild}, {rightChild})" + typescript: "validateBinaryTreeNodes({n}, {leftChild}, {rightChild})" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().validateBinaryTreeNodes(n, leftChild, rightChild, {result})" + checker: | + class Checker: + def validateBinaryTreeNodes(self, n, leftChild, rightChild, result): + if type(result) is not bool or n < 1 or len(leftChild) != n or len(rightChild) != n: + return False + parent_count = [0] * n + for node in range(n): + for child in (leftChild[node], rightChild[node]): + if child == -1: + continue + if child < 0 or child >= n: + return result is False + parent_count[child] += 1 + if parent_count[child] > 1: + return result is False + roots = [node for node, count in enumerate(parent_count) if count == 0] + if len(roots) != 1: + return result is False + seen = {roots[0]} + stack = [roots[0]] + while stack: + node = stack.pop() + for child in (leftChild[node], rightChild[node]): + if child != -1: + if child in seen: + return result is False + seen.add(child) + stack.append(child) + return result is (len(seen) == n) +seed: 1361 +tests: + - name: single-node + in: + n: 1 + leftChild: [-1] + rightChild: [-1] + - name: example-valid + in: + n: 4 + leftChild: [1, -1, 3, -1] + rightChild: [2, -1, -1, -1] + - name: example-duplicate-parent + in: + n: 4 + leftChild: [1, -1, 3, -1] + rightChild: [2, 3, -1, -1] + - name: example-cycle + in: + n: 2 + leftChild: [1, 0] + rightChild: [-1, -1] + - name: two-nodes-left + in: + n: 2 + leftChild: [1, -1] + rightChild: [-1, -1] + - name: two-nodes-right + in: + n: 2 + leftChild: [-1, -1] + rightChild: [1, -1] + - name: root-is-last-index + in: + n: 4 + leftChild: [-1, 2, -1, 1] + rightChild: [-1, -1, -1, 0] + - name: balanced-seven + in: + n: 7 + leftChild: [1, 3, 5, -1, -1, -1, -1] + rightChild: [2, 4, 6, -1, -1, -1, -1] + - name: left-chain-ten + in: + n: 10 + leftChild: [1, 2, 3, 4, 5, 6, 7, 8, 9, -1] + rightChild: [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1] + - name: right-chain-ten + in: + n: 10 + leftChild: [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1] + rightChild: [1, 2, 3, 4, 5, 6, 7, 8, 9, -1] + - name: zigzag-chain + in: + n: 9 + leftChild: [1, -1, 3, -1, 5, -1, 7, -1, -1] + rightChild: [-1, 2, -1, 4, -1, 6, -1, 8, -1] + - name: sparse-valid + in: + n: 8 + leftChild: [1, -1, 4, -1, -1, 6, -1, -1] + rightChild: [2, 3, 5, -1, -1, 7, -1, -1] + - name: duplicate-siblings + in: + n: 3 + leftChild: [1, -1, -1] + rightChild: [1, -1, -1] + - name: duplicate-across-parents + in: + n: 4 + leftChild: [1, 3, 3, -1] + rightChild: [2, -1, -1, -1] + - name: two-isolated-roots + in: + n: 2 + leftChild: [-1, -1] + rightChild: [-1, -1] + - name: forest-of-chains + in: + n: 6 + leftChild: [1, 2, -1, 4, 5, -1] + rightChild: [-1, -1, -1, -1, -1, -1] + - name: cycle-with-separate-root + in: + n: 4 + leftChild: [1, 2, 0, -1] + rightChild: [-1, -1, -1, -1] + - name: self-loop-with-root + in: + n: 3 + leftChild: [1, -1, 2] + rightChild: [-1, -1, -1] + - name: self-loop-only + in: + n: 1 + leftChild: [0] + rightChild: [-1] + - name: three-cycle + in: + n: 3 + leftChild: [1, 2, 0] + rightChild: [-1, -1, -1] + - name: cycle-after-root + in: + n: 5 + leftChild: [1, 2, 3, 1, -1] + rightChild: [-1, -1, -1, -1, -1] + - name: disconnected-cycle + in: + n: 5 + leftChild: [1, -1, 3, 2, -1] + rightChild: [-1, -1, -1, -1, -1] + - name: valid-uneven-five + in: + n: 5 + leftChild: [1, 2, -1, -1, -1] + rightChild: [4, 3, -1, -1, -1] + - name: valid-root-middle + in: + n: 6 + leftChild: [-1, -1, 0, 1, 2, 4] + rightChild: [-1, -1, -1, -1, 3, 5] + - name: shared-child-late + in: + n: 7 + leftChild: [1, 3, 5, -1, 6, 6, -1] + rightChild: [2, 4, -1, -1, -1, -1, -1] + - name: disconnected-leaf-pair + in: + n: 7 + leftChild: [1, 3, -1, -1, 5, -1, -1] + rightChild: [2, 4, -1, -1, 6, -1, -1] + - name: two-node-cycle-and-chain + in: + n: 6 + leftChild: [1, 0, 3, 4, 5, -1] + rightChild: [-1, -1, -1, -1, -1, -1] + - name: duplicate-right-then-left + in: + n: 5 + leftChild: [1, -1, 4, -1, -1] + rightChild: [2, 4, 3, -1, -1] + - name: valid-alternating-twelve + in: + n: 12 + leftChild: [1, -1, 3, -1, 5, -1, 7, -1, 9, -1, 11, -1] + rightChild: [-1, 2, -1, 4, -1, 6, -1, 8, -1, 10, -1, -1] + - name: deep-cycle-with-unique-root + in: + n: 8 + leftChild: [1, 2, 3, 4, 5, 6, 3, -1] + rightChild: [-1, -1, -1, -1, -1, -1, -1, -1] + - name: large-valid-left-chain + in: + n: 50 + leftChild: + [ + 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, + -1, + ] + rightChild: + [ + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -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: large-valid-right-chain + in: + n: 50 + leftChild: + [ + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + ] + rightChild: + [ + 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, + -1, + ] + - name: large-cycle-with-root + in: + n: 20 + leftChild: + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 10] + rightChild: + [ + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + ] + - name: valid-root-high-index + in: + n: 8 + leftChild: [-1, -1, 0, 1, 2, 3, 4, 5] + rightChild: [-1, -1, -1, -1, -1, -1, -1, 6] + - name: duplicated-parent-in-component + in: + n: 8 + leftChild: [1, 3, 5, -1, 7, 7, -1, -1] + rightChild: [2, 4, 6, -1, -1, -1, -1, -1] + - name: generated-large-random-1 + seed: 136101 + in: + n: 10000 + leftChild: + gen: "array" + len: 10000 + of: + gen: "int" + min: -1 + max: 9999 + rightChild: + gen: "array" + len: 10000 + of: + gen: "int" + min: -1 + max: 9999 + - name: generated-large-random-2 + seed: 136102 + in: + n: 10000 + leftChild: + gen: "array" + len: 10000 + of: + gen: "int" + min: -1 + max: 9999 + rightChild: + gen: "array" + len: 10000 + of: + gen: "int" + min: -1 + max: 9999 + - name: generated-large-random-3 + seed: 136103 + in: + n: 10000 + leftChild: + gen: "array" + len: 10000 + of: + gen: "int" + min: -1 + max: 9999 + rightChild: + gen: "array" + len: 10000 + of: + gen: "int" + min: -1 + max: 9999 + - name: generated-large-random-4 + seed: 136104 + in: + n: 10000 + leftChild: + gen: "array" + len: 10000 + of: + gen: "int" + min: -1 + max: 9999 + rightChild: + gen: "array" + len: 10000 + of: + gen: "int" + min: -1 + max: 9999 + - name: generated-large-random-5 + seed: 136105 + in: + n: 10000 + leftChild: + gen: "array" + len: 10000 + of: + gen: "int" + min: -1 + max: 9999 + rightChild: + gen: "array" + len: 10000 + of: + gen: "int" + min: -1 + max: 9999 diff --git a/tests/1001-1500/1361. validate-binary-tree-nodes/sol.cpp b/tests/1001-1500/1361. validate-binary-tree-nodes/sol.cpp new file mode 100644 index 00000000..8d9d00b5 --- /dev/null +++ b/tests/1001-1500/1361. validate-binary-tree-nodes/sol.cpp @@ -0,0 +1,43 @@ +class Solution { +public: + bool validateBinaryTreeNodes(int n, vector& leftChild, vector& rightChild) { + vector inDegree(n, 0); + for (int i = 0; i < n; i++) { + for (int child : {leftChild[i], rightChild[i]}) { + if (child != -1) { + if (child < 0 || child >= n) return false; + inDegree[child]++; + if (inDegree[child] > 1) return false; + } + } + } + + int root = -1; + for (int i = 0; i < n; i++) { + if (inDegree[i] == 0) { + if (root != -1) return false; + root = i; + } + } + if (root == -1) return false; + + queue q; + vector visited(n, false); + q.push(root); + visited[root] = true; + int count = 1; + + while (!q.empty()) { + int node = q.front(); + q.pop(); + for (int child : {leftChild[node], rightChild[node]}) { + if (child == -1) continue; + if (visited[child]) return false; + visited[child] = true; + count++; + q.push(child); + } + } + return count == n; + } +}; diff --git a/tests/1001-1500/1361. validate-binary-tree-nodes/sol.cs b/tests/1001-1500/1361. validate-binary-tree-nodes/sol.cs new file mode 100644 index 00000000..8a9cd475 --- /dev/null +++ b/tests/1001-1500/1361. validate-binary-tree-nodes/sol.cs @@ -0,0 +1,41 @@ +public class Solution { + public bool ValidateBinaryTreeNodes(int n, int[] leftChild, int[] rightChild) { + int[] inDegree = new int[n]; + for (int i = 0; i < n; i++) { + foreach (int child in new int[] { leftChild[i], rightChild[i] }) { + if (child != -1) { + if (child < 0 || child >= n) return false; + inDegree[child]++; + if (inDegree[child] > 1) return false; + } + } + } + + int root = -1; + for (int i = 0; i < n; i++) { + if (inDegree[i] == 0) { + if (root != -1) return false; + root = i; + } + } + if (root == -1) return false; + + Queue queue = new Queue(); + bool[] visited = new bool[n]; + queue.Enqueue(root); + visited[root] = true; + int count = 1; + + while (queue.Count > 0) { + int node = queue.Dequeue(); + foreach (int child in new int[] { leftChild[node], rightChild[node] }) { + if (child == -1) continue; + if (visited[child]) return false; + visited[child] = true; + count++; + queue.Enqueue(child); + } + } + return count == n; + } +} diff --git a/tests/1001-1500/1361. validate-binary-tree-nodes/sol.dart b/tests/1001-1500/1361. validate-binary-tree-nodes/sol.dart new file mode 100644 index 00000000..2722869e --- /dev/null +++ b/tests/1001-1500/1361. validate-binary-tree-nodes/sol.dart @@ -0,0 +1,40 @@ +class Solution { + bool validateBinaryTreeNodes(int n, List leftChild, List rightChild) { + List inDegree = List.filled(n, 0); + for (int i = 0; i < n; i++) { + for (int child in [leftChild[i], rightChild[i]]) { + if (child != -1) { + if (child < 0 || child >= n) return false; + inDegree[child]++; + if (inDegree[child] > 1) return false; + } + } + } + + int root = -1; + for (int i = 0; i < n; i++) { + if (inDegree[i] == 0) { + if (root != -1) return false; + root = i; + } + } + if (root == -1) return false; + + var queue = [root]; + List visited = List.filled(n, false); + visited[root] = true; + int count = 1; + + while (queue.isNotEmpty) { + int node = queue.removeAt(0); + for (int child in [leftChild[node], rightChild[node]]) { + if (child == -1) continue; + if (visited[child]) return false; + visited[child] = true; + count++; + queue.add(child); + } + } + return count == n; + } +} diff --git a/tests/1001-1500/1361. validate-binary-tree-nodes/sol.go b/tests/1001-1500/1361. validate-binary-tree-nodes/sol.go new file mode 100644 index 00000000..4a8137cd --- /dev/null +++ b/tests/1001-1500/1361. validate-binary-tree-nodes/sol.go @@ -0,0 +1,51 @@ +func validateBinaryTreeNodes(n int, leftChild []int, rightChild []int) bool { + inDegree := make([]int, n) + for i := 0; i < n; i++ { + for _, child := range []int{leftChild[i], rightChild[i]} { + if child != -1 { + if child < 0 || child >= n { + return false + } + inDegree[child]++ + if inDegree[child] > 1 { + return false + } + } + } + } + + root := -1 + for i, x := range inDegree { + if x == 0 { + if root != -1 { + return false + } + root = i + } + } + if root == -1 { + return false + } + + queue := []int{root} + visited := make([]bool, n) + visited[root] = true + count := 1 + + for len(queue) > 0 { + node := queue[0] + queue = queue[1:] + for _, child := range []int{leftChild[node], rightChild[node]} { + if child == -1 { + continue + } + if visited[child] { + return false + } + visited[child] = true + count++ + queue = append(queue, child) + } + } + return count == n +} diff --git a/tests/1001-1500/1361. validate-binary-tree-nodes/sol.java b/tests/1001-1500/1361. validate-binary-tree-nodes/sol.java new file mode 100644 index 00000000..c0ba7a69 --- /dev/null +++ b/tests/1001-1500/1361. validate-binary-tree-nodes/sol.java @@ -0,0 +1,43 @@ +class Solution { + public boolean validateBinaryTreeNodes(int n, int[] leftChild, int[] rightChild) { + int[] inDegree = new int[n]; + for (int i = 0; i < n; i++) { + int[] children = {leftChild[i], rightChild[i]}; + for (int child : children) { + if (child != -1) { + if (child < 0 || child >= n) return false; + inDegree[child]++; + if (inDegree[child] > 1) return false; + } + } + } + + int root = -1; + for (int i = 0; i < n; i++) { + if (inDegree[i] == 0) { + if (root != -1) return false; + root = i; + } + } + if (root == -1) return false; + + java.util.Queue queue = new java.util.LinkedList<>(); + boolean[] visited = new boolean[n]; + queue.offer(root); + visited[root] = true; + int count = 1; + + while (!queue.isEmpty()) { + int node = queue.poll(); + int[] children = {leftChild[node], rightChild[node]}; + for (int child : children) { + if (child == -1) continue; + if (visited[child]) return false; + visited[child] = true; + count++; + queue.offer(child); + } + } + return count == n; + } +} diff --git a/tests/1001-1500/1361. validate-binary-tree-nodes/sol.kt b/tests/1001-1500/1361. validate-binary-tree-nodes/sol.kt new file mode 100644 index 00000000..79a21e89 --- /dev/null +++ b/tests/1001-1500/1361. validate-binary-tree-nodes/sol.kt @@ -0,0 +1,41 @@ +class Solution { + fun validateBinaryTreeNodes(n: Int, leftChild: IntArray, rightChild: IntArray): Boolean { + val inDegree = IntArray(n) + for (i in 0 until n) { + for (child in intArrayOf(leftChild[i], rightChild[i])) { + if (child != -1) { + if (child < 0 || child >= n) return false + inDegree[child]++ + if (inDegree[child] > 1) return false + } + } + } + + var root = -1 + for (i in 0 until n) { + if (inDegree[i] == 0) { + if (root != -1) return false + root = i + } + } + if (root == -1) return false + + val queue: java.util.Queue = java.util.LinkedList() + val visited = BooleanArray(n) + queue.offer(root) + visited[root] = true + var count = 1 + + while (queue.isNotEmpty()) { + val node = queue.poll() + for (child in intArrayOf(leftChild[node], rightChild[node])) { + if (child == -1) continue + if (visited[child]) return false + visited[child] = true + count++ + queue.offer(child) + } + } + return count == n + } +} diff --git a/tests/1001-1500/1361. validate-binary-tree-nodes/sol.py b/tests/1001-1500/1361. validate-binary-tree-nodes/sol.py new file mode 100644 index 00000000..084ba811 --- /dev/null +++ b/tests/1001-1500/1361. validate-binary-tree-nodes/sol.py @@ -0,0 +1,40 @@ +from collections import deque +from typing import List + + +class Solution: + def validateBinaryTreeNodes( + self, n: int, leftChild: list[int], rightChild: list[int] + ) -> bool: + in_degree = [0] * n + for i in range(n): + for child in (leftChild[i], rightChild[i]): + if child != -1: + if child < 0 or child >= n: + return False + in_degree[child] += 1 + if in_degree[child] > 1: + return False + + root = -1 + for i, x in enumerate(in_degree): + if x == 0: + if root != -1: + return False + root = i + if root == -1: + return False + + queue = deque([root]) + visited = {root} + + while queue: + node = queue.popleft() + for child in [leftChild[node], rightChild[node]]: + if child == -1: + continue + if child in visited: + return False + visited.add(child) + queue.append(child) + return len(visited) == n diff --git a/tests/1001-1500/1361. validate-binary-tree-nodes/sol.py2 b/tests/1001-1500/1361. validate-binary-tree-nodes/sol.py2 new file mode 100644 index 00000000..6c070209 --- /dev/null +++ b/tests/1001-1500/1361. validate-binary-tree-nodes/sol.py2 @@ -0,0 +1,40 @@ +class Solution(object): + def validateBinaryTreeNodes(self, n, leftChild, rightChild): + """ + :type n: int + :type leftChild: List[int] + :type rightChild: List[int] + :rtype: bool + """ + in_degree = [0] * n + for i in range(n): + for child in (leftChild[i], rightChild[i]): + if child != -1: + if child < 0 or child >= n: + return False + in_degree[child] += 1 + if in_degree[child] > 1: + return False + + root = -1 + for i, x in enumerate(in_degree): + if x == 0: + if root != -1: + return False + root = i + if root == -1: + return False + + queue = [root] + visited = {root} + + while queue: + node = queue.pop(0) + for child in (leftChild[node], rightChild[node]): + if child == -1: + continue + if child in visited: + return False + visited.add(child) + queue.append(child) + return len(visited) == n diff --git a/tests/1001-1500/1361. validate-binary-tree-nodes/sol.rb b/tests/1001-1500/1361. validate-binary-tree-nodes/sol.rb new file mode 100644 index 00000000..61c05096 --- /dev/null +++ b/tests/1001-1500/1361. validate-binary-tree-nodes/sol.rb @@ -0,0 +1,39 @@ +# @param {Integer} n +# @param {Integer[]} left_child +# @param {Integer[]} right_child +# @return {Boolean} +def validate_binary_tree_nodes(n, left_child, right_child) + in_degree = Array.new(n, 0) + (0...n).each do |i| + [left_child[i], right_child[i]].each do |child| + if child != -1 + return false if child < 0 || child >= n + in_degree[child] += 1 + return false if in_degree[child] > 1 + end + end + end + + root = -1 + in_degree.each_with_index do |x, i| + if x == 0 + return false if root != -1 + root = i + end + end + return false if root == -1 + + queue = [root] + visited = {root => true} + + until queue.empty? + node = queue.shift + [left_child[node], right_child[node]].each do |child| + next if child == -1 + return false if visited[child] + visited[child] = true + queue.push(child) + end + end + visited.size == n +end diff --git a/tests/1001-1500/1361. validate-binary-tree-nodes/sol.rs b/tests/1001-1500/1361. validate-binary-tree-nodes/sol.rs new file mode 100644 index 00000000..3fe83dfd --- /dev/null +++ b/tests/1001-1500/1361. validate-binary-tree-nodes/sol.rs @@ -0,0 +1,56 @@ +impl Solution { + pub fn validate_binary_tree_nodes(n: i32, left_child: Vec, right_child: Vec) -> bool { + let n = n as usize; + let mut in_degree = vec![0; n]; + for i in 0..n { + for &child in &[left_child[i], right_child[i]] { + if child != -1 { + let c = child as usize; + if c >= n { + return false; + } + in_degree[c] += 1; + if in_degree[c] > 1 { + return false; + } + } + } + } + + let mut root = None; + for i in 0..n { + if in_degree[i] == 0 { + if root.is_some() { + return false; + } + root = Some(i); + } + } + let root = match root { + Some(r) => r, + None => return false, + }; + + let mut queue = std::collections::VecDeque::new(); + let mut visited = vec![false; n]; + queue.push_back(root); + visited[root] = true; + let mut count = 1; + + while let Some(node) = queue.pop_front() { + for &child in &[left_child[node], right_child[node]] { + if child == -1 { + continue; + } + let c = child as usize; + if visited[c] { + return false; + } + visited[c] = true; + count += 1; + queue.push_back(c); + } + } + count == n + } +} diff --git a/tests/1001-1500/1361. validate-binary-tree-nodes/sol.swift b/tests/1001-1500/1361. validate-binary-tree-nodes/sol.swift new file mode 100644 index 00000000..3c7d0481 --- /dev/null +++ b/tests/1001-1500/1361. validate-binary-tree-nodes/sol.swift @@ -0,0 +1,40 @@ +class Solution { + func validateBinaryTreeNodes(_ n: Int, _ leftChild: [Int], _ rightChild: [Int]) -> Bool { + var inDegree = [Int](repeating: 0, count: n) + for i in 0..= n { return false } + inDegree[child] += 1 + if inDegree[child] > 1 { return false } + } + } + } + + var root = -1 + for i in 0..= n) return false; + inDegree[child]++; + if (inDegree[child] > 1) return false; + } + } + } + + let root = -1; + for (let i = 0; i < n; i++) { + if (inDegree[i] === 0) { + if (root !== -1) return false; + root = i; + } + } + if (root === -1) return false; + + const queue: number[] = [root]; + const visited: boolean[] = new Array(n).fill(false); + visited[root] = true; + let count = 1; + + while (queue.length > 0) { + const node = queue.shift()!; + for (const child of [leftChild[node], rightChild[node]]) { + if (child === -1) continue; + if (visited[child]) return false; + visited[child] = true; + count++; + queue.push(child); + } + } + return count === n; +} diff --git a/tests/1001-1500/1362. closest-divisors/manifest.yaml b/tests/1001-1500/1362. closest-divisors/manifest.yaml new file mode 100644 index 00000000..732e6d43 --- /dev/null +++ b/tests/1001-1500/1362. closest-divisors/manifest.yaml @@ -0,0 +1,192 @@ +entry: + id: 1362 + title: closest-divisors + params: + num: + type: int + call: + cpp: "Solution().closestDivisors({num})" + rust: "Solution::closest_divisors({num})" + python3: "Solution().closestDivisors({num})" + python2: "Solution().closestDivisors({num})" + ruby: "closest_divisors({num})" + java: "new Solution().closestDivisors({num})" + csharp: "new Solution().ClosestDivisors({num})" + kotlin: "Solution().closestDivisors({num})" + go: "closestDivisors({num})" + dart: "Solution().closestDivisors({num})" + swift: "Solution().closestDivisors({num})" + typescript: "closestDivisors({num})" +judge: + type: "exact" +limits: + time_ms: 1000 + memory_mb: 256 +oracle: + python3: + call: "Checker().closestDivisors(num, {result})" + checker: | + from math import isqrt + + class Checker: + def closestDivisors(self, num, result): + if not isinstance(num, int) or isinstance(num, bool) or not 1 <= num <= 1000000000: + return False + if not isinstance(result, list) or len(result) != 2: + return False + a, b = result + if not all(isinstance(value, int) and not isinstance(value, bool) and value > 0 for value in result): + return False + if a * b not in (num + 1, num + 2): + return False + best_difference = None + for candidate in (num + 1, num + 2): + for d in range(isqrt(candidate), 0, -1): + if candidate % d == 0: + difference = candidate // d - d + if best_difference is None or difference < best_difference: + best_difference = difference + break + return abs(a - b) == best_difference +seed: 1362 +tests: + - name: num_one + in: + num: 1 + - name: num_two + in: + num: 2 + - name: num_three + in: + num: 3 + - name: num_four + in: + num: 4 + - name: num_five + in: + num: 5 + - name: num_six + in: + num: 6 + - name: num_seven + in: + num: 7 + - name: example_one_num_eight + in: + num: 8 + - name: num_nine + in: + num: 9 + - name: num_ten + in: + num: 10 + - name: near_square_24 + in: + num: 24 + - name: near_square_35 + in: + num: 35 + - name: near_square_48 + in: + num: 48 + - name: example_two_num_123 + in: + num: 123 + - name: example_three_num_999 + in: + num: 999 + - name: prime_adjacent + in: + num: 100 + - name: power_of_ten + in: + num: 1000 + - name: square_boundary + in: + num: 9998 + - name: square_plus_one + in: + num: 9999 + - name: square_plus_two + in: + num: 10000 + - name: medium_12345 + in: + num: 12345 + - name: medium_54321 + in: + num: 54321 + - name: medium_99999 + in: + num: 99999 + - name: large_million + in: + num: 1000000 + - name: large_prime_like + in: + num: 999983 + - name: large_1234567 + in: + num: 1234567 + - name: large_50000000 + in: + num: 50000000 + - name: large_99999999 + in: + num: 99999999 + - name: maximum_minus_two + in: + num: 999999998 + - name: maximum_minus_one + in: + num: 999999999 + - name: maximum_value + in: + num: 1000000000 + - name: one_below_large_square + in: + num: 998001998 + - name: large_square_minus_one + in: + num: 999950883 + - name: large_square_exact_offset + in: + num: 999950884 + - name: near_maximum_even + in: + num: 999999996 + - name: generated_small + seed: 101 + in: + num: + gen: "int" + min: 1 + max: 1000 + - name: generated_medium + seed: 202 + in: + num: + gen: "int" + min: 1001 + max: 1000000 + - name: generated_large + seed: 303 + in: + num: + gen: "int" + min: 1000001 + max: 100000000 + - name: generated_upper + seed: 404 + in: + num: + gen: "int" + min: 100000001 + max: 999999999 + - name: generated_full_range + seed: 505 + in: + num: + gen: "int" + min: 1 + max: 1000000000 diff --git a/tests/1001-1500/1362. closest-divisors/sol.cpp b/tests/1001-1500/1362. closest-divisors/sol.cpp new file mode 100644 index 00000000..05272ca3 --- /dev/null +++ b/tests/1001-1500/1362. closest-divisors/sol.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + vector closestDivisors(int num) { + int start = sqrt(num + 2); + for (int d = start; d >= 1; d--) { + if ((num + 1) % d == 0) { + return {d, (num + 1) / d}; + } + if ((num + 2) % d == 0) { + return {d, (num + 2) / d}; + } + } + return {}; + } +}; diff --git a/tests/1001-1500/1362. closest-divisors/sol.cs b/tests/1001-1500/1362. closest-divisors/sol.cs new file mode 100644 index 00000000..f82e49f2 --- /dev/null +++ b/tests/1001-1500/1362. closest-divisors/sol.cs @@ -0,0 +1,14 @@ +public class Solution { + public int[] ClosestDivisors(int num) { + int start = (int)Math.Sqrt(num + 2); + for (int d = start; d >= 1; d--) { + if ((num + 1) % d == 0) { + return new int[]{d, (num + 1) / d}; + } + if ((num + 2) % d == 0) { + return new int[]{d, (num + 2) / d}; + } + } + return new int[0]; + } +} diff --git a/tests/1001-1500/1362. closest-divisors/sol.dart b/tests/1001-1500/1362. closest-divisors/sol.dart new file mode 100644 index 00000000..c717c523 --- /dev/null +++ b/tests/1001-1500/1362. closest-divisors/sol.dart @@ -0,0 +1,16 @@ +import 'dart:math' as math; + +class Solution { + List closestDivisors(int num) { + int start = math.sqrt(num + 2).toInt(); + for (int d = start; d >= 1; d--) { + if ((num + 1) % d == 0) { + return [d, (num + 1) ~/ d]; + } + if ((num + 2) % d == 0) { + return [d, (num + 2) ~/ d]; + } + } + return []; + } +} diff --git a/tests/1001-1500/1362. closest-divisors/sol.go b/tests/1001-1500/1362. closest-divisors/sol.go new file mode 100644 index 00000000..1c9bf193 --- /dev/null +++ b/tests/1001-1500/1362. closest-divisors/sol.go @@ -0,0 +1,12 @@ +func closestDivisors(num int) []int { + start := int(math.Sqrt(float64(num + 2))) + for d := start; d >= 1; d-- { + if (num + 1) % d == 0 { + return []int{d, (num + 1) / d} + } + if (num + 2) % d == 0 { + return []int{d, (num + 2) / d} + } + } + return []int{} +} diff --git a/tests/1001-1500/1362. closest-divisors/sol.java b/tests/1001-1500/1362. closest-divisors/sol.java new file mode 100644 index 00000000..e0422d31 --- /dev/null +++ b/tests/1001-1500/1362. closest-divisors/sol.java @@ -0,0 +1,14 @@ +class Solution { + public int[] closestDivisors(int num) { + int start = (int) Math.sqrt(num + 2); + for (int d = start; d >= 1; d--) { + if ((num + 1) % d == 0) { + return new int[]{d, (num + 1) / d}; + } + if ((num + 2) % d == 0) { + return new int[]{d, (num + 2) / d}; + } + } + return new int[0]; + } +} diff --git a/tests/1001-1500/1362. closest-divisors/sol.kt b/tests/1001-1500/1362. closest-divisors/sol.kt new file mode 100644 index 00000000..12b3f0ee --- /dev/null +++ b/tests/1001-1500/1362. closest-divisors/sol.kt @@ -0,0 +1,14 @@ +class Solution { + fun closestDivisors(num: Int): IntArray { + val start = Math.sqrt((num + 2).toDouble()).toInt() + for (d in start downTo 1) { + if ((num + 1) % d == 0) { + return intArrayOf(d, (num + 1) / d) + } + if ((num + 2) % d == 0) { + return intArrayOf(d, (num + 2) / d) + } + } + return intArrayOf() + } +} diff --git a/tests/1001-1500/1362. closest-divisors/sol.py b/tests/1001-1500/1362. closest-divisors/sol.py new file mode 100644 index 00000000..8127f7af --- /dev/null +++ b/tests/1001-1500/1362. closest-divisors/sol.py @@ -0,0 +1,22 @@ +import math +from typing import List + + +class Solution: + def closestDivisors(self, num: int) -> List[int]: + # Start from the largest possible 'balanced' divisor + # This is the integer square root of the largest target (num + 2) + start = int(math.isqrt(num + 2)) + + # Iterating downwards ensures the first divisor found has the + # minimal absolute difference (Mathematical Optimization) + for d in range(start, 0, -1): + # Check for divisors of (num + 1) + if (num + 1) % d == 0: + return [d, (num + 1) // d] + + # Check for divisors of (num + 2) + if (num + 2) % d == 0: + return [d, (num + 2) // d] + + return [] diff --git a/tests/1001-1500/1362. closest-divisors/sol.py2 b/tests/1001-1500/1362. closest-divisors/sol.py2 new file mode 100644 index 00000000..38718db8 --- /dev/null +++ b/tests/1001-1500/1362. closest-divisors/sol.py2 @@ -0,0 +1,14 @@ +class Solution(object): + def closestDivisors(self, num): + """ + :type num: int + :rtype: List[int] + """ + import math + start = int(math.sqrt(num + 2)) + for d in range(start, 0, -1): + if (num + 1) % d == 0: + return [d, (num + 1) // d] + if (num + 2) % d == 0: + return [d, (num + 2) // d] + return [] diff --git a/tests/1001-1500/1362. closest-divisors/sol.rb b/tests/1001-1500/1362. closest-divisors/sol.rb new file mode 100644 index 00000000..350dda85 --- /dev/null +++ b/tests/1001-1500/1362. closest-divisors/sol.rb @@ -0,0 +1,14 @@ +# @param {Integer} num +# @return {Integer[]} +def closest_divisors(num) + start = Integer.sqrt(num + 2) + start.downto(1) do |d| + if (num + 1) % d == 0 + return [d, (num + 1) / d] + end + if (num + 2) % d == 0 + return [d, (num + 2) / d] + end + end + [] +end diff --git a/tests/1001-1500/1362. closest-divisors/sol.rs b/tests/1001-1500/1362. closest-divisors/sol.rs new file mode 100644 index 00000000..a0ced6cd --- /dev/null +++ b/tests/1001-1500/1362. closest-divisors/sol.rs @@ -0,0 +1,14 @@ +impl Solution { + pub fn closest_divisors(num: i32) -> Vec { + let start = ((num + 2) as f64).sqrt() as i32; + for d in (1..=start).rev() { + if (num + 1) % d == 0 { + return vec![d, (num + 1) / d]; + } + if (num + 2) % d == 0 { + return vec![d, (num + 2) / d]; + } + } + vec![] + } +} diff --git a/tests/1001-1500/1362. closest-divisors/sol.swift b/tests/1001-1500/1362. closest-divisors/sol.swift new file mode 100644 index 00000000..de2ff716 --- /dev/null +++ b/tests/1001-1500/1362. closest-divisors/sol.swift @@ -0,0 +1,14 @@ +class Solution { + func closestDivisors(_ num: Int) -> [Int] { + let start = Int(Double(num + 2).squareRoot()) + for d in stride(from: start, through: 1, by: -1) { + if (num + 1) % d == 0 { + return [d, (num + 1) / d] + } + if (num + 2) % d == 0 { + return [d, (num + 2) / d] + } + } + return [] + } +} diff --git a/tests/1001-1500/1362. closest-divisors/sol.ts b/tests/1001-1500/1362. closest-divisors/sol.ts new file mode 100644 index 00000000..540b180c --- /dev/null +++ b/tests/1001-1500/1362. closest-divisors/sol.ts @@ -0,0 +1,12 @@ +function closestDivisors(num: number): number[] { + const start = Math.floor(Math.sqrt(num + 2)); + for (let d = start; d >= 1; d--) { + if ((num + 1) % d === 0) { + return [d, Math.floor((num + 1) / d)]; + } + if ((num + 2) % d === 0) { + return [d, Math.floor((num + 2) / d)]; + } + } + return []; +} diff --git a/tests/1001-1500/1363. largest-multiple-of-three/manifest.yaml b/tests/1001-1500/1363. largest-multiple-of-three/manifest.yaml new file mode 100644 index 00000000..63fb10d0 --- /dev/null +++ b/tests/1001-1500/1363. largest-multiple-of-three/manifest.yaml @@ -0,0 +1,239 @@ +entry: + id: 1363 + title: "largest-multiple-of-three" + params: + digits: + type: array + items: + type: int + call: + cpp: "Solution().largestMultipleOfThree({digits})" + rust: "Solution::largest_multiple_of_three({digits})" + python3: "Solution().largestMultipleOfThree({digits})" + python2: "Solution().largestMultipleOfThree({digits})" + ruby: "largest_multiple_of_three({digits})" + java: "new Solution().largestMultipleOfThree({digits})" + csharp: "new Solution().LargestMultipleOfThree({digits})" + kotlin: "Solution().largestMultipleOfThree({digits})" + go: "largestMultipleOfThree({digits})" + dart: "Solution().largestMultipleOfThree({digits})" + swift: "Solution().largestMultipleOfThree({digits})" + typescript: "largestMultipleOfThree({digits})" +judge: + type: exact +limits: + time_ms: 800 + memory_mb: 300 +oracle: + python3: + call: "Checker().largestMultipleOfThree(digits, {result})" + checker: | + class Checker: + def largestMultipleOfThree(self, digits, result): + if not isinstance(result, str): + return False + if result != '0' and result.startswith('0'): + return False + if any(char < '0' or char > '9' for char in result): + return False + available = [0] * 10 + used = [0] * 10 + for digit in digits: + available[digit] += 1 + for char in result: + used[ord(char) - ord('0')] += 1 + if any(used[digit] > available[digit] for digit in range(10)): + return False + if sum(digit * used[digit] for digit in range(10)) % 3 != 0: + return False + + counts = available[:] + remainder = sum(digit * counts[digit] for digit in range(10)) % 3 + def remove(group, amount): + for digit in group: + take = min(amount, counts[digit]) + counts[digit] -= take + amount -= take + return amount == 0 + if remainder == 1: + if not remove((1, 4, 7), 1): + remove((2, 5, 8), 2) + elif remainder == 2: + if not remove((2, 5, 8), 1): + remove((1, 4, 7), 2) + expected = ''.join(str(digit) * counts[digit] for digit in range(9, -1, -1)) + if expected.startswith('0'): + expected = '0' + return result == expected +seed: 1363 +tests: + - name: example_1 + in: + digits: [8, 1, 9] + - name: example_2 + in: + digits: [8, 6, 7, 1, 0] + - name: example_3 + in: + digits: [1] + - name: single_zero + in: + digits: [0] + - name: all_zeros + in: + digits: [0, 0, 0, 0] + - name: single_divisible_digit + in: + digits: [9] + - name: single_remainder_two + in: + digits: [8] + - name: only_two_remainder_one_digits + in: + digits: [1, 4] + - name: only_three_remainder_one_digits + in: + digits: [1, 4, 7] + - name: only_three_remainder_two_digits + in: + digits: [2, 5, 8] + - name: remove_smallest_remainder_one + in: + digits: [9, 8, 4, 1] + - name: remove_smallest_remainder_two + in: + digits: [9, 7, 5, 2] + - name: remove_two_remainder_two_digits + in: + digits: [8, 5, 9] + - name: remove_two_remainder_one_digits + in: + digits: [7, 4, 9] + - name: preserve_zero_suffix + in: + digits: [0, 0, 1, 2, 8] + - name: zero_after_removal + in: + digits: [0, 1] + - name: high_digits_need_low_removal + in: + digits: [9, 9, 8, 8, 1] + - name: prefer_one_over_two_removals + in: + digits: [8, 5, 4, 1, 0] + - name: prefer_one_remainder_two_removal + in: + digits: [8, 7, 4, 2, 0] + - name: all_digit_kinds + in: + digits: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + - name: descending_with_duplicate_high + in: + digits: [9, 9, 8, 8, 7, 7, 6, 5, 4, 3, 2, 1, 0] + - name: repeated_mixed_remainder + in: + digits: [1, 1, 1, 2, 2, 2, 4, 4, 5, 5, 8, 8] + - name: divisible_digits_only + in: + digits: [3, 6, 9, 0, 3, 6, 9, 0] + - name: remove_middle_remainder_one + in: + digits: [9, 8, 7, 6, 5, 4, 3] + - name: remove_middle_remainder_two + in: + digits: [8, 7, 6, 5, 4, 3, 2] + - name: many_low_digits + in: + digits: [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3] + - name: repeated_nines_and_ones + in: + digits: [9, 9, 9, 1, 1, 1, 1] + - name: repeated_eights_and_twos + in: + digits: [8, 8, 8, 2, 2, 2, 2] + - name: no_divisible_subset + in: + digits: [1, 1, 2] + - name: smallest_nonempty_after_removal + in: + digits: [2, 2] + - name: zero_and_two_remainder_classes + in: + digits: [0, 2, 2, 5] + - name: long_static_balanced + in: + digits: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] + - name: long_static_remove_two + in: + digits: [9, 9, 8, 8, 8, 7, 7, 5, 5, 4, 4, 2, 2, 1, 0] + - name: only_zero_and_one + in: + digits: [0, 0, 1, 1] + - name: only_zero_and_two + in: + digits: [0, 0, 2, 2] + - name: generated_small + seed: 1364 + in: + digits: + gen: "array" + len: 25 + of: + gen: "int" + min: 0 + max: 9 + distinct: false + sorted: false + elemType: "int" + - name: generated_medium + seed: 1365 + in: + digits: + gen: "array" + len: 250 + of: + gen: "int" + min: 0 + max: 9 + distinct: false + sorted: false + elemType: "int" + - name: generated_large_random + seed: 1366 + in: + digits: + gen: "array" + len: 5000 + of: + gen: "int" + min: 0 + max: 9 + distinct: false + sorted: false + elemType: "int" + - name: generated_maximum_random + seed: 1367 + in: + digits: + gen: "array" + len: 10000 + of: + gen: "int" + min: 0 + max: 9 + distinct: false + sorted: false + elemType: "int" + - name: generated_maximum_nonzero + seed: 1368 + in: + digits: + gen: "array" + len: 10000 + of: + gen: "int" + min: 1 + max: 9 + distinct: false + sorted: false + elemType: "int" diff --git a/tests/1001-1500/1363. largest-multiple-of-three/sol.cpp b/tests/1001-1500/1363. largest-multiple-of-three/sol.cpp new file mode 100644 index 00000000..d092c688 --- /dev/null +++ b/tests/1001-1500/1363. largest-multiple-of-three/sol.cpp @@ -0,0 +1,41 @@ +class Solution { +public: + string largestMultipleOfThree(vector& digits) { + vector counts(10, 0); + for (int digit : digits) { + counts[digit]++; + } + + int sum = 0; + for (int i = 0; i < 10; i++) { + sum += i * counts[i]; + } + int remainder = sum % 3; + + auto removeSmallest = [&](vector group, int amount) -> bool { + for (int digit : group) { + while (amount > 0 && counts[digit] > 0) { + counts[digit]--; + amount--; + } + } + return amount == 0; + }; + + if (remainder == 1) { + if (!removeSmallest({1, 4, 7}, 1)) { + removeSmallest({2, 5, 8}, 2); + } + } else if (remainder == 2) { + if (!removeSmallest({2, 5, 8}, 1)) { + removeSmallest({1, 4, 7}, 2); + } + } + + string result; + for (int i = 9; i >= 0; i--) { + result.append(counts[i], '0' + i); + } + return result.size() > 0 && result[0] == '0' ? "0" : result; + } +}; diff --git a/tests/1001-1500/1363. largest-multiple-of-three/sol.cs b/tests/1001-1500/1363. largest-multiple-of-three/sol.cs new file mode 100644 index 00000000..331719ac --- /dev/null +++ b/tests/1001-1500/1363. largest-multiple-of-three/sol.cs @@ -0,0 +1,41 @@ +public class Solution { + public string LargestMultipleOfThree(int[] digits) { + int[] counts = new int[10]; + foreach (int digit in digits) { + counts[digit]++; + } + + int sum = 0; + for (int i = 0; i < 10; i++) { + sum += i * counts[i]; + } + int remainder = sum % 3; + + bool RemoveSmallest(int[] group, int amount) { + foreach (int digit in group) { + while (amount > 0 && counts[digit] > 0) { + counts[digit]--; + amount--; + } + } + return amount == 0; + } + + if (remainder == 1) { + if (!RemoveSmallest(new int[] {1, 4, 7}, 1)) { + RemoveSmallest(new int[] {2, 5, 8}, 2); + } + } else if (remainder == 2) { + if (!RemoveSmallest(new int[] {2, 5, 8}, 1)) { + RemoveSmallest(new int[] {1, 4, 7}, 2); + } + } + + var sb = new System.Text.StringBuilder(); + for (int i = 9; i >= 0; i--) { + sb.Append((char)('0' + i), counts[i]); + } + string result = sb.ToString(); + return result.Length > 0 && result[0] == '0' ? "0" : result; + } +} diff --git a/tests/1001-1500/1363. largest-multiple-of-three/sol.dart b/tests/1001-1500/1363. largest-multiple-of-three/sol.dart new file mode 100644 index 00000000..73a070e1 --- /dev/null +++ b/tests/1001-1500/1363. largest-multiple-of-three/sol.dart @@ -0,0 +1,44 @@ +class Solution { + String largestMultipleOfThree(List digits) { + var counts = List.filled(10, 0); + for (var digit in digits) { + counts[digit]++; + } + + var sum = 0; + for (var i = 0; i < 10; i++) { + sum += i * counts[i]; + } + var remainder = sum % 3; + + bool removeSmallest(List group, int amount) { + var amt = amount; + for (var digit in group) { + while (amt > 0 && counts[digit] > 0) { + counts[digit]--; + amt--; + } + } + return amt == 0; + } + + if (remainder == 1) { + if (!removeSmallest([1, 4, 7], 1)) { + removeSmallest([2, 5, 8], 2); + } + } else if (remainder == 2) { + if (!removeSmallest([2, 5, 8], 1)) { + removeSmallest([1, 4, 7], 2); + } + } + + var sb = StringBuffer(); + for (var i = 9; i >= 0; i--) { + for (var j = 0; j < counts[i]; j++) { + sb.write(i); + } + } + var result = sb.toString(); + return result.startsWith('0') ? '0' : result; + } +} diff --git a/tests/1001-1500/1363. largest-multiple-of-three/sol.go b/tests/1001-1500/1363. largest-multiple-of-three/sol.go new file mode 100644 index 00000000..0fe2f46a --- /dev/null +++ b/tests/1001-1500/1363. largest-multiple-of-three/sol.go @@ -0,0 +1,44 @@ +func largestMultipleOfThree(digits []int) string { + counts := make([]int, 10) + for _, digit := range digits { + counts[digit]++ + } + + sum := 0 + for i := 0; i < 10; i++ { + sum += i * counts[i] + } + remainder := sum % 3 + + removeSmallest := func(group []int, amount int) bool { + amt := amount + for _, digit := range group { + for amt > 0 && counts[digit] > 0 { + counts[digit]-- + amt-- + } + } + return amt == 0 + } + + if remainder == 1 { + if !removeSmallest([]int{1, 4, 7}, 1) { + removeSmallest([]int{2, 5, 8}, 2) + } + } else if remainder == 2 { + if !removeSmallest([]int{2, 5, 8}, 1) { + removeSmallest([]int{1, 4, 7}, 2) + } + } + + var result []byte + for i := 9; i >= 0; i-- { + for j := 0; j < counts[i]; j++ { + result = append(result, byte('0'+i)) + } + } + if len(result) > 0 && result[0] == '0' { + return "0" + } + return string(result) +} diff --git a/tests/1001-1500/1363. largest-multiple-of-three/sol.java b/tests/1001-1500/1363. largest-multiple-of-three/sol.java new file mode 100644 index 00000000..1db88f0a --- /dev/null +++ b/tests/1001-1500/1363. largest-multiple-of-three/sol.java @@ -0,0 +1,43 @@ +class Solution { + public String largestMultipleOfThree(int[] digits) { + int[] counts = new int[10]; + for (int digit : digits) { + counts[digit]++; + } + + int sum = 0; + for (int i = 0; i < 10; i++) { + sum += i * counts[i]; + } + int remainder = sum % 3; + + if (remainder == 1) { + if (!removeSmallest(counts, new int[]{1, 4, 7}, 1)) { + removeSmallest(counts, new int[]{2, 5, 8}, 2); + } + } else if (remainder == 2) { + if (!removeSmallest(counts, new int[]{2, 5, 8}, 1)) { + removeSmallest(counts, new int[]{1, 4, 7}, 2); + } + } + + StringBuilder sb = new StringBuilder(); + for (int i = 9; i >= 0; i--) { + for (int j = 0; j < counts[i]; j++) { + sb.append(i); + } + } + String result = sb.toString(); + return result.startsWith("0") ? "0" : result; + } + + private boolean removeSmallest(int[] counts, int[] group, int amount) { + for (int digit : group) { + while (amount > 0 && counts[digit] > 0) { + counts[digit]--; + amount--; + } + } + return amount == 0; + } +} diff --git a/tests/1001-1500/1363. largest-multiple-of-three/sol.kt b/tests/1001-1500/1363. largest-multiple-of-three/sol.kt new file mode 100644 index 00000000..0e8575db --- /dev/null +++ b/tests/1001-1500/1363. largest-multiple-of-three/sol.kt @@ -0,0 +1,44 @@ +class Solution { + fun largestMultipleOfThree(digits: IntArray): String { + val counts = IntArray(10) + for (digit in digits) { + counts[digit]++ + } + + var sum = 0 + for (i in 0..9) { + sum += i * counts[i] + } + val remainder = sum % 3 + + fun removeSmallest(group: IntArray, amount: Int): Boolean { + var amt = amount + for (digit in group) { + while (amt > 0 && counts[digit] > 0) { + counts[digit]-- + amt-- + } + } + return amt == 0 + } + + if (remainder == 1) { + if (!removeSmallest(intArrayOf(1, 4, 7), 1)) { + removeSmallest(intArrayOf(2, 5, 8), 2) + } + } else if (remainder == 2) { + if (!removeSmallest(intArrayOf(2, 5, 8), 1)) { + removeSmallest(intArrayOf(1, 4, 7), 2) + } + } + + val sb = StringBuilder() + for (i in 9 downTo 0) { + repeat(counts[i]) { + sb.append(i) + } + } + val result = sb.toString() + return if (result.startsWith('0')) "0" else result + } +} diff --git a/tests/1001-1500/1363. largest-multiple-of-three/sol.py b/tests/1001-1500/1363. largest-multiple-of-three/sol.py new file mode 100644 index 00000000..9bf3ab31 --- /dev/null +++ b/tests/1001-1500/1363. largest-multiple-of-three/sol.py @@ -0,0 +1,24 @@ +class Solution: + def largestMultipleOfThree(self, digits): + counts = [0] * 10 + for digit in digits: + counts[digit] += 1 + + remainder = sum(digit * counts[digit] for digit in range(10)) % 3 + + def remove_smallest(group, amount): + for digit in group: + while amount and counts[digit]: + counts[digit] -= 1 + amount -= 1 + return amount == 0 + + if remainder == 1: + if not remove_smallest((1, 4, 7), 1): + remove_smallest((2, 5, 8), 2) + elif remainder == 2: + if not remove_smallest((2, 5, 8), 1): + remove_smallest((1, 4, 7), 2) + + result = "".join(str(digit) * counts[digit] for digit in range(9, -1, -1)) + return "0" if result.startswith("0") else result diff --git a/tests/1001-1500/1363. largest-multiple-of-three/sol.py2 b/tests/1001-1500/1363. largest-multiple-of-three/sol.py2 new file mode 100644 index 00000000..a7132319 --- /dev/null +++ b/tests/1001-1500/1363. largest-multiple-of-three/sol.py2 @@ -0,0 +1,28 @@ +class Solution(object): + def largestMultipleOfThree(self, digits): + """ + :type digits: List[int] + :rtype: str + """ + counts = [0] * 10 + for digit in digits: + counts[digit] += 1 + + remainder = sum(digit * counts[digit] for digit in range(10)) % 3 + + def remove_smallest(group, amount): + for digit in group: + while amount and counts[digit]: + counts[digit] -= 1 + amount -= 1 + return amount == 0 + + if remainder == 1: + if not remove_smallest((1, 4, 7), 1): + remove_smallest((2, 5, 8), 2) + elif remainder == 2: + if not remove_smallest((2, 5, 8), 1): + remove_smallest((1, 4, 7), 2) + + result = ''.join(str(digit) * counts[digit] for digit in range(9, -1, -1)) + return '0' if result.startswith('0') else result diff --git a/tests/1001-1500/1363. largest-multiple-of-three/sol.rb b/tests/1001-1500/1363. largest-multiple-of-three/sol.rb new file mode 100644 index 00000000..a1ce4c27 --- /dev/null +++ b/tests/1001-1500/1363. largest-multiple-of-three/sol.rb @@ -0,0 +1,31 @@ +# @param {Integer[]} digits +# @return {String} +def largest_multiple_of_three(digits) + counts = Array.new(10, 0) + digits.each { |digit| counts[digit] += 1 } + + remainder = (0..9).sum { |digit| digit * counts[digit] } % 3 + + remove_smallest = lambda do |group, amount| + group.each do |digit| + while amount > 0 && counts[digit] > 0 + counts[digit] -= 1 + amount -= 1 + end + end + amount == 0 + end + + if remainder == 1 + unless remove_smallest.call([1, 4, 7], 1) + remove_smallest.call([2, 5, 8], 2) + end + elsif remainder == 2 + unless remove_smallest.call([2, 5, 8], 1) + remove_smallest.call([1, 4, 7], 2) + end + end + + result = (0..9).reverse_each.map { |digit| digit.to_s * counts[digit] }.join + result.start_with?('0') ? '0' : result +end diff --git a/tests/1001-1500/1363. largest-multiple-of-three/sol.rs b/tests/1001-1500/1363. largest-multiple-of-three/sol.rs new file mode 100644 index 00000000..0f53fcd4 --- /dev/null +++ b/tests/1001-1500/1363. largest-multiple-of-three/sol.rs @@ -0,0 +1,44 @@ +impl Solution { + pub fn largest_multiple_of_three(digits: Vec) -> String { + let mut counts = [0usize; 10]; + for digit in digits { + counts[digit as usize] += 1; + } + + let sum: i32 = (0usize..10).map(|i| i as i32 * counts[i] as i32).sum(); + let remainder = sum % 3; + + fn remove_smallest(counts: &mut [usize; 10], group: &[usize], mut amount: usize) -> bool { + for &digit in group { + while amount > 0 && counts[digit] > 0 { + counts[digit] -= 1; + amount -= 1; + } + } + amount == 0 + } + + if remainder == 1 { + if !remove_smallest(&mut counts, &[1, 4, 7], 1) { + remove_smallest(&mut counts, &[2, 5, 8], 2); + } + } else if remainder == 2 { + if !remove_smallest(&mut counts, &[2, 5, 8], 1) { + remove_smallest(&mut counts, &[1, 4, 7], 2); + } + } + + let mut result = String::new(); + for digit in (0usize..10).rev() { + for _ in 0..counts[digit] { + result.push(char::from(b'0' + digit as u8)); + } + } + + if result.starts_with('0') { + "0".to_string() + } else { + result + } + } +} diff --git a/tests/1001-1500/1363. largest-multiple-of-three/sol.swift b/tests/1001-1500/1363. largest-multiple-of-three/sol.swift new file mode 100644 index 00000000..d8356b43 --- /dev/null +++ b/tests/1001-1500/1363. largest-multiple-of-three/sol.swift @@ -0,0 +1,41 @@ +class Solution { + func largestMultipleOfThree(_ digits: [Int]) -> String { + var counts = [Int](repeating: 0, count: 10) + for digit in digits { + counts[digit] += 1 + } + + var sum = 0 + for i in 0..<10 { + sum += i * counts[i] + } + let remainder = sum % 3 + + func removeSmallest(_ group: [Int], _ amount: Int) -> Bool { + var amt = amount + for digit in group { + while amt > 0 && counts[digit] > 0 { + counts[digit] -= 1 + amt -= 1 + } + } + return amt == 0 + } + + if remainder == 1 { + if !removeSmallest([1, 4, 7], 1) { + removeSmallest([2, 5, 8], 2) + } + } else if remainder == 2 { + if !removeSmallest([2, 5, 8], 1) { + removeSmallest([1, 4, 7], 2) + } + } + + var result = "" + for i in stride(from: 9, through: 0, by: -1) { + result += String(repeating: String(i), count: counts[i]) + } + return result.hasPrefix("0") ? "0" : result + } +} diff --git a/tests/1001-1500/1363. largest-multiple-of-three/sol.ts b/tests/1001-1500/1363. largest-multiple-of-three/sol.ts new file mode 100644 index 00000000..cb219e86 --- /dev/null +++ b/tests/1001-1500/1363. largest-multiple-of-three/sol.ts @@ -0,0 +1,39 @@ +function largestMultipleOfThree(digits: number[]): string { + const counts: number[] = Array(10).fill(0); + for (const digit of digits) { + counts[digit]++; + } + + let sum = 0; + for (let i = 0; i < 10; i++) { + sum += i * counts[i]; + } + const remainder = sum % 3; + + const removeSmallest = (group: number[], amount: number): boolean => { + let amt = amount; + for (const digit of group) { + while (amt > 0 && counts[digit] > 0) { + counts[digit]--; + amt--; + } + } + return amt === 0; + }; + + if (remainder === 1) { + if (!removeSmallest([1, 4, 7], 1)) { + removeSmallest([2, 5, 8], 2); + } + } else if (remainder === 2) { + if (!removeSmallest([2, 5, 8], 1)) { + removeSmallest([1, 4, 7], 2); + } + } + + let result = ""; + for (let i = 9; i >= 0; i--) { + result += i.toString().repeat(counts[i]); + } + return result.startsWith("0") ? "0" : result; +} diff --git a/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/manifest.yaml b/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/manifest.yaml new file mode 100644 index 00000000..aef140b0 --- /dev/null +++ b/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/manifest.yaml @@ -0,0 +1,247 @@ +entry: + id: 1365 + title: "how-many-numbers-are-smaller-than-the-current-number" + params: + nums: + type: array + items: + type: int + call: + python3: "Solution().smallerNumbersThanCurrent({nums})" + python2: "Solution().smallerNumbersThanCurrent({nums})" + cpp: "Solution().smallerNumbersThanCurrent({nums})" + rust: "Solution::smaller_numbers_than_current({nums})" + ruby: "smaller_numbers_than_current({nums})" + java: "new Solution().smallerNumbersThanCurrent({nums})" + csharp: "new Solution().SmallerNumbersThanCurrent({nums})" + kotlin: "Solution().smallerNumbersThanCurrent({nums})" + go: "smallerNumbersThanCurrent({nums})" + dart: "Solution().smallerNumbersThanCurrent({nums})" + swift: "Solution().smallerNumbersThanCurrent({nums})" + typescript: "smallerNumbersThanCurrent({nums})" +judge: + type: "exact" +limits: + time_ms: 500 + memory_mb: 300 +oracle: + python3: + call: "Checker().smallerNumbersThanCurrent(nums, {result})" + checker: | + class Checker: + def smallerNumbersThanCurrent(self, nums, result): + if not isinstance(result, list) or len(result) != len(nums): + return False + for index, value in enumerate(nums): + if not isinstance(result[index], int): + return False + if result[index] != sum(1 for other in nums if other < value): + return False + return True +seed: 1365 +tests: + - name: "example_one" + in: + nums: [8, 1, 2, 2, 3] + out: [4, 0, 1, 1, 3] + - name: "example_two" + in: + nums: [6, 5, 4, 8] + out: [2, 1, 0, 3] + - name: "example_three" + in: + nums: [7, 7, 7, 7] + out: [0, 0, 0, 0] + - name: "two_ascending" + in: + nums: [0, 1] + out: [0, 1] + - name: "two_descending" + in: + nums: [100, 0] + out: [1, 0] + - name: "two_equal_zero" + in: + nums: [0, 0] + out: [0, 0] + - name: "two_equal_maximum" + in: + nums: [100, 100] + out: [0, 0] + - name: "strictly_increasing" + in: + nums: [0, 1, 2, 3, 4, 5] + out: [0, 1, 2, 3, 4, 5] + - name: "strictly_decreasing" + in: + nums: [5, 4, 3, 2, 1, 0] + out: [5, 4, 3, 2, 1, 0] + - name: "all_zero" + in: + nums: [0, 0, 0, 0, 0] + out: [0, 0, 0, 0, 0] + - name: "all_hundred" + in: + nums: [100, 100, 100, 100, 100] + out: [0, 0, 0, 0, 0] + - name: "low_duplicates" + in: + nums: [1, 1, 2, 2, 3, 3] + out: [0, 0, 2, 2, 4, 4] + - name: "high_duplicates" + in: + nums: [98, 100, 99, 100, 98] + out: [0, 3, 2, 3, 0] + - name: "endpoints_and_middle" + in: + nums: [0, 100, 50, 50, 1] + out: [0, 4, 2, 2, 1] + - name: "alternating_values" + in: + nums: [1, 9, 2, 8, 3, 7] + out: [0, 5, 1, 4, 2, 3] + - name: "sparse_range" + in: + nums: [0, 25, 50, 75, 100] + out: [0, 1, 2, 3, 4] + - name: "peak" + in: + nums: [1, 2, 100, 2, 1] + out: [0, 2, 4, 2, 0] + - name: "valley" + in: + nums: [100, 2, 1, 2, 100] + out: [3, 1, 0, 1, 3] + - name: "mixed_small" + in: + nums: [2, 1, 2, 0, 1] + out: [3, 1, 3, 0, 1] + - name: "mixed_values_a" + in: + nums: [4, 0, 9, 4, 2, 8] + out: [2, 0, 5, 2, 1, 4] + - name: "mixed_values_b" + in: + nums: [10, 3, 6, 1, 9, 2, 5] + out: [6, 2, 4, 0, 5, 1, 3] + - name: "mixed_values_c" + in: + nums: [20, 20, 1, 19, 0, 20] + out: [3, 3, 1, 2, 0, 3] + - name: "mixed_values_d" + in: + nums: [33, 12, 76, 4, 55, 4] + out: [3, 2, 5, 0, 4, 0] + - name: "repeated_middle" + in: + nums: [0, 50, 50, 50, 100] + out: [0, 1, 1, 1, 4] + - name: "near_maximum" + in: + nums: [96, 97, 98, 99, 100, 0] + out: [1, 2, 3, 4, 5, 0] + - name: "permuted_sequence" + in: + nums: [5, 3, 1, 4, 2, 0] + out: [5, 3, 1, 4, 2, 0] + - name: "repeated_endpoints" + in: + nums: [0, 100, 0, 100, 50, 50] + out: [0, 4, 0, 4, 2, 2] + - name: "dense_duplicates" + in: + nums: [1, 2, 1, 3, 2, 4, 3, 5] + out: [0, 2, 0, 4, 2, 6, 4, 7] + - name: "frequency_gradient" + in: + nums: [3, 0, 3, 1, 3, 2, 2, 1] + out: [5, 0, 5, 1, 5, 3, 3, 1] + - name: "zero_and_one_heavy" + in: + nums: [1, 0, 1, 0, 1, 0, 2] + out: [3, 0, 3, 0, 3, 0, 6] + - name: "full_extremes" + in: + nums: [100, 0, 100, 0, 99, 1] + out: [4, 0, 4, 0, 3, 2] + - name: "middle_value_plateau" + in: + nums: [51, 49, 50, 50, 49, 51, 50] + out: [5, 0, 2, 2, 0, 5, 2] + - name: "interleaved_frequency_bands" + in: + nums: [10, 30, 20, 10, 40, 30, 20, 10] + out: [0, 5, 3, 0, 7, 5, 3, 0] + - name: "nonuniform_repetitions" + in: + nums: [6, 3, 6, 3, 6, 2, 2, 5, 5] + out: [6, 2, 6, 2, 6, 0, 0, 4, 4] + - name: "hundred_value_span" + in: + nums: [100, 1, 99, 2, 98, 3, 97, 4] + out: [7, 0, 6, 1, 5, 2, 4, 3] + - name: "generator_small" + seed: 11 + in: + nums: + gen: "array" + len: 20 + of: + gen: "int" + min: 0 + max: 100 + distinct: false + sorted: false + elemType: "int" + - name: "generator_duplicate_heavy" + seed: 22 + in: + nums: + gen: "array" + len: 100 + of: + gen: "int" + min: 0 + max: 5 + distinct: false + sorted: false + elemType: "int" + - name: "generator_boundary_range" + seed: 33 + in: + nums: + gen: "array" + len: 200 + of: + gen: "int" + min: 0 + max: 100 + distinct: false + sorted: false + elemType: "int" + - name: "generator_near_maximum" + seed: 44 + in: + nums: + gen: "array" + len: 499 + of: + gen: "int" + min: 90 + max: 100 + distinct: false + sorted: false + elemType: "int" + - name: "generator_maximum_length" + seed: 55 + in: + nums: + gen: "array" + len: 500 + of: + gen: "int" + min: 0 + max: 100 + distinct: false + sorted: false + elemType: "int" diff --git a/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.cpp b/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.cpp new file mode 100644 index 00000000..0fef97e5 --- /dev/null +++ b/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + vector smallerNumbersThanCurrent(vector& nums) { + vector allNums(101, 0); + vector res(nums.size(), 0); + + for (int v : nums) { + allNums[v]++; + } + + for (int v = 1; v <= 100; v++) { + allNums[v] += allNums[v - 1]; + } + + for (int i = 0; i < nums.size(); i++) { + int v = nums[i]; + if (v == 0) { + res[i] = 0; + } else { + res[i] = allNums[v - 1]; + } + } + return res; + } +}; diff --git a/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.cs b/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.cs new file mode 100644 index 00000000..d7f54b94 --- /dev/null +++ b/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.cs @@ -0,0 +1,24 @@ +public class Solution { + public int[] SmallerNumbersThanCurrent(int[] nums) { + int[] allNums = new int[101]; + int[] res = new int[nums.Length]; + + foreach (int v in nums) { + allNums[v]++; + } + + for (int v = 1; v <= 100; v++) { + allNums[v] += allNums[v - 1]; + } + + for (int i = 0; i < nums.Length; i++) { + int v = nums[i]; + if (v == 0) { + res[i] = 0; + } else { + res[i] = allNums[v - 1]; + } + } + return res; + } +} diff --git a/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.dart b/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.dart new file mode 100644 index 00000000..99a08135 --- /dev/null +++ b/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.dart @@ -0,0 +1,24 @@ +class Solution { + List smallerNumbersThanCurrent(List nums) { + List allNums = List.filled(101, 0); + List res = List.filled(nums.length, 0); + + for (int v in nums) { + allNums[v]++; + } + + for (int v = 1; v <= 100; v++) { + allNums[v] += allNums[v - 1]; + } + + for (int i = 0; i < nums.length; i++) { + int v = nums[i]; + if (v == 0) { + res[i] = 0; + } else { + res[i] = allNums[v - 1]; + } + } + return res; + } +} diff --git a/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.go b/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.go new file mode 100644 index 00000000..7d23c480 --- /dev/null +++ b/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.go @@ -0,0 +1,21 @@ +func smallerNumbersThanCurrent(nums []int) []int { + allNums := make([]int, 101) + res := make([]int, len(nums)) + + for _, v := range nums { + allNums[v]++ + } + + for v := 1; v <= 100; v++ { + allNums[v] += allNums[v-1] + } + + for i, v := range nums { + if v == 0 { + res[i] = 0 + } else { + res[i] = allNums[v-1] + } + } + return res +} diff --git a/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.java b/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.java new file mode 100644 index 00000000..8bf13290 --- /dev/null +++ b/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.java @@ -0,0 +1,24 @@ +class Solution { + public int[] smallerNumbersThanCurrent(int[] nums) { + int[] allNums = new int[101]; + int[] res = new int[nums.length]; + + for (int v : nums) { + allNums[v]++; + } + + for (int v = 1; v <= 100; v++) { + allNums[v] += allNums[v - 1]; + } + + for (int i = 0; i < nums.length; i++) { + int v = nums[i]; + if (v == 0) { + res[i] = 0; + } else { + res[i] = allNums[v - 1]; + } + } + return res; + } +} diff --git a/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.kt b/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.kt new file mode 100644 index 00000000..8153dfde --- /dev/null +++ b/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.kt @@ -0,0 +1,24 @@ +class Solution { + fun smallerNumbersThanCurrent(nums: IntArray): IntArray { + val allNums = IntArray(101) + val res = IntArray(nums.size) + + for (v in nums) { + allNums[v]++ + } + + for (v in 1..100) { + allNums[v] += allNums[v - 1] + } + + for (i in nums.indices) { + val v = nums[i] + if (v == 0) { + res[i] = 0 + } else { + res[i] = allNums[v - 1] + } + } + return res + } +} diff --git a/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.py b/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.py new file mode 100644 index 00000000..e1e384d6 --- /dev/null +++ b/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.py @@ -0,0 +1,32 @@ +class Solution(object): + def smallerNumbersThanCurrent(self, nums): + """ + :type nums: List[int] + :rtype: List[int] + """ + # Frequency array for values in range [0, 100]. + # allNums[v] will first store how many times value v appears in nums. + allNums = [0] * 101 + + # Result array. res[i] = count of numbers strictly smaller than nums[i]. + res = [0] * len(nums) + + # 1) Count frequency of each number in nums. + for v in nums: + allNums[v] += 1 + + # 2) Convert frequency array into a prefix sum array. + # After this loop: allNums[v] = number of elements <= v. + for v in range(1, 101): + allNums[v] += allNums[v - 1] + + # 3) Build the result using if-else (no ternary). + for i in range(len(nums)): + v = nums[i] + if v == 0: + # If value is 0, no smaller numbers exist. + res[i] = 0 + else: + # Otherwise, count of numbers strictly less than v. + res[i] = allNums[v - 1] + return res diff --git a/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.py2 b/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.py2 new file mode 100644 index 00000000..7287715f --- /dev/null +++ b/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.py2 @@ -0,0 +1,22 @@ +class Solution(object): + def smallerNumbersThanCurrent(self, nums): + """ + :type nums: List[int] + :rtype: List[int] + """ + allNums = [0] * 101 + res = [0] * len(nums) + + for v in nums: + allNums[v] += 1 + + for v in range(1, 101): + allNums[v] += allNums[v - 1] + + for i in range(len(nums)): + v = nums[i] + if v == 0: + res[i] = 0 + else: + res[i] = allNums[v - 1] + return res diff --git a/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.rb b/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.rb new file mode 100644 index 00000000..49cd0b45 --- /dev/null +++ b/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.rb @@ -0,0 +1,23 @@ +# @param {Integer[]} nums +# @return {Integer[]} +def smaller_numbers_than_current(nums) + all_nums = Array.new(101, 0) + res = Array.new(nums.length, 0) + + nums.each do |v| + all_nums[v] += 1 + end + + (1..100).each do |v| + all_nums[v] += all_nums[v - 1] + end + + nums.each_with_index do |v, i| + if v == 0 + res[i] = 0 + else + res[i] = all_nums[v - 1] + end + end + res +end diff --git a/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.rs b/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.rs new file mode 100644 index 00000000..65624117 --- /dev/null +++ b/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.rs @@ -0,0 +1,23 @@ +impl Solution { + pub fn smaller_numbers_than_current(nums: Vec) -> Vec { + let mut all_nums = vec![0; 101]; + let mut res = vec![0; nums.len()]; + + for &v in &nums { + all_nums[v as usize] += 1; + } + + for v in 1..=100 { + all_nums[v] += all_nums[v - 1]; + } + + for (i, &v) in nums.iter().enumerate() { + if v == 0 { + res[i] = 0; + } else { + res[i] = all_nums[(v - 1) as usize]; + } + } + res + } +} diff --git a/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.swift b/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.swift new file mode 100644 index 00000000..c438ff64 --- /dev/null +++ b/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.swift @@ -0,0 +1,23 @@ +class Solution { + func smallerNumbersThanCurrent(_ nums: [Int]) -> [Int] { + var allNums = [Int](repeating: 0, count: 101) + var res = [Int](repeating: 0, count: nums.count) + + for v in nums { + allNums[v] += 1 + } + + for v in 1...100 { + allNums[v] += allNums[v - 1] + } + + for (i, v) in nums.enumerated() { + if v == 0 { + res[i] = 0 + } else { + res[i] = allNums[v - 1] + } + } + return res + } +} diff --git a/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.ts b/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.ts new file mode 100644 index 00000000..567e557d --- /dev/null +++ b/tests/1001-1500/1365. how-many-numbers-are-smaller-than-the-current-number/sol.ts @@ -0,0 +1,22 @@ +function smallerNumbersThanCurrent(nums: number[]): number[] { + const allNums: number[] = new Array(101).fill(0); + const res: number[] = new Array(nums.length).fill(0); + + for (const v of nums) { + allNums[v]++; + } + + for (let v = 1; v <= 100; v++) { + allNums[v] += allNums[v - 1]; + } + + for (let i = 0; i < nums.length; i++) { + const v = nums[i]; + if (v === 0) { + res[i] = 0; + } else { + res[i] = allNums[v - 1]; + } + } + return res; +} diff --git a/tests/1001-1500/1366. rank-teams-by-votes/manifest.yaml b/tests/1001-1500/1366. rank-teams-by-votes/manifest.yaml new file mode 100644 index 00000000..3ed0ef92 --- /dev/null +++ b/tests/1001-1500/1366. rank-teams-by-votes/manifest.yaml @@ -0,0 +1,234 @@ +entry: + id: 1366 + title: "rank-teams-by-votes" + params: + votes: + type: array + items: + type: string + call: + cpp: "Solution().rankTeams({votes})" + rust: "Solution::rank_teams({votes})" + python3: "Solution().rankTeams({votes})" + python2: "Solution().rankTeams({votes})" + ruby: "rank_teams({votes})" + java: "new Solution().rankTeams({votes})" + csharp: "new Solution().RankTeams({votes})" + kotlin: "Solution().rankTeams({votes})" + go: "rankTeams({votes})" + dart: "Solution().rankTeams({votes})" + swift: "Solution().rankTeams({votes})" + typescript: "rankTeams({votes})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().rankTeams(votes, {result})" + checker: | + class Checker: + def rankTeams(self, votes, result): + if not isinstance(result, str): + return False + teams = list(votes[0]) + if len(result) != len(teams) or set(result) != set(teams): + return False + counts = {team: [0] * len(teams) for team in teams} + for vote in votes: + for place, team in enumerate(vote): + counts[team][place] += 1 + expected = ''.join(sorted( + teams, + key=lambda team: tuple([-count for count in counts[team]]) + (team,), + )) + return result == expected + +seed: 1366 + +tests: + - name: "example-one" + in: + votes: ["ABC", "ACB", "ABC", "ACB", "ACB"] + - name: "example-two" + in: + votes: ["WXYZ", "XYZW"] + - name: "example-three" + in: + votes: ["ZMNAGUEDSJYLBOPHRQICWFXTVK"] + - name: "single-team" + in: + votes: ["A"] + - name: "two-teams-alphabetical-tie" + in: + votes: ["AB", "BA"] + - name: "two-teams-clear-winner" + in: + votes: ["BA", "BA", "AB"] + - name: "three-teams-perfect-tie" + in: + votes: ["ABC", "BCA", "CAB"] + - name: "three-teams-second-place-break" + in: + votes: ["ABC", "ACB"] + - name: "three-teams-third-place-break" + in: + votes: ["ABC", "BAC", "CBA", "BCA"] + - name: "four-teams-alphabetical-tie" + in: + votes: ["ABCD", "DCBA"] + - name: "four-teams-first-place-split" + in: + votes: ["ABCD", "ACBD", "BACD", "BCAD"] + - name: "four-teams-deep-tie" + in: + votes: ["ABCD", "BADC", "CDAB", "DCBA"] + - name: "five-teams-one-voter" + in: + votes: ["EDCBA"] + - name: "five-teams-repeated-winner" + in: + votes: ["ABCDE", "ABCDE", "ABCDE", "BACDE", "CBADE"] + - name: "five-teams-last-place-tie" + in: + votes: ["ABCDE", "ABDEC", "ABDCE", "ABEDC"] + - name: "six-teams-cyclic" + in: + votes: ["ABCDEF", "BCDEFA", "CDEFAB", "DEFABC", "EFABCD", "FABCDE"] + - name: "six-teams-reversed-pairs" + in: + votes: ["ABCDEF", "FEDCBA", "ABCDEF", "FEDCBA", "BADCFE"] + - name: "six-teams-late-resolution" + in: + votes: ["ABCDEF", "BACDEF", "ACBDEF", "CABDEF", "DABCEF"] + - name: "seven-teams-openings" + in: + votes: ["ABCDEFG", "GFEDCBA", "BCADEFG", "CBADEFG", "ABCDEFG"] + - name: "seven-teams-balanced" + in: + votes: + [ + "ABCDEFG", + "BCDEFGA", + "CDEFGAB", + "DEFGABC", + "EFGABCD", + "FGABCDE", + "GABCDEF", + ] + - name: "eight-teams-alternating" + in: + votes: ["ABCDEFGH", "HGFEDCBA", "ABCDEFGH", "HGFEDCBA", "BADCFEHG"] + - name: "eight-teams-shifted" + in: + votes: ["ABCDEFGH", "BCDEFGHA", "CDEFGHAB", "DEFGHABC"] + - name: "nine-teams-tied-leaders" + in: + votes: ["ABCDEFGHI", "BACDEFGHI", "CBADEFGHI", "ACBDEFGHI", "BCADEFGHI"] + - name: "ten-teams-single-voter" + in: + votes: ["JIHGFEDCBA"] + - name: "ten-teams-repeated-prefix" + in: + votes: + ["ABCDEFGHIJ", "ABCDJIHGFE", "ABCDJIHGFE", "BACDJIHGFE", "CABDJIHGFE"] + - name: "ten-teams-reversed" + in: + votes: ["ABCDEFGHIJ", "JIHGFEDCBA", "JIHGFEDCBA", "ABCDEFGHIJ"] + - name: "twelve-teams-cyclic" + in: + votes: + [ + "ABCDEFGHIJKL", + "BCDEFGHIJKLA", + "CDEFGHIJKLAB", + "DEFGHIJKLABC", + "EFGHIJKLABCD", + ] + - name: "twelve-teams-deep-tie" + in: + votes: ["ABCDEFGHIJKL", "BACDEFGHIJKL", "ABCDIJKLEFGH"] + - name: "thirteen-teams-one-voter" + in: + votes: ["MNABCDEFGHIJK"] + - name: "fourteen-teams-mixed" + in: + votes: + ["ABCDEFGHIJKLMN", "NMLKJIHGFEDCBA", "BACDEFGHIJKLMN", "CBADEFGHIJKLMN"] + - name: "sixteen-teams-balanced" + in: + votes: + [ + "ABCDEFGHIJKLMNOP", + "PONMLKJIHGFEDCBA", + "BADCFEHGJILKNMPO", + "ABCDEFGHIJKLMNOP", + ] + - name: "eighteen-teams-one-voter" + in: + votes: ["SRQPONMLKJIHGFEDCBA"] + - name: "twenty-teams-shifted" + in: + votes: + ["ABCDEFGHIJKLMNOPQRST", "BCDEFGHIJKLMNOPQRSTA", "CDEFGHIJKLMNOPQRSTAB"] + - name: "twenty-six-teams-one-voter" + in: + votes: ["ZYXWVUTSRQPONMLKJIHGFEDCBA"] + - name: "twenty-six-teams-reversed-pair" + in: + votes: ["ABCDEFGHIJKLMNOPQRSTUVWXYZ", "ZYXWVUTSRQPONMLKJIHGFEDCBA"] + - name: "five-teams-ten-voters-distributed" + in: + votes: + [ + "ABCDE", + "BACDE", + "CABDE", + "DABCE", + "EABCD", + "ABCDE", + "BACDE", + "CABDE", + "DABCE", + "EABCD", + ] + - name: "eight-teams-middle-position-resolution" + in: + votes: + ["ABCDEFGH", "BACDEFGH", "ABDCFEGH", "BADCEFHG", "CDEFGHAB", "CDEFGHBA"] + - name: "fourteen-teams-repeated-front-tie" + in: + votes: + [ + "ABCDEFGHIJKLMN", + "BACDEFGHIJKLMN", + "ABCDEFGHIJKLMN", + "BACDEFGHIJKLMN", + "CDEFGHIJKLMNAB", + "CDEFGHIJKLMNBA", + ] + - name: "twenty-one-teams-mixed-rotations" + in: + votes: + [ + "ABCDEFGHIJKLMNOPQRSTU", + "BCDEFGHIJKLMNOPQRSTUA", + "CDEFGHIJKLMNOPQRSTUAB", + "UTSRQPONMLKJIHGFEDCBA", + "KLMNOPQRSTUABCDEFGHIJ", + ] + - name: "twenty-six-teams-many-position-ties" + in: + votes: + [ + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", + "BCDEFGHIJKLMNOPQRSTUVWXYZA", + "CDEFGHIJKLMNOPQRSTUVWXYZAB", + "ZYXWVUTSRQPONMLKJIHGFEDCBA", + "YXWVUTSRQPONMLKJIHGFEDCBAZ", + "XWVUTSRQPONMLKJIHGFEDCBAZY", + ] diff --git a/tests/1001-1500/1366. rank-teams-by-votes/sol.cpp b/tests/1001-1500/1366. rank-teams-by-votes/sol.cpp new file mode 100644 index 00000000..97605f02 --- /dev/null +++ b/tests/1001-1500/1366. rank-teams-by-votes/sol.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + string rankTeams(vector& votes) { + string teams = votes[0]; + int n = teams.size(); + unordered_map> positions; + for (char team : teams) { + positions[team] = vector(n, 0); + } + for (const string& vote : votes) { + for (int i = 0; i < n; i++) { + positions[vote[i]][i]++; + } + } + sort(teams.begin(), teams.end(), [&](char a, char b) { + const vector& countsA = positions[a]; + const vector& countsB = positions[b]; + for (int i = 0; i < n; i++) { + if (countsA[i] != countsB[i]) { + return countsA[i] > countsB[i]; + } + } + return a < b; + }); + return teams; + } +}; diff --git a/tests/1001-1500/1366. rank-teams-by-votes/sol.cs b/tests/1001-1500/1366. rank-teams-by-votes/sol.cs new file mode 100644 index 00000000..ed080a24 --- /dev/null +++ b/tests/1001-1500/1366. rank-teams-by-votes/sol.cs @@ -0,0 +1,27 @@ +public class Solution { + public string RankTeams(string[] votes) { + string teams = votes[0]; + int n = teams.Length; + Dictionary positions = new Dictionary(); + foreach (char team in teams) { + positions[team] = new int[n]; + } + foreach (string vote in votes) { + for (int i = 0; i < n; i++) { + positions[vote[i]][i]++; + } + } + char[] sortedTeams = teams.ToCharArray(); + Array.Sort(sortedTeams, (a, b) => { + int[] countsA = positions[a]; + int[] countsB = positions[b]; + for (int i = 0; i < n; i++) { + if (countsA[i] != countsB[i]) { + return countsB[i] - countsA[i]; + } + } + return a - b; + }); + return new string(sortedTeams); + } +} diff --git a/tests/1001-1500/1366. rank-teams-by-votes/sol.dart b/tests/1001-1500/1366. rank-teams-by-votes/sol.dart new file mode 100644 index 00000000..ca323c40 --- /dev/null +++ b/tests/1001-1500/1366. rank-teams-by-votes/sol.dart @@ -0,0 +1,28 @@ +class Solution { + String rankTeams(List votes) { + String teams = votes[0]; + int n = teams.length; + Map> positions = {}; + for (var team in teams.split('')) { + positions[team] = List.filled(n, 0); + } + for (var vote in votes) { + for (int i = 0; i < n; i++) { + String team = vote[i]; + positions[team]![i]++; + } + } + List sortedTeams = teams.split(''); + sortedTeams.sort((a, b) { + List countsA = positions[a]!; + List countsB = positions[b]!; + for (int i = 0; i < n; i++) { + if (countsA[i] != countsB[i]) { + return countsB[i] - countsA[i]; + } + } + return a.codeUnitAt(0) - b.codeUnitAt(0); + }); + return sortedTeams.join(''); + } +} diff --git a/tests/1001-1500/1366. rank-teams-by-votes/sol.go b/tests/1001-1500/1366. rank-teams-by-votes/sol.go new file mode 100644 index 00000000..2798b575 --- /dev/null +++ b/tests/1001-1500/1366. rank-teams-by-votes/sol.go @@ -0,0 +1,27 @@ +func rankTeams(votes []string) string { + teams := votes[0] + n := len(teams) + positions := make(map[rune][]int) + for _, team := range teams { + positions[team] = make([]int, n) + } + for _, vote := range votes { + for i, team := range vote { + positions[team][i]++ + } + } + sortedTeams := []rune(teams) + sort.Slice(sortedTeams, func(i, j int) bool { + a := sortedTeams[i] + b := sortedTeams[j] + countsA := positions[a] + countsB := positions[b] + for k := 0; k < n; k++ { + if countsA[k] != countsB[k] { + return countsA[k] > countsB[k] + } + } + return a < b + }) + return string(sortedTeams) +} diff --git a/tests/1001-1500/1366. rank-teams-by-votes/sol.java b/tests/1001-1500/1366. rank-teams-by-votes/sol.java new file mode 100644 index 00000000..2cd1ce8d --- /dev/null +++ b/tests/1001-1500/1366. rank-teams-by-votes/sol.java @@ -0,0 +1,35 @@ +class Solution { + public String rankTeams(String[] votes) { + String teams = votes[0]; + int n = teams.length(); + Map positions = new HashMap<>(); + for (char team : teams.toCharArray()) { + positions.put(team, new int[n]); + } + for (String vote : votes) { + for (int i = 0; i < n; i++) { + char team = vote.charAt(i); + positions.get(team)[i]++; + } + } + Character[] sortedTeams = new Character[n]; + for (int i = 0; i < n; i++) { + sortedTeams[i] = teams.charAt(i); + } + Arrays.sort(sortedTeams, (a, b) -> { + int[] countsA = positions.get(a); + int[] countsB = positions.get(b); + for (int i = 0; i < n; i++) { + if (countsA[i] != countsB[i]) { + return countsB[i] - countsA[i]; + } + } + return a - b; + }); + StringBuilder sb = new StringBuilder(); + for (char c : sortedTeams) { + sb.append(c); + } + return sb.toString(); + } +} diff --git a/tests/1001-1500/1366. rank-teams-by-votes/sol.kt b/tests/1001-1500/1366. rank-teams-by-votes/sol.kt new file mode 100644 index 00000000..8a577478 --- /dev/null +++ b/tests/1001-1500/1366. rank-teams-by-votes/sol.kt @@ -0,0 +1,27 @@ +class Solution { + fun rankTeams(votes: Array): String { + val teams = votes[0] + val n = teams.length + val positions = mutableMapOf() + for (team in teams) { + positions[team] = IntArray(n) + } + for (vote in votes) { + for ((index, team) in vote.withIndex()) { + positions[team]!![index]++ + } + } + return teams.toCharArray() + .sortedWith(Comparator { a, b -> + val countsA = positions[a]!! + val countsB = positions[b]!! + for (i in 0 until n) { + if (countsA[i] != countsB[i]) { + return@Comparator countsB[i] - countsA[i] + } + } + a - b + }) + .joinToString("") + } +} diff --git a/tests/1001-1500/1366. rank-teams-by-votes/sol.py b/tests/1001-1500/1366. rank-teams-by-votes/sol.py new file mode 100644 index 00000000..eadcfa91 --- /dev/null +++ b/tests/1001-1500/1366. rank-teams-by-votes/sol.py @@ -0,0 +1,15 @@ +class Solution: + def rankTeams(self, votes): + teams = votes[0] + positions = {team: [0] * len(teams) for team in teams} + for vote in votes: + for index, team in enumerate(vote): + positions[team][index] += 1 + return "".join( + sorted( + teams, + key=lambda team: tuple( + [-count for count in positions[team]] + [ord(team)] + ), + ) + ) diff --git a/tests/1001-1500/1366. rank-teams-by-votes/sol.py2 b/tests/1001-1500/1366. rank-teams-by-votes/sol.py2 new file mode 100644 index 00000000..a208d0ae --- /dev/null +++ b/tests/1001-1500/1366. rank-teams-by-votes/sol.py2 @@ -0,0 +1,12 @@ +class Solution(object): + def rankTeams(self, votes): + """ + :type votes: List[str] + :rtype: str + """ + teams = votes[0] + positions = {team: [0] * len(teams) for team in teams} + for vote in votes: + for index, team in enumerate(vote): + positions[team][index] += 1 + return ''.join(sorted(teams, key=lambda team: tuple([-count for count in positions[team]] + [ord(team)]))) diff --git a/tests/1001-1500/1366. rank-teams-by-votes/sol.rb b/tests/1001-1500/1366. rank-teams-by-votes/sol.rb new file mode 100644 index 00000000..1e3df5d4 --- /dev/null +++ b/tests/1001-1500/1366. rank-teams-by-votes/sol.rb @@ -0,0 +1,13 @@ +# @param {String[]} votes +# @return {String} +def rank_teams(votes) + teams = votes[0] + positions = {} + teams.each_char { |team| positions[team] = Array.new(teams.length, 0) } + votes.each do |vote| + vote.each_char.with_index do |team, index| + positions[team][index] += 1 + end + end + teams.chars.sort_by { |team| positions[team].map { |count| -count } + [team.ord] }.join +end diff --git a/tests/1001-1500/1366. rank-teams-by-votes/sol.rs b/tests/1001-1500/1366. rank-teams-by-votes/sol.rs new file mode 100644 index 00000000..f96fb402 --- /dev/null +++ b/tests/1001-1500/1366. rank-teams-by-votes/sol.rs @@ -0,0 +1,28 @@ +impl Solution { + pub fn rank_teams(votes: Vec) -> String { + use std::collections::HashMap; + let teams: Vec = votes[0].chars().collect(); + let n = teams.len(); + let mut positions: HashMap> = HashMap::new(); + for &team in &teams { + positions.insert(team, vec![0; n]); + } + for vote in &votes { + for (i, team) in vote.chars().enumerate() { + positions.get_mut(&team).unwrap()[i] += 1; + } + } + let mut sorted_teams = teams.clone(); + sorted_teams.sort_by(|&a, &b| { + let counts_a = positions.get(&a).unwrap(); + let counts_b = positions.get(&b).unwrap(); + for i in 0..n { + if counts_a[i] != counts_b[i] { + return counts_b[i].cmp(&counts_a[i]); + } + } + a.cmp(&b) + }); + sorted_teams.into_iter().collect() + } +} diff --git a/tests/1001-1500/1366. rank-teams-by-votes/sol.swift b/tests/1001-1500/1366. rank-teams-by-votes/sol.swift new file mode 100644 index 00000000..4c3f4f51 --- /dev/null +++ b/tests/1001-1500/1366. rank-teams-by-votes/sol.swift @@ -0,0 +1,26 @@ +class Solution { + func rankTeams(_ votes: [String]) -> String { + let teams = Array(votes[0]) + let n = teams.count + var positions = [Character: [Int]]() + for team in teams { + positions[team] = Array(repeating: 0, count: n) + } + for vote in votes { + for (index, team) in vote.enumerated() { + positions[team]![index] += 1 + } + } + let sortedTeams = teams.sorted { a, b in + let countsA = positions[a]! + let countsB = positions[b]! + for i in 0.. countsB[i] + } + } + return a.asciiValue! < b.asciiValue! + } + return String(sortedTeams) + } +} diff --git a/tests/1001-1500/1366. rank-teams-by-votes/sol.ts b/tests/1001-1500/1366. rank-teams-by-votes/sol.ts new file mode 100644 index 00000000..39c96a95 --- /dev/null +++ b/tests/1001-1500/1366. rank-teams-by-votes/sol.ts @@ -0,0 +1,25 @@ +function rankTeams(votes: string[]): string { + const teams = votes[0]; + const n = teams.length; + const positions: Record = {}; + for (const team of teams) { + positions[team] = new Array(n).fill(0); + } + for (const vote of votes) { + for (let i = 0; i < n; i++) { + const team = vote[i]; + positions[team][i]++; + } + } + const sortedTeams = teams.split("").sort((a, b) => { + const countsA = positions[a]; + const countsB = positions[b]; + for (let i = 0; i < n; i++) { + if (countsA[i] !== countsB[i]) { + return countsB[i] - countsA[i]; + } + } + return a.charCodeAt(0) - b.charCodeAt(0); + }); + return sortedTeams.join(""); +} diff --git a/tests/1001-1500/1367. linked-list-in-binary-tree/manifest.yaml b/tests/1001-1500/1367. linked-list-in-binary-tree/manifest.yaml new file mode 100644 index 00000000..f5b9d861 --- /dev/null +++ b/tests/1001-1500/1367. linked-list-in-binary-tree/manifest.yaml @@ -0,0 +1,670 @@ +entry: + id: 1367 + title: linked-list-in-binary-tree + params: + head: + type: list_node + root: + type: tree_node + call: + cpp: "Solution().isSubPath({head}, {root})" + rust: "Solution::is_sub_path({head}, {root})" + python3: "Solution().isSubPath({head}, {root})" + python2: "Solution().isSubPath({head}, {root})" + ruby: "is_sub_path({head}, {root})" + java: "new Solution().isSubPath({head}, {root})" + csharp: "new Solution().IsSubPath({head}, {root})" + kotlin: "Solution().isSubPath({head}, {root})" + go: "isSubPath({head}, {root})" + dart: "Solution().isSubPath({head}, {root})" + swift: "Solution().isSubPath({head}, {root})" + typescript: "isSubPath({head}, {root})" +judge: + type: "exact" +limits: + time_ms: 1000 + memory_mb: 256 +oracle: + python3: + call: "Checker().isSubPath(head, root, {result})" + checker: | + class Checker: + def isSubPath(self, head, root, result): + if type(result) is not bool: + return False + + if isinstance(head, list): + pattern = head + else: + pattern = [] + while head is not None: + pattern.append(head.val) + head = head.next + + if isinstance(root, list): + if not root or root[0] is None: + return result is False + children = [[] for _ in root] + pending = [0] + position = 1 + for parent in pending: + for _ in range(2): + if position < len(root): + if root[position] is not None: + children[parent].append(position) + pending.append(position) + position += 1 + + def starts_here(index, offset): + if root[index] != pattern[offset]: + return False + if offset == len(pattern) - 1: + return True + return any(starts_here(child, offset + 1) for child in children[index]) + + expected = any(starts_here(index, 0) for index in pending) + else: + def starts_here(node, offset): + if node is None or node.val != pattern[offset]: + return False + if offset == len(pattern) - 1: + return True + return starts_here(node.left, offset + 1) or starts_here(node.right, offset + 1) + + def search(node): + if node is None: + return False + return starts_here(node, 0) or search(node.left) or search(node.right) + + expected = search(root) + return result == expected +seed: 1367 +tests: + - name: "example_1" + in: + head: [4, 2, 8] + root: + [1, 4, 4, null, 2, 2, null, 1, null, 6, 8, null, null, null, null, 1, 3] + - name: "example_2" + in: + head: [1, 4, 2, 6] + root: + [1, 4, 4, null, 2, 2, null, 1, null, 6, 8, null, null, null, null, 1, 3] + - name: "example_3" + in: + head: [1, 4, 2, 6, 8] + root: + [1, 4, 4, null, 2, 2, null, 1, null, 6, 8, null, null, null, null, 1, 3] + - name: "single_node_match" + in: + head: [1] + root: [1] + - name: "single_node_miss" + in: + head: [2] + root: [1] + - name: "root_to_left_leaf" + in: + head: [1, 2, 4] + root: [1, 2, 3, 4] + - name: "root_to_right_leaf" + in: + head: [1, 3, 7] + root: [1, 2, 3, null, null, 6, 7] + - name: "internal_left_chain" + in: + head: [5, 6, 7] + root: [9, 5, 2, 6, null, null, 3, 7] + - name: "internal_right_chain" + in: + head: [5, 6, 7] + root: [9, 2, 5, null, 3, 6, null, null, 7] + - name: "siblings_are_not_a_path" + in: + head: [2, 3] + root: [1, 2, 3] + - name: "wrong_branch_after_prefix" + in: + head: [3, 4, 5] + root: [1, 3, 3, 4, null, null, 5] + - name: "repeated_values_match" + in: + head: [2, 2, 2] + root: [2, 2, 9, 2, null, null, 2] + - name: "repeated_values_too_deep" + in: + head: [2, 2, 2, 2] + root: [2, 2, 2, 2, null, null, 2] + - name: "list_longer_than_tree" + in: + head: [1, 2, 3, 4] + root: [1, 2, 3] + - name: "multi_digit_concatenation_false_positive" + in: + head: [1, 23] + root: [12, 3] + - name: "multi_digit_path_match" + in: + head: [12, 3] + root: [8, 12, 9, 3] + - name: "value_at_upper_bound" + in: + head: [100, 99, 98] + root: [1, 100, 2, 99, null, null, 98] + - name: "single_value_anywhere" + in: + head: [77] + root: [1, 2, 3, 4, 77, 5, 6] + - name: "left_chain_depth_ten" + in: + head: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + root: + [ + 1, + 2, + null, + 3, + null, + 4, + null, + 5, + null, + 6, + null, + 7, + null, + 8, + null, + 9, + null, + 10, + ] + - name: "right_chain_depth_ten" + in: + head: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + root: + [ + 1, + null, + 2, + null, + 3, + null, + 4, + null, + 5, + null, + 6, + null, + 7, + null, + 8, + null, + 9, + null, + 10, + ] + - name: "zigzag_path" + in: + head: [9, 8, 7, 6] + root: [1, 9, 2, null, 8, 3, null, null, 7, null, 6] + - name: "duplicate_start_uses_later_node" + in: + head: [4, 5, 6] + root: [4, 4, 1, 2, 5, null, null, null, null, 6] + - name: "repeated_prefix_then_match" + in: + head: [1, 2, 1, 2, 3] + root: [8, 1, 4, 2, null, null, null, 1, null, 2, null, 3] + - name: "repeated_prefix_wrong_final_value" + in: + head: [1, 2, 1, 2, 4] + root: [8, 1, 4, 2, null, null, null, 1, null, 2, null, 3] + - name: "match_ending_at_internal_node" + in: + head: [7, 8] + root: [1, 7, 2, 8, 9, 3, 4] + - name: "partial_match_cannot_switch_children" + in: + head: [7, 8, 9] + root: [1, 7, 2, 8, 9] + - name: "complete_tree_leaf_path" + in: + head: [1, 3, 7, 15] + root: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] + - name: "complete_tree_non_path_order" + in: + head: [1, 3, 6] + root: [1, 2, 3, 4, 5, 6, 7] + - name: "all_same_exact_depth" + in: + head: [1, 1, 1] + root: [1, 1, 1, 1, 1, 1, 1] + - name: "all_same_exceeds_depth" + in: + head: [1, 1, 1, 1] + root: [1, 1, 1, 1, 1, 1, 1] + - name: "wide_tree_deep_right_match" + in: + head: [10, 11, 12, 13] + root: + [ + 1, + 2, + 10, + 3, + 4, + 11, + 5, + 6, + 7, + 8, + 9, + null, + 12, + null, + null, + null, + null, + null, + null, + null, + null, + 13, + ] + - name: "wide_tree_deep_right_miss" + in: + head: [10, 11, 13] + root: + [ + 1, + 2, + 10, + 3, + 4, + 11, + 5, + 6, + 7, + 8, + 9, + null, + 12, + null, + null, + null, + null, + null, + null, + null, + null, + 13, + ] + - name: "multiple_candidates_only_one_continues" + in: + head: [6, 7, 8] + root: [6, 6, 6, 7, 4, 5, 7, 1, 8, null, null, null, null, null, 8] + - name: "matching_values_across_different_branches" + in: + head: [4, 5] + root: [1, 4, 2, null, null, 5, 3] + - name: "start_not_at_root" + in: + head: [8, 9, 10] + root: [1, 2, 8, 3, 4, 9, 5, null, null, null, null, 10] + - name: "deep_path_final_mismatch" + in: + head: [2, 3, 4, 5, 7] + root: [1, 2, null, 3, null, 4, null, 5, null, 6] + - name: "alternating_values_long_match" + in: + head: [10, 20, 10, 20, 10, 20] + root: [3, 10, 4, null, 20, null, null, 10, null, 20, null, 10, null, 20] + - name: "alternating_values_long_miss" + in: + head: [10, 20, 10, 20, 20] + root: [3, 10, 4, null, 20, null, null, 10, null, 20, null, 10, null, 20] + - name: "maximum_length_list_match" + in: + head: + [ + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + ] + root: + [ + 1, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + ] + - name: "maximum_length_list_final_miss" + in: + head: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2] + root: + [ + 1, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + null, + 1, + ] diff --git a/tests/1001-1500/1367. linked-list-in-binary-tree/sol.cpp b/tests/1001-1500/1367. linked-list-in-binary-tree/sol.cpp new file mode 100644 index 00000000..1e692aca --- /dev/null +++ b/tests/1001-1500/1367. linked-list-in-binary-tree/sol.cpp @@ -0,0 +1,35 @@ +/** + * 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) {} + * }; + */ +/** + * 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 { +private: + bool matches(TreeNode* node, ListNode* current) { + if (current == nullptr) return true; + if (node == nullptr || node->val != current->val) return false; + return matches(node->left, current->next) || matches(node->right, current->next); + } + +public: + bool isSubPath(ListNode* head, TreeNode* root) { + if (root == nullptr) return false; + return matches(root, head) || isSubPath(head, root->left) || isSubPath(head, root->right); + } +}; diff --git a/tests/1001-1500/1367. linked-list-in-binary-tree/sol.cs b/tests/1001-1500/1367. linked-list-in-binary-tree/sol.cs new file mode 100644 index 00000000..0f12fcf5 --- /dev/null +++ b/tests/1001-1500/1367. linked-list-in-binary-tree/sol.cs @@ -0,0 +1,36 @@ +/** + * 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; + * } + * } + */ +/** + * 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 { + private bool Matches(TreeNode node, ListNode current) { + if (current == null) return true; + if (node == null || node.val != current.val) return false; + return Matches(node.left, current.next) || Matches(node.right, current.next); + } + + public bool IsSubPath(ListNode head, TreeNode root) { + if (root == null) return false; + return Matches(root, head) || IsSubPath(head, root.left) || IsSubPath(head, root.right); + } +} diff --git a/tests/1001-1500/1367. linked-list-in-binary-tree/sol.dart b/tests/1001-1500/1367. linked-list-in-binary-tree/sol.dart new file mode 100644 index 00000000..b19d4d6a --- /dev/null +++ b/tests/1001-1500/1367. linked-list-in-binary-tree/sol.dart @@ -0,0 +1,29 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * int val; + * ListNode? next; + * ListNode([this.val = 0, this.next]); + * } + */ +/** + * 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 matches(TreeNode? node, ListNode? current) { + if (current == null) return true; + if (node == null || node.val != current.val) return false; + return matches(node.left, current.next) || matches(node.right, current.next); + } + + bool isSubPath(ListNode? head, TreeNode? root) { + if (root == null) return false; + return matches(root, head) || isSubPath(head, root.left) || isSubPath(head, root.right); + } +} diff --git a/tests/1001-1500/1367. linked-list-in-binary-tree/sol.go b/tests/1001-1500/1367. linked-list-in-binary-tree/sol.go new file mode 100644 index 00000000..c66e113b --- /dev/null +++ b/tests/1001-1500/1367. linked-list-in-binary-tree/sol.go @@ -0,0 +1,32 @@ +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func isSubPath(head *ListNode, root *TreeNode) bool { + var matches func(node *TreeNode, current *ListNode) bool + matches = func(node *TreeNode, current *ListNode) bool { + if current == nil { + return true + } + if node == nil || node.Val != current.Val { + return false + } + return matches(node.Left, current.Next) || matches(node.Right, current.Next) + } + + if root == nil { + return false + } + return matches(root, head) || isSubPath(head, root.Left) || isSubPath(head, root.Right) +} diff --git a/tests/1001-1500/1367. linked-list-in-binary-tree/sol.java b/tests/1001-1500/1367. linked-list-in-binary-tree/sol.java new file mode 100644 index 00000000..e85a5c10 --- /dev/null +++ b/tests/1001-1500/1367. linked-list-in-binary-tree/sol.java @@ -0,0 +1,37 @@ +/** + * 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; } + * } + */ +/** + * 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 { + private boolean matches(TreeNode node, ListNode current) { + if (current == null) return true; + if (node == null || node.val != current.val) return false; + return matches(node.left, current.next) || matches(node.right, current.next); + } + + public boolean isSubPath(ListNode head, TreeNode root) { + if (root == null) return false; + return matches(root, head) || isSubPath(head, root.left) || isSubPath(head, root.right); + } +} diff --git a/tests/1001-1500/1367. linked-list-in-binary-tree/sol.kt b/tests/1001-1500/1367. linked-list-in-binary-tree/sol.kt new file mode 100644 index 00000000..99be638d --- /dev/null +++ b/tests/1001-1500/1367. linked-list-in-binary-tree/sol.kt @@ -0,0 +1,31 @@ +/** + * Example: + * var li = ListNode(5) + * var v = li.`val` + * Definition for singly-linked list. + * class ListNode(var `val`: Int) { + * var next: ListNode? = null + * } + */ +/** + * 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 { + private fun matches(node: TreeNode?, current: ListNode?): Boolean { + if (current == null) return true + if (node == null || node.`val` != current.`val`) return false + return matches(node.left, current.next) || matches(node.right, current.next) + } + + fun isSubPath(head: ListNode?, root: TreeNode?): Boolean { + if (root == null) return false + return matches(root, head) || isSubPath(head, root.left) || isSubPath(head, root.right) + } +} diff --git a/tests/1001-1500/1367. linked-list-in-binary-tree/sol.py b/tests/1001-1500/1367. linked-list-in-binary-tree/sol.py new file mode 100644 index 00000000..6000fa39 --- /dev/null +++ b/tests/1001-1500/1367. linked-list-in-binary-tree/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 +# 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 isSubPath(self, head: Optional[ListNode], root: Optional[TreeNode]) -> bool: + def matches(node, current): + if current is None: + return True + if node is None or node.val != current.val: + return False + return matches(node.left, current.next) or matches(node.right, current.next) + + if root is None: + return False + return ( + matches(root, head) + or self.isSubPath(head, root.left) + or self.isSubPath(head, root.right) + ) diff --git a/tests/1001-1500/1367. linked-list-in-binary-tree/sol.py2 b/tests/1001-1500/1367. linked-list-in-binary-tree/sol.py2 new file mode 100644 index 00000000..0664dbc7 --- /dev/null +++ b/tests/1001-1500/1367. linked-list-in-binary-tree/sol.py2 @@ -0,0 +1,28 @@ +# Definition for singly-linked list. +# class ListNode(object): +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +# 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 isSubPath(self, head, root): + """ + :type head: Optional[ListNode] + :type root: Optional[TreeNode] + :rtype: bool + """ + def matches(node, current): + if current is None: + return True + if node is None or node.val != current.val: + return False + return matches(node.left, current.next) or matches(node.right, current.next) + + if root is None: + return False + return matches(root, head) or self.isSubPath(head, root.left) or self.isSubPath(head, root.right) diff --git a/tests/1001-1500/1367. linked-list-in-binary-tree/sol.rb b/tests/1001-1500/1367. linked-list-in-binary-tree/sol.rb new file mode 100644 index 00000000..c3ae1406 --- /dev/null +++ b/tests/1001-1500/1367. linked-list-in-binary-tree/sol.rb @@ -0,0 +1,30 @@ +# Definition for singly-linked list. +# class ListNode +# attr_accessor :val, :next +# def initialize(val = 0, _next = nil) +# @val = val +# @next = _next +# end +# end +# 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 {ListNode} head +# @param {TreeNode} root +# @return {Boolean} +def is_sub_path(head, root) + def matches(node, current) + return true if current.nil? + return false if node.nil? || node.val != current.val + return matches(node.left, current.next) || matches(node.right, current.next) + end + + return false if root.nil? + return matches(root, head) || is_sub_path(head, root.left) || is_sub_path(head, root.right) +end diff --git a/tests/1001-1500/1367. linked-list-in-binary-tree/sol.rs b/tests/1001-1500/1367. linked-list-in-binary-tree/sol.rs new file mode 100644 index 00000000..7351dedf --- /dev/null +++ b/tests/1001-1500/1367. linked-list-in-binary-tree/sol.rs @@ -0,0 +1,63 @@ +// 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 +// } +// } +// } +// 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 { + fn matches(node: &Option>>, current: Option<&Box>) -> bool { + match current { + None => true, + Some(curr) => match node { + None => false, + Some(rc_node) => { + let node_ref = rc_node.borrow(); + if node_ref.val != curr.val { + return false; + } + Self::matches(&node_ref.left, curr.next.as_ref()) || + Self::matches(&node_ref.right, curr.next.as_ref()) + } + } + } + } + + pub fn is_sub_path(head: Option>, root: Option>>) -> bool { + match root { + None => false, + Some(ref rc_root) => { + Self::matches(&Some(rc_root.clone()), head.as_ref()) || + Self::is_sub_path(head.clone(), rc_root.borrow().left.clone()) || + Self::is_sub_path(head.clone(), rc_root.borrow().right.clone()) + } + } + } +} diff --git a/tests/1001-1500/1367. linked-list-in-binary-tree/sol.swift b/tests/1001-1500/1367. linked-list-in-binary-tree/sol.swift new file mode 100644 index 00000000..1ec34c27 --- /dev/null +++ b/tests/1001-1500/1367. linked-list-in-binary-tree/sol.swift @@ -0,0 +1,37 @@ +/** + * 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; } + * } + */ +/** + * 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 matches(_ node: TreeNode?, _ current: ListNode?) -> Bool { + if current == nil { return true } + if node == nil || node!.val != current!.val { return false } + return matches(node!.left, current!.next) || matches(node!.right, current!.next) + } + + func isSubPath(_ head: ListNode?, _ root: TreeNode?) -> Bool { + if root == nil { return false } + return matches(root, head) || isSubPath(head, root!.left) || isSubPath(head, root!.right) + } +} diff --git a/tests/1001-1500/1367. linked-list-in-binary-tree/sol.ts b/tests/1001-1500/1367. linked-list-in-binary-tree/sol.ts new file mode 100644 index 00000000..0860545c --- /dev/null +++ b/tests/1001-1500/1367. linked-list-in-binary-tree/sol.ts @@ -0,0 +1,45 @@ +/** + * 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) + * } + * } + */ + +/** + * 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 isSubPath(head: ListNode | null, root: TreeNode | null): boolean { + const matches = ( + node: TreeNode | null, + current: ListNode | null, + ): boolean => { + if (current === null) return true; + if (node === null || node.val !== current.val) return false; + return ( + matches(node.left, current.next) || matches(node.right, current.next) + ); + }; + + if (root === null) return false; + return ( + matches(root, head) || + isSubPath(head, root.left) || + isSubPath(head, root.right) + ); +} diff --git a/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/manifest.yaml b/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/manifest.yaml new file mode 100644 index 00000000..229e30e9 --- /dev/null +++ b/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/manifest.yaml @@ -0,0 +1,769 @@ +entry: + id: 1368 + title: "minimum-cost-to-make-at-least-one-valid-path-in-a-grid" + params: + grid: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().minCost({grid})" + rust: "Solution::min_cost({grid})" + python3: "Solution().minCost({grid})" + python2: "Solution().minCost({grid})" + ruby: "min_cost({grid})" + java: "new Solution().minCost({grid})" + csharp: "new Solution().MinCost({grid})" + kotlin: "Solution().minCost({grid})" + go: "minCost({grid})" + dart: "Solution().minCost({grid})" + swift: "Solution().minCost({grid})" + typescript: "minCost({grid})" +judge: + type: exact +limits: + time_ms: 700 + memory_mb: 300 +oracle: + python3: + call: "Checker().minCost(grid, {result})" + checker: | + from collections import deque + + class Checker: + def minCost(self, grid, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + rows, cols = len(grid), len(grid[0]) + distance = [[rows * cols + 1] * cols for _ in range(rows)] + distance[0][0] = 0 + queue = deque([(0, 0)]) + directions = ((0, 1), (0, -1), (1, 0), (-1, 0)) + while queue: + row, col = queue.popleft() + for sign, (dr, dc) in enumerate(directions, 1): + next_row, next_col = row + dr, col + dc + if not (0 <= next_row < rows and 0 <= next_col < cols): + continue + next_cost = distance[row][col] + (grid[row][col] != sign) + if next_cost < distance[next_row][next_col]: + distance[next_row][next_col] = next_cost + if grid[row][col] == sign: + queue.appendleft((next_row, next_col)) + else: + queue.append((next_row, next_col)) + return result == distance[rows - 1][cols - 1] +seed: 1368 +tests: + - name: example_one + in: + grid: + - [1, 1, 1, 1] + - [2, 2, 2, 2] + - [1, 1, 1, 1] + - [2, 2, 2, 2] + - name: example_two + in: + grid: + - [1, 1, 3] + - [3, 2, 2] + - [1, 1, 4] + - name: example_three + in: + grid: + - [1, 2] + - [4, 3] + - name: singleton_right + in: + grid: + - [1] + - name: singleton_up + in: + grid: + - [4] + - name: rightward_row + in: + grid: + - [1, 1, 1, 1, 1] + - name: leftward_row + in: + grid: + - [2, 2, 2, 2, 2] + - name: downward_column + in: + grid: + - [3] + - [3] + - [3] + - [3] + - [3] + - name: upward_column + in: + grid: + - [4] + - [4] + - [4] + - [4] + - [4] + - name: two_by_two_zero + in: + grid: + - [3, 2] + - [1, 4] + - name: two_by_two_all_wrong + in: + grid: + - [2, 4] + - [4, 4] + - name: horizontal_snake + in: + grid: + - [1, 1, 1, 3] + - [3, 2, 2, 2] + - [1, 1, 1, 3] + - [2, 2, 2, 2] + - name: vertical_snake + in: + grid: + - [3, 3, 3, 3] + - [4, 4, 4, 3] + - [3, 3, 3, 3] + - [4, 4, 4, 4] + - name: alternating_horizontal + in: + grid: + - [1, 2, 1, 2, 1] + - [2, 1, 2, 1, 2] + - [1, 2, 1, 2, 1] + - name: alternating_vertical + in: + grid: + - [3, 4, 3] + - [4, 3, 4] + - [3, 4, 3] + - [4, 3, 4] + - [3, 4, 3] + - name: directional_cycle + in: + grid: + - [1, 3, 2] + - [4, 2, 3] + - [1, 4, 2] + - name: edge_outside_arrows + in: + grid: + - [4, 4, 4, 4] + - [2, 1, 3, 1] + - [2, 4, 2, 1] + - [2, 2, 2, 3] + - name: choice_of_zero_cost_components + in: + grid: + - [1, 3, 2, 2] + - [4, 1, 3, 2] + - [1, 4, 1, 3] + - [4, 1, 4, 1] + - name: detour_beats_direct + in: + grid: + - [3, 2, 2, 2, 2] + - [1, 1, 1, 1, 3] + - [4, 4, 4, 4, 3] + - name: wide_mixed + in: + grid: + - [1, 3, 1, 2, 3, 1, 4] + - [3, 1, 2, 3, 4, 2, 2] + - name: tall_mixed + in: + grid: + - [3, 1] + - [4, 3] + - [1, 4] + - [3, 2] + - [4, 3] + - [1, 4] + - [3, 2] + - name: five_by_five_pattern + in: + grid: + - [1, 2, 3, 4, 1] + - [2, 3, 4, 1, 2] + - [3, 4, 1, 2, 3] + - [4, 1, 2, 3, 4] + - [1, 2, 3, 4, 1] + - name: six_by_six_clockwise_loops + in: + grid: + - [1, 1, 1, 1, 1, 3] + - [4, 1, 1, 1, 3, 3] + - [4, 4, 1, 3, 3, 3] + - [4, 4, 4, 2, 2, 3] + - [4, 4, 2, 2, 2, 3] + - [4, 2, 2, 2, 2, 2] + - name: six_by_four_asymmetric + in: + grid: + - [2, 3, 4, 1] + - [1, 4, 2, 3] + - [3, 2, 1, 4] + - [4, 1, 3, 2] + - [2, 4, 1, 3] + - [3, 1, 4, 2] + - name: seven_by_three_asymmetric + in: + grid: + - [1, 3, 2] + - [4, 2, 3] + - [3, 1, 4] + - [2, 4, 1] + - [1, 3, 2] + - [4, 1, 3] + - [3, 2, 4] + - name: eight_by_eight_diagonal_bias + in: + grid: + - [3, 1, 1, 1, 1, 1, 1, 1] + - [4, 3, 1, 1, 1, 1, 1, 1] + - [4, 4, 3, 1, 1, 1, 1, 1] + - [4, 4, 4, 3, 1, 1, 1, 1] + - [4, 4, 4, 4, 3, 1, 1, 1] + - [4, 4, 4, 4, 4, 3, 1, 1] + - [4, 4, 4, 4, 4, 4, 3, 1] + - [4, 4, 4, 4, 4, 4, 4, 1] + - name: ten_by_ten_mixed + in: + grid: + - [1, 2, 3, 4, 1, 2, 3, 4, 1, 2] + - [2, 3, 4, 1, 2, 3, 4, 1, 2, 3] + - [3, 4, 1, 2, 3, 4, 1, 2, 3, 4] + - [4, 1, 2, 3, 4, 1, 2, 3, 4, 1] + - [1, 2, 3, 4, 1, 2, 3, 4, 1, 2] + - [2, 3, 4, 1, 2, 3, 4, 1, 2, 3] + - [3, 4, 1, 2, 3, 4, 1, 2, 3, 4] + - [4, 1, 2, 3, 4, 1, 2, 3, 4, 1] + - [1, 2, 3, 4, 1, 2, 3, 4, 1, 2] + - [2, 3, 4, 1, 2, 3, 4, 1, 2, 3] + - name: zero_cost_zigzag + in: + grid: + - [3, 2, 2, 2, 2] + - [1, 1, 1, 1, 3] + - [3, 2, 2, 2, 2] + - [1, 1, 1, 1, 3] + - [4, 4, 4, 4, 4] + - name: competing_short_paths + in: + grid: + - [1, 3, 2, 3, 2] + - [4, 1, 3, 1, 3] + - [3, 4, 1, 2, 3] + - [1, 3, 4, 1, 3] + - [4, 1, 1, 1, 4] + - name: max_width_rightward + 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, + ] + - name: max_width_leftward + 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, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + ] + - name: max_height_downward + 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] + - [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] + - [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] + - name: max_height_upward + 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] + - [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] + - [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] + - [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] + - [4] + - name: nine_by_nine_perimeter_route + in: + grid: + - [1, 1, 1, 1, 1, 1, 1, 1, 3] + - [4, 2, 2, 2, 2, 2, 2, 2, 3] + - [4, 2, 1, 1, 1, 1, 1, 2, 3] + - [4, 2, 1, 4, 4, 4, 1, 2, 3] + - [4, 2, 1, 4, 2, 4, 1, 2, 3] + - [4, 2, 1, 4, 4, 4, 1, 2, 3] + - [4, 2, 1, 1, 1, 1, 1, 2, 3] + - [4, 2, 2, 2, 2, 2, 2, 2, 3] + - [4, 4, 4, 4, 4, 4, 4, 4, 1] + - name: nine_by_nine_reverse_perimeter + in: + grid: + - [3, 2, 2, 2, 2, 2, 2, 2, 2] + - [3, 1, 1, 1, 1, 1, 1, 1, 4] + - [3, 1, 3, 3, 3, 3, 3, 1, 4] + - [3, 1, 3, 2, 2, 2, 3, 1, 4] + - [3, 1, 3, 2, 4, 2, 3, 1, 4] + - [3, 1, 3, 2, 2, 2, 3, 1, 4] + - [3, 1, 3, 3, 3, 3, 3, 1, 4] + - [3, 1, 1, 1, 1, 1, 1, 1, 4] + - [1, 1, 1, 1, 1, 1, 1, 1, 1] + - name: generated_max_square_a + seed: 136801 + in: + grid: + gen: "array" + len: 100 + of: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 4 + - name: generated_max_square_b + seed: 136802 + in: + grid: + gen: "array" + len: 100 + of: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 4 + - name: generated_max_square_c + seed: 136803 + in: + grid: + gen: "array" + len: 100 + of: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 4 + - name: generated_max_square_d + seed: 136804 + in: + grid: + gen: "array" + len: 100 + of: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 4 + - name: generated_max_square_e + seed: 136805 + in: + grid: + gen: "array" + len: 100 + of: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 4 diff --git a/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.cpp b/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.cpp new file mode 100644 index 00000000..3e0ce9c6 --- /dev/null +++ b/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + int minCost(vector>& grid) { + int m = grid.size(); + int n = grid[0].size(); + vector> minCost(m, vector(n, INT_MAX)); + minCost[0][0] = 0; + + deque> dq; + dq.push_front({0, 0}); + + vector> directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + + while (!dq.empty()) { + auto [r, c] = dq.front(); + dq.pop_front(); + + for (int i = 0; i < 4; i++) { + int nr = r + directions[i].first; + int nc = c + directions[i].second; + int cost = (grid[r][c] != i + 1) ? 1 : 0; + + if (nr >= 0 && nr < m && nc >= 0 && nc < n && minCost[r][c] + cost < minCost[nr][nc]) { + minCost[nr][nc] = minCost[r][c] + cost; + + if (cost == 1) { + dq.push_back({nr, nc}); + } else { + dq.push_front({nr, nc}); + } + } + } + } + + return minCost[m - 1][n - 1]; + } +}; diff --git a/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.cs b/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.cs new file mode 100644 index 00000000..55b4453f --- /dev/null +++ b/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.cs @@ -0,0 +1,45 @@ +public class Solution { + public int MinCost(int[][] grid) { + int m = grid.Length; + int n = grid[0].Length; + int[][] minCost = new int[m][]; + for (int i = 0; i < m; i++) { + minCost[i] = new int[n]; + Array.Fill(minCost[i], int.MaxValue); + } + minCost[0][0] = 0; + + var deque = new LinkedList<(int, int)>(); + deque.AddFirst((0, 0)); + + int[][] directions = new int[][] { + new int[] {0, 1}, + new int[] {0, -1}, + new int[] {1, 0}, + new int[] {-1, 0} + }; + + while (deque.Count > 0) { + var (r, c) = deque.First.Value; + deque.RemoveFirst(); + + for (int i = 0; i < 4; i++) { + int nr = r + directions[i][0]; + int nc = c + directions[i][1]; + int cost = (grid[r][c] != i + 1) ? 1 : 0; + + if (nr >= 0 && nr < m && nc >= 0 && nc < n && minCost[r][c] + cost < minCost[nr][nc]) { + minCost[nr][nc] = minCost[r][c] + cost; + + if (cost == 1) { + deque.AddLast((nr, nc)); + } else { + deque.AddFirst((nr, nc)); + } + } + } + } + + return minCost[m - 1][n - 1]; + } +} diff --git a/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.dart b/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.dart new file mode 100644 index 00000000..9b0461dc --- /dev/null +++ b/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.dart @@ -0,0 +1,42 @@ +class Solution { + int minCost(List> grid) { + int m = grid.length; + int n = grid[0].length; + List> minCost = List.generate(m, (_) => List.filled(n, 1 << 30)); + minCost[0][0] = 0; + + List> queue = []; + queue.add([0, 0]); + + List> directions = [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0] + ]; + + while (queue.isNotEmpty) { + List curr = queue.removeAt(0); + int r = curr[0]; + int c = curr[1]; + + for (int i = 0; i < 4; i++) { + int nr = r + directions[i][0]; + int nc = c + directions[i][1]; + int cost = (grid[r][c] != i + 1) ? 1 : 0; + + if (nr >= 0 && nr < m && nc >= 0 && nc < n && minCost[r][c] + cost < minCost[nr][nc]) { + minCost[nr][nc] = minCost[r][c] + cost; + + if (cost == 1) { + queue.add([nr, nc]); + } else { + queue.insert(0, [nr, nc]); + } + } + } + } + + return minCost[m - 1][n - 1]; + } +} diff --git a/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.go b/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.go new file mode 100644 index 00000000..5af2a2ca --- /dev/null +++ b/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.go @@ -0,0 +1,44 @@ +func minCost(grid [][]int) int { + m := len(grid) + n := len(grid[0]) + minCost := make([][]int, m) + for i := range minCost { + minCost[i] = make([]int, n) + for j := range minCost[i] { + minCost[i][j] = int(^uint(0) >> 1) + } + } + minCost[0][0] = 0 + + type pair struct{ r, c int } + var deque []pair + deque = append(deque, pair{0, 0}) + + directions := [][]int{{0, 1}, {0, -1}, {1, 0}, {-1, 0}} + + for len(deque) > 0 { + curr := deque[0] + deque = deque[1:] + r, c := curr.r, curr.c + + for i, dir := range directions { + nr, nc := r+dir[0], c+dir[1] + cost := 1 + if grid[r][c] == i+1 { + cost = 0 + } + + if nr >= 0 && nr < m && nc >= 0 && nc < n && minCost[r][c]+cost < minCost[nr][nc] { + minCost[nr][nc] = minCost[r][c] + cost + + if cost == 1 { + deque = append(deque, pair{nr, nc}) + } else { + deque = append([]pair{{nr, nc}}, deque...) + } + } + } + } + + return minCost[m-1][n-1] +} diff --git a/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.java b/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.java new file mode 100644 index 00000000..d8126c09 --- /dev/null +++ b/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.java @@ -0,0 +1,42 @@ +class Solution { + public int minCost(int[][] grid) { + int m = grid.length; + int n = grid[0].length; + int[][] minCost = new int[m][n]; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + minCost[i][j] = Integer.MAX_VALUE; + } + } + minCost[0][0] = 0; + + java.util.Deque deque = new java.util.ArrayDeque<>(); + deque.offerFirst(new int[]{0, 0}); + + int[][] directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + + while (!deque.isEmpty()) { + int[] curr = deque.pollFirst(); + int r = curr[0]; + int c = curr[1]; + + for (int i = 0; i < 4; i++) { + int nr = r + directions[i][0]; + int nc = c + directions[i][1]; + int cost = (grid[r][c] != i + 1) ? 1 : 0; + + if (nr >= 0 && nr < m && nc >= 0 && nc < n && minCost[r][c] + cost < minCost[nr][nc]) { + minCost[nr][nc] = minCost[r][c] + cost; + + if (cost == 1) { + deque.offerLast(new int[]{nr, nc}); + } else { + deque.offerFirst(new int[]{nr, nc}); + } + } + } + } + + return minCost[m - 1][n - 1]; + } +} diff --git a/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.kt b/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.kt new file mode 100644 index 00000000..11098254 --- /dev/null +++ b/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.kt @@ -0,0 +1,40 @@ +class Solution { + fun minCost(grid: Array): Int { + val m = grid.size + val n = grid[0].size + val minCost = Array(m) { IntArray(n) { Int.MAX_VALUE } } + minCost[0][0] = 0 + + val deque = java.util.ArrayDeque>() + deque.offerFirst(Pair(0, 0)) + + val directions = arrayOf( + intArrayOf(0, 1), + intArrayOf(0, -1), + intArrayOf(1, 0), + intArrayOf(-1, 0) + ) + + while (!deque.isEmpty()) { + val (r, c) = deque.pollFirst() + + for (i in directions.indices) { + val nr = r + directions[i][0] + val nc = c + directions[i][1] + val cost = if (grid[r][c] != i + 1) 1 else 0 + + if (nr in 0 until m && nc in 0 until n && minCost[r][c] + cost < minCost[nr][nc]) { + minCost[nr][nc] = minCost[r][c] + cost + + if (cost == 1) { + deque.offerLast(Pair(nr, nc)) + } else { + deque.offerFirst(Pair(nr, nc)) + } + } + } + } + + return minCost[m - 1][n - 1] + } +} diff --git a/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.py b/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.py new file mode 100644 index 00000000..4bf4f2f0 --- /dev/null +++ b/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.py @@ -0,0 +1,43 @@ +from collections import deque + + +class Solution(object): + def minCost(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + m, n = len(grid), len(grid[0]) + # Initialize the minCost matrix with a large value + minCost = [[float("inf")] * n for _ in range(m)] + minCost[0][0] = 0 + + # Deque for 0-1 BFS + dque = deque([(0, 0)]) + + # Directions: right, left, down, up + directions = [(0, 1), (0, -1), (1, 0), (-1, 0)] + + while dque: + r, c = dque.popleft() + + # Visit adjacent cells + for i, (dr, dc) in enumerate(directions): + nr, nc = r + dr, c + dc + cost = 1 if grid[r][c] != i + 1 else 0 + + if ( + 0 <= nr < m + and 0 <= nc < n + and minCost[r][c] + cost < minCost[nr][nc] + ): + minCost[nr][nc] = minCost[r][c] + cost + + # Add to deque based on cost + if cost == 1: + dque.append((nr, nc)) + else: + dque.appendleft((nr, nc)) + + # Return the minimum cost to reach the bottom-right corner + return minCost[m - 1][n - 1] diff --git a/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.py2 b/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.py2 new file mode 100644 index 00000000..8fef8d27 --- /dev/null +++ b/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.py2 @@ -0,0 +1,38 @@ +from collections import deque + +class Solution(object): + def minCost(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + m, n = len(grid), len(grid[0]) + # Initialize the minCost matrix with a large value + minCost = [[float('inf')] * n for _ in range(m)] + minCost[0][0] = 0 + + # Deque for 0-1 BFS + dque = deque([(0, 0)]) + + # Directions: right, left, down, up + directions = [(0, 1), (0, -1), (1, 0), (-1, 0)] + + while dque: + r, c = dque.popleft() + + # Visit adjacent cells + for i, (dr, dc) in enumerate(directions): + nr, nc = r + dr, c + dc + cost = 1 if grid[r][c] != i + 1 else 0 + + if 0 <= nr < m and 0 <= nc < n and minCost[r][c] + cost < minCost[nr][nc]: + minCost[nr][nc] = minCost[r][c] + cost + + # Add to deque based on cost + if cost == 1: + dque.append((nr, nc)) + else: + dque.appendleft((nr, nc)) + + # Return the minimum cost to reach the bottom-right corner + return minCost[m - 1][n - 1] diff --git a/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.rb b/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.rb new file mode 100644 index 00000000..a439284e --- /dev/null +++ b/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.rb @@ -0,0 +1,39 @@ +# @param {Integer[][]} grid +# @return {Integer} +def min_cost(grid) + m = grid.length + n = grid[0].length + min_cost = Array.new(m) { Array.new(n, Float::INFINITY) } + min_cost[0][0] = 0 + + deque = [[0, 0]] + + directions = [ + [0, 1], # right + [0, -1], # left + [1, 0], # down + [-1, 0] # up + ] + + while !deque.empty? + r, c = deque.shift + + directions.each_with_index do |(dr, dc), i| + nr = r + dr + nc = c + dc + cost = (grid[r][c] != i + 1) ? 1 : 0 + + if nr >= 0 && nr < m && nc >= 0 && nc < n && min_cost[r][c] + cost < min_cost[nr][nc] + min_cost[nr][nc] = min_cost[r][c] + cost + + if cost == 1 + deque.push([nr, nc]) + else + deque.unshift([nr, nc]) + end + end + end + end + + min_cost[m - 1][n - 1] +end diff --git a/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.rs b/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.rs new file mode 100644 index 00000000..2481f135 --- /dev/null +++ b/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.rs @@ -0,0 +1,39 @@ +impl Solution { + pub fn min_cost(grid: Vec>) -> i32 { + use std::collections::VecDeque; + + let m = grid.len(); + let n = grid[0].len(); + let mut min_cost = vec![vec![i32::MAX; n]; m]; + min_cost[0][0] = 0; + + let mut deque = VecDeque::new(); + deque.push_back((0, 0)); + + let directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]; + + while let Some((r, c)) = deque.pop_front() { + for (i, &(dr, dc)) in directions.iter().enumerate() { + let nr = r as i32 + dr; + let nc = c as i32 + dc; + let cost = if grid[r][c] != (i + 1) as i32 { 1 } else { 0 }; + + if nr >= 0 && nr < m as i32 && nc >= 0 && nc < n as i32 { + let nr = nr as usize; + let nc = nc as usize; + if min_cost[r][c] + cost < min_cost[nr][nc] { + min_cost[nr][nc] = min_cost[r][c] + cost; + + if cost == 1 { + deque.push_back((nr, nc)); + } else { + deque.push_front((nr, nc)); + } + } + } + } + } + + min_cost[m - 1][n - 1] + } +} diff --git a/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.swift b/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.swift new file mode 100644 index 00000000..06176ec9 --- /dev/null +++ b/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.swift @@ -0,0 +1,34 @@ +class Solution { + func minCost(_ grid: [[Int]]) -> Int { + let m = grid.count + let n = grid[0].count + var minCost = Array(repeating: Array(repeating: Int.max, count: n), count: m) + minCost[0][0] = 0 + + var deque: [(Int, Int)] = [(0, 0)] + + let directions = [(0, 1), (0, -1), (1, 0), (-1, 0)] + + while !deque.isEmpty { + let (r, c) = deque.removeFirst() + + for (i, (dr, dc)) in directions.enumerated() { + let nr = r + dr + let nc = c + dc + let cost = (grid[r][c] != i + 1) ? 1 : 0 + + if nr >= 0 && nr < m && nc >= 0 && nc < n && minCost[r][c] + cost < minCost[nr][nc] { + minCost[nr][nc] = minCost[r][c] + cost + + if cost == 1 { + deque.append((nr, nc)) + } else { + deque.insert((nr, nc), at: 0) + } + } + } + } + + return minCost[m - 1][n - 1] + } +} diff --git a/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.ts b/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.ts new file mode 100644 index 00000000..0e54127d --- /dev/null +++ b/tests/1001-1500/1368. minimum-cost-to-make-at-least-one-valid-path-in-a-grid/sol.ts @@ -0,0 +1,45 @@ +function minCost(grid: number[][]): number { + const m = grid.length; + const n = grid[0].length; + const minCost: number[][] = Array.from({ length: m }, () => + Array(n).fill(Infinity), + ); + minCost[0][0] = 0; + + const deque: [number, number][] = [[0, 0]]; + + const directions: [number, number][] = [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + ]; + + while (deque.length > 0) { + const [r, c] = deque.shift()!; + + for (let i = 0; i < 4; i++) { + const nr = r + directions[i][0]; + const nc = c + directions[i][1]; + const cost = grid[r][c] !== i + 1 ? 1 : 0; + + if ( + nr >= 0 && + nr < m && + nc >= 0 && + nc < n && + minCost[r][c] + cost < minCost[nr][nc] + ) { + minCost[nr][nc] = minCost[r][c] + cost; + + if (cost === 1) { + deque.push([nr, nc]); + } else { + deque.unshift([nr, nc]); + } + } + } + } + + return minCost[m - 1][n - 1]; +} diff --git a/tests/1001-1500/1370. increasing-decreasing-string/manifest.yaml b/tests/1001-1500/1370. increasing-decreasing-string/manifest.yaml new file mode 100644 index 00000000..da9100ce --- /dev/null +++ b/tests/1001-1500/1370. increasing-decreasing-string/manifest.yaml @@ -0,0 +1,241 @@ +entry: + id: 1370 + title: increasing-decreasing-string + params: + s: + type: string + call: + cpp: "Solution().sortString({s})" + rust: "Solution::sort_string({s})" + python3: "Solution().sortString({s})" + python2: "Solution().sortString({s})" + ruby: "sort_string({s})" + java: "new Solution().sortString({s})" + csharp: "new Solution().SortString({s})" + kotlin: "Solution().sortString({s})" + go: "sortString({s})" + dart: "Solution().sortString({s})" + swift: "Solution().sortString({s})" + typescript: "sortString({s})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().sortString(s, {result})" + checker: | + class Checker: + def sortString(self, s, result): + if not isinstance(result, str) or len(result) != len(s): + return False + remaining = [0] * 26 + for ch in s: + remaining[ord(ch) - ord('a')] += 1 + expected = [] + while any(remaining): + for index in range(26): + if remaining[index]: + expected.append(chr(ord('a') + index)) + remaining[index] -= 1 + for index in range(25, -1, -1): + if remaining[index]: + expected.append(chr(ord('a') + index)) + remaining[index] -= 1 + return result == ''.join(expected) + +seed: 1370 + +tests: + - name: "example_four_blocks" + in: + s: "aaaabbbbcccc" + + - name: "example_three_distinct" + in: + s: "rat" + + - name: "single_a" + in: + s: "a" + + - name: "single_z" + in: + s: "z" + + - name: "two_reversed" + in: + s: "ba" + + - name: "two_equal" + in: + s: "aa" + + - name: "one_full_alphabet" + in: + s: "abcdefghijklmnopqrstuvwxyz" + + - name: "full_alphabet_reversed" + in: + s: "zyxwvutsrqponmlkjihgfedcba" + + - name: "two_pairs" + in: + s: "aabb" + + - name: "three_equal_groups" + in: + s: "aaabbbccc" + + - name: "two_letters_many_rounds" + in: + s: "abababab" + + - name: "repeated_vowels" + in: + s: "aeiouaeiou" + + - name: "distinct_consonants" + in: + s: "bcdfghjklmnpqrstvwxyz" + + - name: "descending_runs" + in: + s: "fedcbafedcba" + + - name: "smallest_heavy" + in: + s: "aaaaabc" + + - name: "largest_heavy" + in: + s: "zzzyx" + + - name: "sparse_range" + in: + s: "azbycxdw" + + - name: "already_symmetric" + in: + s: "abccba" + + - name: "banana" + in: + s: "banana" + + - name: "mississippi" + in: + s: "mississippi" + + - name: "uneven_frequencies" + in: + s: "aaabccdddd" + + - name: "six_equal_pairs" + in: + s: "aabbccddeeff" + + - name: "vowels_with_uneven_counts" + in: + s: "aaaeeeiiiooouuu" + + - name: "alphabet_doubled" + in: + s: "aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz" + + - name: "endpoint_alternation" + in: + s: "azazazaz" + + - name: "middle_letter_heavy" + in: + s: "mmmmabcmmm" + + - name: "irregular_six_letters" + in: + s: "fdbacedefabc" + + - name: "rising_multiplicities" + in: + s: "aabbbcccccdddddd" + + - name: "ascending_periods" + in: + s: "abcabcabcabcabc" + + - name: "descending_periods" + in: + s: "zyxzyxzyxzyx" + + - name: "near_alphabet" + in: + s: "abczxyabcxyz" + + - name: "phrase_like_mix" + in: + s: "thequickbrownfox" + + - name: "leetcode_word" + in: + s: "leetcode" + + - name: "programming_word" + in: + s: "programming" + + - name: "three_full_passes" + in: + s: "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" + + - name: "generated_short_binary" + seed: 1371 + in: + s: + gen: "str" + len: + gen: "int" + min: 1 + max: 12 + alphabet: "az" + + - name: "generated_small_alphabet" + seed: 1372 + in: + s: + gen: "str" + len: + gen: "int" + min: 13 + max: 60 + alphabet: "abcde" + + - name: "generated_full_alphabet" + seed: 1373 + in: + s: + gen: "str" + len: + gen: "int" + min: 61 + max: 200 + alphabet: "abcdefghijklmnopqrstuvwxyz" + + - name: "generated_maximum_binary" + seed: 1374 + in: + s: + gen: "str" + len: 500 + alphabet: "az" + + - name: "generated_maximum_full_alphabet" + seed: 1375 + in: + s: + gen: "str" + len: 500 + alphabet: "abcdefghijklmnopqrstuvwxyz" diff --git a/tests/1001-1500/1370. increasing-decreasing-string/sol.cpp b/tests/1001-1500/1370. increasing-decreasing-string/sol.cpp new file mode 100644 index 00000000..825810ba --- /dev/null +++ b/tests/1001-1500/1370. increasing-decreasing-string/sol.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + string sortString(string s) { + if (s.empty()) return ""; + int counts[26] = {0}; + for (char c : s) { + counts[c - 'a']++; + } + string ans; + bool added; + do { + added = false; + for (int i = 0; i < 26; i++) { + if (counts[i] > 0) { + ans += (char)('a' + i); + counts[i]--; + added = true; + } + } + for (int i = 25; i >= 0; i--) { + if (counts[i] > 0) { + ans += (char)('a' + i); + counts[i]--; + added = true; + } + } + } while (added); + return ans; + } +}; diff --git a/tests/1001-1500/1370. increasing-decreasing-string/sol.cs b/tests/1001-1500/1370. increasing-decreasing-string/sol.cs new file mode 100644 index 00000000..0db3031a --- /dev/null +++ b/tests/1001-1500/1370. increasing-decreasing-string/sol.cs @@ -0,0 +1,29 @@ +public class Solution { + public string SortString(string s) { + if (string.IsNullOrEmpty(s)) return ""; + int[] counts = new int[26]; + foreach (char c in s) { + counts[c - 'a']++; + } + System.Text.StringBuilder ans = new System.Text.StringBuilder(); + bool added; + do { + added = false; + for (int i = 0; i < 26; i++) { + if (counts[i] > 0) { + ans.Append((char)('a' + i)); + counts[i]--; + added = true; + } + } + for (int i = 25; i >= 0; i--) { + if (counts[i] > 0) { + ans.Append((char)('a' + i)); + counts[i]--; + added = true; + } + } + } while (added); + return ans.ToString(); + } +} diff --git a/tests/1001-1500/1370. increasing-decreasing-string/sol.dart b/tests/1001-1500/1370. increasing-decreasing-string/sol.dart new file mode 100644 index 00000000..b2619965 --- /dev/null +++ b/tests/1001-1500/1370. increasing-decreasing-string/sol.dart @@ -0,0 +1,29 @@ +class Solution { + String sortString(String s) { + if (s.isEmpty) return ""; + List counts = List.filled(26, 0); + for (int i = 0; i < s.length; i++) { + counts[s.codeUnitAt(i) - 'a'.codeUnitAt(0)]++; + } + StringBuffer ans = StringBuffer(); + bool added; + do { + added = false; + for (int i = 0; i < 26; i++) { + if (counts[i] > 0) { + ans.writeCharCode('a'.codeUnitAt(0) + i); + counts[i]--; + added = true; + } + } + for (int i = 25; i >= 0; i--) { + if (counts[i] > 0) { + ans.writeCharCode('a'.codeUnitAt(0) + i); + counts[i]--; + added = true; + } + } + } while (added); + return ans.toString(); + } +} diff --git a/tests/1001-1500/1370. increasing-decreasing-string/sol.go b/tests/1001-1500/1370. increasing-decreasing-string/sol.go new file mode 100644 index 00000000..3788500b --- /dev/null +++ b/tests/1001-1500/1370. increasing-decreasing-string/sol.go @@ -0,0 +1,31 @@ +func sortString(s string) string { + if len(s) == 0 { + return "" + } + counts := make([]int, 26) + for _, c := range s { + counts[c-'a']++ + } + ans := "" + for { + added := false + for i := 0; i < 26; i++ { + if counts[i] > 0 { + ans += string(rune('a' + i)) + counts[i]-- + added = true + } + } + for i := 25; i >= 0; i-- { + if counts[i] > 0 { + ans += string(rune('a' + i)) + counts[i]-- + added = true + } + } + if !added { + break + } + } + return ans +} diff --git a/tests/1001-1500/1370. increasing-decreasing-string/sol.java b/tests/1001-1500/1370. increasing-decreasing-string/sol.java new file mode 100644 index 00000000..35c22059 --- /dev/null +++ b/tests/1001-1500/1370. increasing-decreasing-string/sol.java @@ -0,0 +1,29 @@ +class Solution { + public String sortString(String s) { + if (s.isEmpty()) return ""; + int[] counts = new int[26]; + for (char c : s.toCharArray()) { + counts[c - 'a']++; + } + StringBuilder ans = new StringBuilder(); + boolean added; + do { + added = false; + for (int i = 0; i < 26; i++) { + if (counts[i] > 0) { + ans.append((char) ('a' + i)); + counts[i]--; + added = true; + } + } + for (int i = 25; i >= 0; i--) { + if (counts[i] > 0) { + ans.append((char) ('a' + i)); + counts[i]--; + added = true; + } + } + } while (added); + return ans.toString(); + } +} diff --git a/tests/1001-1500/1370. increasing-decreasing-string/sol.kt b/tests/1001-1500/1370. increasing-decreasing-string/sol.kt new file mode 100644 index 00000000..7f703f90 --- /dev/null +++ b/tests/1001-1500/1370. increasing-decreasing-string/sol.kt @@ -0,0 +1,29 @@ +class Solution { + fun sortString(s: String): String { + if (s.isEmpty()) return "" + val counts = IntArray(26) + for (c in s) { + counts[c - 'a']++ + } + val ans = StringBuilder() + var added: Boolean + do { + added = false + for (i in 0..25) { + if (counts[i] > 0) { + ans.append('a' + i) + counts[i]-- + added = true + } + } + for (i in 25 downTo 0) { + if (counts[i] > 0) { + ans.append('a' + i) + counts[i]-- + added = true + } + } + } while (added) + return ans.toString() + } +} diff --git a/tests/1001-1500/1370. increasing-decreasing-string/sol.py b/tests/1001-1500/1370. increasing-decreasing-string/sol.py new file mode 100644 index 00000000..41c9b06f --- /dev/null +++ b/tests/1001-1500/1370. increasing-decreasing-string/sol.py @@ -0,0 +1,21 @@ +from collections import Counter + + +class Solution: + def sortString(self, s: str) -> str: + if not s: + return "" + counts = Counter(s) + keys = list(counts.keys()) + keys.sort(key=lambda x: ord(x)) + ans = "" + while max(counts.values()) > 0: + for key in keys: + if counts[key] > 0: + ans += key + counts[key] -= 1 + for key in reversed(keys): + if counts[key] > 0: + ans += key + counts[key] -= 1 + return ans diff --git a/tests/1001-1500/1370. increasing-decreasing-string/sol.py2 b/tests/1001-1500/1370. increasing-decreasing-string/sol.py2 new file mode 100644 index 00000000..f43881e2 --- /dev/null +++ b/tests/1001-1500/1370. increasing-decreasing-string/sol.py2 @@ -0,0 +1,22 @@ +class Solution(object): + def sortString(self, s): + """ + :type s: str + :rtype: str + """ + if not s: + return "" + from collections import Counter + counts = Counter(s) + keys = sorted(counts.keys(), key=lambda x: ord(x)) + ans = "" + while max(counts.values()) > 0: + for key in keys: + if counts[key] > 0: + ans += key + counts[key] -= 1 + for key in reversed(keys): + if counts[key] > 0: + ans += key + counts[key] -= 1 + return ans diff --git a/tests/1001-1500/1370. increasing-decreasing-string/sol.rb b/tests/1001-1500/1370. increasing-decreasing-string/sol.rb new file mode 100644 index 00000000..41cbaa6a --- /dev/null +++ b/tests/1001-1500/1370. increasing-decreasing-string/sol.rb @@ -0,0 +1,24 @@ +# @param {String} s +# @return {String} +def sort_string(s) + return "" if s.empty? + counts = Hash.new(0) + s.each_char { |c| counts[c] += 1 } + keys = counts.keys.sort_by { |x| x.ord } + ans = "" + while counts.values.max > 0 + keys.each do |key| + if counts[key] > 0 + ans += key + counts[key] -= 1 + end + end + keys.reverse_each do |key| + if counts[key] > 0 + ans += key + counts[key] -= 1 + end + end + end + ans +end diff --git a/tests/1001-1500/1370. increasing-decreasing-string/sol.rs b/tests/1001-1500/1370. increasing-decreasing-string/sol.rs new file mode 100644 index 00000000..677c9746 --- /dev/null +++ b/tests/1001-1500/1370. increasing-decreasing-string/sol.rs @@ -0,0 +1,33 @@ +impl Solution { + pub fn sort_string(s: String) -> String { + if s.is_empty() { + return String::new(); + } + let mut counts = [0u32; 26]; + for c in s.chars() { + counts[(c as usize) - ('a' as usize)] += 1; + } + let mut ans = String::new(); + loop { + let mut added = false; + for i in 0..26 { + if counts[i] > 0 { + ans.push((b'a' + i as u8) as char); + counts[i] -= 1; + added = true; + } + } + for i in (0..26).rev() { + if counts[i] > 0 { + ans.push((b'a' + i as u8) as char); + counts[i] -= 1; + added = true; + } + } + if !added { + break; + } + } + ans + } +} diff --git a/tests/1001-1500/1370. increasing-decreasing-string/sol.swift b/tests/1001-1500/1370. increasing-decreasing-string/sol.swift new file mode 100644 index 00000000..03920948 --- /dev/null +++ b/tests/1001-1500/1370. increasing-decreasing-string/sol.swift @@ -0,0 +1,29 @@ +class Solution { + func sortString(_ s: String) -> String { + if s.isEmpty { return "" } + var counts = [Int](repeating: 0, count: 26) + for c in s { + counts[Int(c.asciiValue! - 97)] += 1 + } + var ans = "" + var added = true + while added { + added = false + for i in 0..<26 { + if counts[i] > 0 { + ans.append(Character(UnicodeScalar(i + 97)!)) + counts[i] -= 1 + added = true + } + } + for i in (0..<26).reversed() { + if counts[i] > 0 { + ans.append(Character(UnicodeScalar(i + 97)!)) + counts[i] -= 1 + added = true + } + } + } + return ans + } +} diff --git a/tests/1001-1500/1370. increasing-decreasing-string/sol.ts b/tests/1001-1500/1370. increasing-decreasing-string/sol.ts new file mode 100644 index 00000000..3b2da6b6 --- /dev/null +++ b/tests/1001-1500/1370. increasing-decreasing-string/sol.ts @@ -0,0 +1,27 @@ +function sortString(s: string): string { + if (s.length === 0) return ""; + const counts: number[] = new Array(26).fill(0); + for (const c of s) { + counts[c.charCodeAt(0) - 97]++; + } + let ans = ""; + let added: boolean; + do { + added = false; + for (let i = 0; i < 26; i++) { + if (counts[i] > 0) { + ans += String.fromCharCode(97 + i); + counts[i]--; + added = true; + } + } + for (let i = 25; i >= 0; i--) { + if (counts[i] > 0) { + ans += String.fromCharCode(97 + i); + counts[i]--; + added = true; + } + } + } while (added); + return ans; +} diff --git a/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/manifest.yaml b/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/manifest.yaml new file mode 100644 index 00000000..a59b859b --- /dev/null +++ b/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/manifest.yaml @@ -0,0 +1,203 @@ +entry: + id: 1371 + title: "find-the-longest-substring-containing-vowels-in-even-counts" + params: + s: + type: string + call: + cpp: "Solution().findTheLongestSubstring({s})" + rust: "Solution::find_the_longest_substring({s})" + python3: "Solution().findTheLongestSubstring({s})" + python2: "Solution().findTheLongestSubstring({s})" + ruby: "find_the_longest_substring({s})" + java: "new Solution().findTheLongestSubstring({s})" + csharp: "new Solution().FindTheLongestSubstring({s})" + kotlin: "Solution().findTheLongestSubstring({s})" + go: "findTheLongestSubstring({s})" + dart: "Solution().findTheLongestSubstring({s})" + swift: "Solution().findTheLongestSubstring({s})" + typescript: "findTheLongestSubstring({s})" +judge: + type: "exact" +limits: + time_ms: 2000 + memory_mb: 300 +oracle: + python3: + call: "Checker().findTheLongestSubstring(s, {result})" + checker: | + class Checker: + def findTheLongestSubstring(self, s, result): + if isinstance(result, bool) or not isinstance(result, int): + return False + if result < 0 or result > len(s): + return False + vowel_index = {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4} + prefix_masks = [0] + for char in s: + next_mask = prefix_masks[-1] + if char in vowel_index: + next_mask ^= 1 << vowel_index[char] + prefix_masks.append(next_mask) + earliest = {} + expected = 0 + for end, mask in enumerate(prefix_masks): + if mask not in earliest: + earliest[mask] = end + else: + expected = max(expected, end - earliest[mask]) + return result == expected +seed: 1371 +tests: + - name: "example_one" + in: + s: "eleetminicoworoep" + - name: "example_two" + in: + s: "leetcodeisgreat" + - name: "example_three" + in: + s: "bcbcbc" + - name: "single_consonant" + in: + s: "z" + - name: "single_vowel" + in: + s: "a" + - name: "double_same_vowel" + in: + s: "aa" + - name: "two_distinct_vowels" + in: + s: "ae" + - name: "all_vowels_once" + in: + s: "aeiou" + - name: "all_vowels_twice" + in: + s: "aeiouaeiou" + - name: "consonants_only_alphabet" + in: + s: "bcdfghjklmnpqrstvwxyz" + - name: "odd_run_of_one_vowel" + in: + s: "aaaaaaaaa" + - name: "even_run_of_one_vowel" + in: + s: "aaaaaaaa" + - name: "vowels_at_both_ends" + in: + s: "abca" + - name: "best_strictly_inside" + in: + s: "aabbcde" + - name: "alternating_a_with_consonants" + in: + s: "abababab" + - name: "alternating_two_vowels" + in: + s: "aeaeaeae" + - name: "interleaved_all_vowels" + in: + s: "abecidofughaeiou" + - name: "first_mask_repeated_late" + in: + s: "abecidofughajklmnopqrstuvwxyza" + - name: "prefix_must_be_discarded" + in: + s: "aebcde" + - name: "suffix_must_be_selected" + in: + s: "aebcd" + - name: "repeated_mask_not_latest" + in: + s: "aebeaeb" + - name: "mixed_word_abracadabra" + in: + s: "abracadabra" + - name: "mixed_word_education" + in: + s: "education" + - name: "pangram" + in: + s: "thequickbrownfoxjumpsoverthelazydog" + - name: "vowel_pairs_with_gaps" + in: + s: "axexixoxuuaeio" + - name: "all_five_odd_with_tail" + in: + s: "bcdaeiouxyz" + - name: "dense_repeated_vowels" + in: + s: "aeiouuoiea" + - name: "long_consonant_middle" + in: + s: "aeioubcdfghjklmnpqrstvwxyzaeiou" + - name: "multiple_candidate_windows" + in: + s: "aebicodufaeioubcdef" + - name: "late_full_length_balance" + in: + s: "zaeioubcdfghaeiouz" + - name: "single_internal_even_pair" + in: + s: "zaaz" + - name: "all_vowels_odd_except_one_pair" + in: + s: "baeiaouu" + - name: "generated_small_uniform" + seed: 11 + in: + s: + gen: "str" + len: 31 + alphabet: "aeiou" + - name: "generated_small_mixed" + seed: 22 + in: + s: + gen: "str" + len: 127 + alphabet: "aeioubcdxyz" + - name: "generated_medium_alphabet" + seed: 33 + in: + s: + gen: "str" + len: 4096 + alphabet: "abcdefghijklmnopqrstuvwxyz" + - name: "generated_vowel_heavy" + seed: 44 + in: + s: + gen: "str" + len: 20000 + alphabet: "aeiouaeioub" + - name: "generated_consonant_heavy" + seed: 55 + in: + s: + gen: "str" + len: 50000 + alphabet: "aeioubcdfghjklmnpqrstvwxyz" + - name: "maximum_uniform_vowel_stress" + seed: 66 + in: + s: + gen: "str" + len: 500000 + alphabet: "a" + - name: "maximum_vowel_only_stress" + seed: 77 + in: + s: + gen: "str" + len: 500000 + alphabet: "aeiou" + - name: "maximum_full_alphabet_stress" + seed: 88 + in: + s: + gen: "str" + len: 500000 + alphabet: "abcdefghijklmnopqrstuvwxyz" diff --git a/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.cpp b/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.cpp new file mode 100644 index 00000000..934224f2 --- /dev/null +++ b/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int findTheLongestSubstring(string s) { + int mapy[32]; + for (int i = 0; i < 32; i++) mapy[i] = -2; + mapy[0] = -1; + + int res = 0; + int mask = 0; + + for (int i = 0; i < s.size(); i++) { + char c = s[i]; + if (c == 'a') mask ^= 1; + else if (c == 'e') mask ^= 2; + else if (c == 'i') mask ^= 4; + else if (c == 'o') mask ^= 8; + else if (c == 'u') mask ^= 16; + + int prev = mapy[mask]; + if (prev == -2) mapy[mask] = i; + else res = max(res, i - prev); + } + + return res; + } +}; diff --git a/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.cs b/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.cs new file mode 100644 index 00000000..d08da3b6 --- /dev/null +++ b/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.cs @@ -0,0 +1,25 @@ +public class Solution { + public int FindTheLongestSubstring(string s) { + int[] mapy = new int[32]; + for (int i = 0; i < 32; i++) mapy[i] = -2; + mapy[0] = -1; + + int res = 0; + int mask = 0; + + for (int i = 0; i < s.Length; i++) { + char c = s[i]; + if (c == 'a') mask ^= 1; + else if (c == 'e') mask ^= 2; + else if (c == 'i') mask ^= 4; + else if (c == 'o') mask ^= 8; + else if (c == 'u') mask ^= 16; + + int prev = mapy[mask]; + if (prev == -2) mapy[mask] = i; + else res = Math.Max(res, i - prev); + } + + return res; + } +} diff --git a/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.dart b/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.dart new file mode 100644 index 00000000..19057a93 --- /dev/null +++ b/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.dart @@ -0,0 +1,27 @@ +class Solution { + int findTheLongestSubstring(String s) { + List mapy = List.filled(32, -2); + mapy[0] = -1; + + int res = 0; + int mask = 0; + + for (int i = 0; i < s.length; i++) { + String c = s[i]; + if (c == 'a') mask ^= 1; + else if (c == 'e') mask ^= 2; + else if (c == 'i') mask ^= 4; + else if (c == 'o') mask ^= 8; + else if (c == 'u') mask ^= 16; + + int prev = mapy[mask]; + if (prev == -2) { + mapy[mask] = i; + } else { + if (i - prev > res) res = i - prev; + } + } + + return res; + } +} diff --git a/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.go b/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.go new file mode 100644 index 00000000..5f94cf99 --- /dev/null +++ b/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.go @@ -0,0 +1,36 @@ +func findTheLongestSubstring(s string) int { + mapy := make([]int, 32) + for i := range mapy { + mapy[i] = -2 + } + mapy[0] = -1 + + res := 0 + mask := 0 + + for i, c := range s { + switch c { + case 'a': + mask ^= 1 + case 'e': + mask ^= 2 + case 'i': + mask ^= 4 + case 'o': + mask ^= 8 + case 'u': + mask ^= 16 + } + + prev := mapy[mask] + if prev == -2 { + mapy[mask] = i + } else { + if i - prev > res { + res = i - prev + } + } + } + + return res +} diff --git a/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.java b/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.java new file mode 100644 index 00000000..26904514 --- /dev/null +++ b/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.java @@ -0,0 +1,25 @@ +class Solution { + public int findTheLongestSubstring(String s) { + int[] mapy = new int[32]; + for (int i = 0; i < 32; i++) mapy[i] = -2; + mapy[0] = -1; + + int res = 0; + int mask = 0; + + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (c == 'a') mask ^= 1; + else if (c == 'e') mask ^= 2; + else if (c == 'i') mask ^= 4; + else if (c == 'o') mask ^= 8; + else if (c == 'u') mask ^= 16; + + int prev = mapy[mask]; + if (prev == -2) mapy[mask] = i; + else res = Math.max(res, i - prev); + } + + return res; + } +} diff --git a/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.kt b/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.kt new file mode 100644 index 00000000..ad4d1510 --- /dev/null +++ b/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.kt @@ -0,0 +1,26 @@ +class Solution { + fun findTheLongestSubstring(s: String): Int { + val mapy = IntArray(32) { -2 } + mapy[0] = -1 + + var res = 0 + var mask = 0 + + for (i in s.indices) { + val c = s[i] + when (c) { + 'a' -> mask = mask xor 1 + 'e' -> mask = mask xor 2 + 'i' -> mask = mask xor 4 + 'o' -> mask = mask xor 8 + 'u' -> mask = mask xor 16 + } + + val prev = mapy[mask] + if (prev == -2) mapy[mask] = i + else res = maxOf(res, i - prev) + } + + return res + } +} diff --git a/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.py b/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.py new file mode 100644 index 00000000..fe27d9e8 --- /dev/null +++ b/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.py @@ -0,0 +1,27 @@ +class Solution: + def findTheLongestSubstring(self, s: str) -> int: + mapy = [-2] * 32 + mapy[0] = -1 + + res = 0 + mask = 0 + + for i, c in enumerate(s): + if c == "a": + mask ^= 1 + elif c == "e": + mask ^= 2 + elif c == "i": + mask ^= 4 + elif c == "o": + mask ^= 8 + elif c == "u": + mask ^= 16 + + prev = mapy[mask] + if prev == -2: + mapy[mask] = i + else: + res = max(res, i - prev) + + return res diff --git a/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.py2 b/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.py2 new file mode 100644 index 00000000..85f10219 --- /dev/null +++ b/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.py2 @@ -0,0 +1,31 @@ +class Solution(object): + def findTheLongestSubstring(self, s): + """ + :type s: str + :rtype: int + """ + mapy = [-2] * 32 + mapy[0] = -1 + + res = 0 + mask = 0 + + for i, c in enumerate(s): + if c == 'a': + mask ^= 1 + elif c == 'e': + mask ^= 2 + elif c == 'i': + mask ^= 4 + elif c == 'o': + mask ^= 8 + elif c == 'u': + mask ^= 16 + + prev = mapy[mask] + if prev == -2: + mapy[mask] = i + else: + res = max(res, i - prev) + + return res diff --git a/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.rb b/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.rb new file mode 100644 index 00000000..cbb9bc8b --- /dev/null +++ b/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.rb @@ -0,0 +1,33 @@ +# @param {String} s +# @return {Integer} +def find_the_longest_substring(s) + mapy = [-2] * 32 + mapy[0] = -1 + + res = 0 + mask = 0 + + s.each_char.with_index do |c, i| + case c + when 'a' + mask ^= 1 + when 'e' + mask ^= 2 + when 'i' + mask ^= 4 + when 'o' + mask ^= 8 + when 'u' + mask ^= 16 + end + + prev = mapy[mask] + if prev == -2 + mapy[mask] = i + else + res = [res, i - prev].max + end + end + + res +end diff --git a/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.rs b/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.rs new file mode 100644 index 00000000..9a84bfe4 --- /dev/null +++ b/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.rs @@ -0,0 +1,32 @@ +impl Solution { + pub fn find_the_longest_substring(s: String) -> i32 { + let mut mapy = [-2i32; 32]; + mapy[0] = -1; + + let mut res = 0i32; + let mut mask = 0i32; + + for (i, c) in s.chars().enumerate() { + match c { + 'a' => mask ^= 1, + 'e' => mask ^= 2, + 'i' => mask ^= 4, + 'o' => mask ^= 8, + 'u' => mask ^= 16, + _ => {} + } + + let prev = mapy[mask as usize]; + if prev == -2 { + mapy[mask as usize] = i as i32; + } else { + let len = i as i32 - prev; + if len > res { + res = len; + } + } + } + + res + } +} diff --git a/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.swift b/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.swift new file mode 100644 index 00000000..3837c9c6 --- /dev/null +++ b/tests/1001-1500/1371. find-the-longest-substring-containing-vowels-in-even-counts/sol.swift @@ -0,0 +1,37 @@ +class Solution { + func findTheLongestSubstring(_ s: String) -> Int { + var mapy = [Int](repeating: -2, count: 32) + mapy[0] = -1 + + var res = 0 + var mask = 0 + let chars = Array(s) + + for i in 0..> st; + st.push({root, 0, 0}); + while (!st.empty()) { + auto [node, endedLeft, endedRight] = st.top(); + st.pop(); + best = max({best, endedLeft, endedRight}); + if (node->left) { + st.push({node->left, endedRight + 1, 0}); + } + if (node->right) { + st.push({node->right, 0, endedLeft + 1}); + } + } + return best; + } +}; diff --git a/tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.cs b/tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.cs new file mode 100644 index 00000000..9bae5f0b --- /dev/null +++ b/tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.cs @@ -0,0 +1,32 @@ +/** + * 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 LongestZigZag(TreeNode root) { + if (root == null) return 0; + int best = 0; + Stack<(TreeNode node, int endedLeft, int endedRight)> stack = new Stack<(TreeNode, int, int)>(); + stack.Push((root, 0, 0)); + while (stack.Count > 0) { + var (node, endedLeft, endedRight) = stack.Pop(); + best = Math.Max(best, Math.Max(endedLeft, endedRight)); + if (node.left != null) { + stack.Push((node.left, endedRight + 1, 0)); + } + if (node.right != null) { + stack.Push((node.right, 0, endedLeft + 1)); + } + } + return best; + } +} diff --git a/tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.dart b/tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.dart new file mode 100644 index 00000000..0f0699f1 --- /dev/null +++ b/tests/1001-1500/1372. longest-zigzag-path-in-a-binary-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 { + int longestZigZag(TreeNode? root) { + if (root == null) return 0; + int best = 0; + final List> stack = [[root, 0, 0]]; + while (stack.isNotEmpty) { + final state = stack.removeLast(); + final TreeNode node = state[0] as TreeNode; + final int endedLeft = state[1] as int; + final int endedRight = state[2] as int; + if (endedLeft > best) best = endedLeft; + if (endedRight > best) best = endedRight; + if (node.left != null) { + stack.add([node.left!, endedRight + 1, 0]); + } + if (node.right != null) { + stack.add([node.right!, 0, endedLeft + 1]); + } + } + return best; + } +} diff --git a/tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.go b/tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.go new file mode 100644 index 00000000..63df52f5 --- /dev/null +++ b/tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.go @@ -0,0 +1,37 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func longestZigZag(root *TreeNode) int { + if root == nil { + return 0 + } + best := 0 + type item struct { + node *TreeNode + endedLeft int + endedRight int + } + stack := []item{{root, 0, 0}} + for len(stack) > 0 { + cur := stack[len(stack)-1] + stack = stack[:len(stack)-1] + if cur.endedLeft > best { + best = cur.endedLeft + } + if cur.endedRight > best { + best = cur.endedRight + } + if cur.node.Left != nil { + stack = append(stack, item{cur.node.Left, cur.endedRight + 1, 0}) + } + if cur.node.Right != nil { + stack = append(stack, item{cur.node.Right, 0, cur.endedLeft + 1}) + } + } + return best +} diff --git a/tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.java b/tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.java new file mode 100644 index 00000000..76acd166 --- /dev/null +++ b/tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.java @@ -0,0 +1,37 @@ +/** + * 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 longestZigZag(TreeNode root) { + if (root == null) return 0; + int best = 0; + Stack stack = new Stack<>(); + stack.push(new Object[]{root, 0, 0}); + while (!stack.isEmpty()) { + Object[] cur = stack.pop(); + TreeNode node = (TreeNode) cur[0]; + int endedLeft = (int) cur[1]; + int endedRight = (int) cur[2]; + best = Math.max(best, Math.max(endedLeft, endedRight)); + if (node.left != null) { + stack.push(new Object[]{node.left, endedRight + 1, 0}); + } + if (node.right != null) { + stack.push(new Object[]{node.right, 0, endedLeft + 1}); + } + } + return best; + } +} diff --git a/tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.kt b/tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.kt new file mode 100644 index 00000000..034d75a7 --- /dev/null +++ b/tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.kt @@ -0,0 +1,25 @@ +/** + * 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 longestZigZag(root: TreeNode?): Int { + if (root == null) return 0 + var best = 0 + val stack = ArrayDeque>() + stack.addLast(Triple(root, 0, 0)) + while (stack.isNotEmpty()) { + val (node, endedLeft, endedRight) = stack.removeLast() + best = maxOf(best, maxOf(endedLeft, endedRight)) + node.left?.let { stack.addLast(Triple(it, endedRight + 1, 0)) } + node.right?.let { stack.addLast(Triple(it, 0, endedLeft + 1)) } + } + return best + } +} diff --git a/tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.py b/tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.py new file mode 100644 index 00000000..bcc0c087 --- /dev/null +++ b/tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.py @@ -0,0 +1,26 @@ +# 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 longestZigZag(self, root: TreeNode) -> int: + if root is None: + return 0 + + # Store the best alternating path ending at each node by final direction. + best = 0 + stack = [ + (root, 0, 0) + ] # node, path ending with left edge, path ending with right edge + while stack: + node, ended_left, ended_right = stack.pop() + best = max(best, ended_left, ended_right) + if node.left: + stack.append((node.left, ended_right + 1, 0)) + if node.right: + stack.append((node.right, 0, ended_left + 1)) + return best diff --git a/tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.py2 b/tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.py2 new file mode 100644 index 00000000..0ad014d1 --- /dev/null +++ b/tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.py2 @@ -0,0 +1,24 @@ +# 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 longestZigZag(self, root): + """ + :type root: Optional[TreeNode] + :rtype: int + """ + if root is None: + return 0 + best = 0 + stack = [(root, 0, 0)] + while stack: + node, ended_left, ended_right = stack.pop() + best = max(best, ended_left, ended_right) + if node.left: + stack.append((node.left, ended_right + 1, 0)) + if node.right: + stack.append((node.right, 0, ended_left + 1)) + return best diff --git a/tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.rb b/tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.rb new file mode 100644 index 00000000..c2d76c37 --- /dev/null +++ b/tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.rb @@ -0,0 +1,27 @@ +# 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 {Integer} +def longest_zig_zag(root) + return 0 if root.nil? + best = 0 + stack = [[root, 0, 0]] + while !stack.empty? + node, ended_left, ended_right = stack.pop + best = [best, ended_left, ended_right].max + if node.left + stack.push([node.left, ended_right + 1, 0]) + end + if node.right + stack.push([node.right, 0, ended_left + 1]) + end + end + best +end diff --git a/tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.rs b/tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.rs new file mode 100644 index 00000000..6cb975f1 --- /dev/null +++ b/tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.rs @@ -0,0 +1,38 @@ +// 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 longest_zig_zag(root: Option>>) -> i32 { + if root.is_none() { + return 0; + } + let mut best = 0; + let mut stack = vec![(root.unwrap(), 0, 0)]; + while let Some((node_rc, ended_left, ended_right)) = stack.pop() { + let node = node_rc.borrow(); + best = best.max(ended_left).max(ended_right); + if let Some(left) = node.left.clone() { + stack.push((left, ended_right + 1, 0)); + } + if let Some(right) = node.right.clone() { + stack.push((right, 0, ended_left + 1)); + } + } + best + } +} diff --git a/tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.swift b/tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.swift new file mode 100644 index 00000000..87e193a9 --- /dev/null +++ b/tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.swift @@ -0,0 +1,33 @@ +/** + * 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 longestZigZag(_ root: TreeNode?) -> Int { + guard let root = root else { return 0 } + var best = 0 + var stack: [(node: TreeNode, endedLeft: Int, endedRight: Int)] = [(root, 0, 0)] + while !stack.isEmpty { + let (node, endedLeft, endedRight) = stack.removeLast() + best = max(best, max(endedLeft, endedRight)) + if let left = node.left { + stack.append((left, endedRight + 1, 0)) + } + if let right = node.right { + stack.append((right, 0, endedLeft + 1)) + } + } + return best + } +} diff --git a/tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.ts b/tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.ts new file mode 100644 index 00000000..54e3d093 --- /dev/null +++ b/tests/1001-1500/1372. longest-zigzag-path-in-a-binary-tree/sol.ts @@ -0,0 +1,30 @@ +/** + * 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 longestZigZag(root: TreeNode | null): number { + if (root === null) return 0; + let best = 0; + const stack: [TreeNode, number, number][] = [[root, 0, 0]]; + while (stack.length > 0) { + const [node, endedLeft, endedRight] = stack.pop()!; + best = Math.max(best, endedLeft, endedRight); + if (node.left !== null) { + stack.push([node.left, endedRight + 1, 0]); + } + if (node.right !== null) { + stack.push([node.right, 0, endedLeft + 1]); + } + } + return best; +} diff --git a/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/manifest.yaml b/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/manifest.yaml new file mode 100644 index 00000000..042a7b4f --- /dev/null +++ b/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/manifest.yaml @@ -0,0 +1,324 @@ +entry: + id: 1373 + title: "maximum-sum-bst-in-binary-tree" + params: + root: + type: tree_node + call: + cpp: "Solution().maxSumBST({root})" + rust: "Solution::max_sum_bst({root})" + python3: "Solution().maxSumBST({root})" + python2: "Solution().maxSumBST({root})" + ruby: "max_sum_bst({root})" + java: "new Solution().maxSumBST({root})" + csharp: "new Solution().MaxSumBST({root})" + kotlin: "Solution().maxSumBST({root})" + go: "maxSumBST({root})" + dart: "Solution().maxSumBST({root})" + swift: "Solution().maxSumBST({root})" + typescript: "maxSumBST({root})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().maxSumBST(root, {result})" + checker: | + class Checker: + def maxSumBST(self, root, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + + if isinstance(root, list): + class Node: + def __init__(self, value): + self.val = value + self.left = None + self.right = None + + serialized_nodes = [None if value is None else Node(value) for value in root] + child = 1 + for node in serialized_nodes: + if node is not None: + if child < len(serialized_nodes): + node.left = serialized_nodes[child] + child += 1 + if child < len(serialized_nodes): + node.right = serialized_nodes[child] + child += 1 + root = serialized_nodes[0] if serialized_nodes else None + + nodes = [] + stack = [root] if root is not None else [] + while stack: + node = stack.pop() + nodes.append(node) + if node.left is not None: + stack.append(node.left) + if node.right is not None: + stack.append(node.right) + + best = 0 + for candidate in nodes: + total = 0 + previous = None + valid = True + traversal = [] + current = candidate + while traversal or current is not None: + while current is not None: + traversal.append(current) + current = current.left + current = traversal.pop() + if previous is not None and current.val <= previous: + valid = False + break + previous = current.val + total += current.val + current = current.right + if valid and total > best: + best = total + return result == best + +seed: 1373 + +tests: + - name: "example-one" + in: + root: [1, 4, 3, 2, 4, 2, 5, null, null, null, null, null, null, 4, 6] + - name: "example-two" + in: + root: [4, 3, null, 1, 2] + - name: "example-three" + in: + root: [-4, -2, -5] + - name: "single-positive" + in: + root: [7] + - name: "single-negative" + in: + root: [-7] + - name: "single-zero" + in: + root: [0] + - name: "two-node-valid" + in: + root: [2, 1] + - name: "two-node-invalid" + in: + root: [2, 3] + - name: "right-chain-valid" + in: + root: [1, null, 2, null, 3] + - name: "left-chain-valid" + in: + root: [3, 2, null, 1] + - name: "balanced-bst" + in: + root: [4, 2, 6, 1, 3, 5, 7] + - name: "duplicate-on-left" + in: + root: [5, 5, 6] + - name: "duplicate-on-right" + in: + root: [5, 4, 5] + - name: "cross-subtree-violation" + in: + root: [5, 3, 8, 2, 6, 7, 9] + - name: "best-valid-right-subtree" + in: + root: [10, 5, 15, 1, 8, 7, 20] + - name: "right-subtree-only" + in: + root: [10, 5, 15, null, null, 6, 20] + - name: "negative-valid-bst" + in: + root: [-1, -3, 2, -4, -2, 1, 3] + - name: "mixed-sign-valid-bst" + in: + root: [0, -3, 4, -5, -1, 2, 7] + - name: "all-negative-valid-bst" + in: + root: [-2, -4, -1, -5, -3] + - name: "invalid-left-valid-right" + in: + root: [8, 4, 12, 2, 10, 9, 14] + - name: "invalid-left-large-right" + in: + root: [20, 10, 30, 5, 25, 22, 35] + - name: "sparse-valid" + in: + root: [6, 2, 9, null, 4, 7, null, 3, 5] + - name: "sparse-boundaries-valid" + in: + root: [5, 1, 8, null, 4, 6, 9, 3] + - name: "extreme-values-valid" + in: + root: [0, -40000, 40000, null, -1, 1] + - name: "extreme-values-duplicate" + in: + root: [40000, 40000, -40000] + - name: "largest-single-leaf" + in: + root: [50, 60, 40, 70, 55, 45, 30] + - name: "zero-root-positive-subtree" + in: + root: [0, -2, 3, -3, -1, 2, 4] + - name: "all-equal-values" + in: + root: [4, 4, 4, 4, 4, 4, 4] + - name: "deep-left-chain" + in: + root: + [ + 10, + 9, + null, + 8, + null, + 7, + null, + 6, + null, + 5, + null, + 4, + null, + 3, + null, + 2, + null, + 1, + ] + - name: "deep-descendant-breaks-root" + in: + root: [10, 5, 15, 2, 7, 12, 20, null, null, null, 11] + - name: "complete-fifteen-node-bst" + in: + root: [8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15] + - name: "broken-root-two-bst-branches" + in: + root: [15, 5, 20, 1, 30, 17, 25] + - name: "complete-thirty-one-node-bst" + in: + root: + [ + 16, + 8, + 24, + 4, + 12, + 20, + 28, + 2, + 6, + 10, + 14, + 18, + 22, + 26, + 30, + 1, + 3, + 5, + 7, + 9, + 11, + 13, + 15, + 17, + 19, + 21, + 23, + 25, + 27, + 29, + 31, + ] + - name: "large-invalid-branches" + in: + root: [50, 25, 75, 10, 80, 60, 90, 5, 15, 70, 85, 55, 65, 85, 95] + - name: "long-right-chain" + in: + root: + [ + 1, + null, + 2, + null, + 3, + null, + 4, + null, + 5, + null, + 6, + null, + 7, + null, + 8, + null, + 9, + null, + 10, + null, + 11, + null, + 12, + null, + 13, + null, + 14, + null, + 15, + ] + - name: "long-left-chain" + in: + root: + [ + 15, + 14, + null, + 13, + null, + 12, + null, + 11, + null, + 10, + null, + 9, + null, + 8, + null, + 7, + null, + 6, + null, + 5, + null, + 4, + null, + 3, + null, + 2, + null, + 1, + ] + - name: "zigzag-valid-bst" + in: + root: [8, 3, 10, 1, 6, null, 14, null, null, 4, 7, 13] + - name: "zigzag-broken-boundary" + in: + root: [8, 3, 10, 1, 6, null, 14, null, null, 4, 9, 13] + - name: "negative-root-best-right" + in: + root: [-100, 5, 10, 2, 7, 8, 12] + - name: "maximum-value-positive-branch" + in: + root: [0, -40000, 40000, -39999, -1, 1, 39999] diff --git a/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.cpp b/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.cpp new file mode 100644 index 00000000..af6ea141 --- /dev/null +++ b/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.cpp @@ -0,0 +1,39 @@ +/** + * 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: + int maxSumBST(TreeNode* root) { + int best = 0; + dfs(root, best); + return best; + } + +private: + tuple dfs(TreeNode* node, int& best) { + if (!node) { + return {true, INT_MAX, INT_MIN, 0}; + } + + auto [lbst, lmin, lmax, lsum] = dfs(node->left, best); + auto [rbst, rmin, rmax, rsum] = dfs(node->right, best); + + if (lbst && rbst && lmax < node->val && node->val < rmin) { + int total = lsum + rsum + node->val; + best = max(best, total); + int newMin = min(lmin, node->val); + int newMax = max(rmax, node->val); + return {true, newMin, newMax, total}; + } + + return {false, INT_MIN, INT_MAX, 0}; + } +}; diff --git a/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.cs b/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.cs new file mode 100644 index 00000000..205f4d28 --- /dev/null +++ b/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.cs @@ -0,0 +1,41 @@ +/** + * 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 { + private int best = 0; + + public int MaxSumBST(TreeNode root) { + best = 0; + dfs(root); + return best; + } + + private (bool, int, int, int) dfs(TreeNode node) { + if (node == null) { + return (true, int.MaxValue, int.MinValue, 0); + } + + var (lbst, lmin, lmax, lsum) = dfs(node.left); + var (rbst, rmin, rmax, rsum) = dfs(node.right); + + if (lbst && rbst && lmax < node.val && node.val < rmin) { + int total = lsum + rsum + node.val; + best = Math.Max(best, total); + int newMin = Math.Min(lmin, node.val); + int newMax = Math.Max(rmax, node.val); + return (true, newMin, newMax, total); + } + + return (false, int.MinValue, int.MaxValue, 0); + } +} diff --git a/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.dart b/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.dart new file mode 100644 index 00000000..5026a2fa --- /dev/null +++ b/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.dart @@ -0,0 +1,40 @@ +/** + * 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 best = 0; + + int maxSumBST(TreeNode? root) { + best = 0; + dfs(root); + return best; + } + + List dfs(TreeNode? node) { + if (node == null) { + return [1, 0x7FFFFFFF, -0x80000000, 0]; + } + + List left = dfs(node.left); + List right = dfs(node.right); + + int lbst = left[0], lmin = left[1], lmax = left[2], lsum = left[3]; + int rbst = right[0], rmin = right[1], rmax = right[2], rsum = right[3]; + + if (lbst == 1 && rbst == 1 && lmax < node.val && node.val < rmin) { + int total = lsum + rsum + node.val; + best = best > total ? best : total; + int newMin = lmin < node.val ? lmin : node.val; + int newMax = rmax > node.val ? rmax : node.val; + return [1, newMin, newMax, total]; + } + + return [0, -0x80000000, 0x7FFFFFFF, 0]; + } +} diff --git a/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.go b/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.go new file mode 100644 index 00000000..3ad45e88 --- /dev/null +++ b/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.go @@ -0,0 +1,42 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func maxSumBST(root *TreeNode) int { + best := 0 + + var dfs func(node *TreeNode) (bool, int, int, int) + dfs = func(node *TreeNode) (bool, int, int, int) { + if node == nil { + return true, int(^uint(0) >> 1), -int(^uint(0) >> 1) - 1, 0 + } + + lbst, lmin, lmax, lsum := dfs(node.Left) + rbst, rmin, rmax, rsum := dfs(node.Right) + + if lbst && rbst && lmax < node.Val && node.Val < rmin { + total := lsum + rsum + node.Val + if total > best { + best = total + } + newMin := lmin + if node.Val < newMin { + newMin = node.Val + } + newMax := rmax + if node.Val > newMax { + newMax = node.Val + } + return true, newMin, newMax, total + } + + return false, -int(^uint(0) >> 1) - 1, int(^uint(0) >> 1), 0 + } + + dfs(root) + return best +} diff --git a/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.java b/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.java new file mode 100644 index 00000000..10813546 --- /dev/null +++ b/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.java @@ -0,0 +1,46 @@ +/** + * 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 { + private int best = 0; + + public int maxSumBST(TreeNode root) { + best = 0; + dfs(root); + return best; + } + + private int[] dfs(TreeNode node) { + if (node == null) { + return new int[]{1, Integer.MAX_VALUE, Integer.MIN_VALUE, 0}; + } + + int[] left = dfs(node.left); + int[] right = dfs(node.right); + + int lbst = left[0], lmin = left[1], lmax = left[2], lsum = left[3]; + int rbst = right[0], rmin = right[1], rmax = right[2], rsum = right[3]; + + if (lbst == 1 && rbst == 1 && lmax < node.val && node.val < rmin) { + int total = lsum + rsum + node.val; + best = Math.max(best, total); + int newMin = Math.min(lmin, node.val); + int newMax = Math.max(rmax, node.val); + return new int[]{1, newMin, newMax, total}; + } + + return new int[]{0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0}; + } +} diff --git a/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.kt b/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.kt new file mode 100644 index 00000000..aa6743d5 --- /dev/null +++ b/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.kt @@ -0,0 +1,47 @@ +/** + * 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 { + private var best = 0 + + fun maxSumBST(root: TreeNode?): Int { + best = 0 + dfs(root) + return best + } + + private fun dfs(node: TreeNode?): IntArray { + if (node == null) { + return intArrayOf(1, Int.MAX_VALUE, Int.MIN_VALUE, 0) + } + + val left = dfs(node.left) + val right = dfs(node.right) + + val lbst = left[0] + val lmin = left[1] + val lmax = left[2] + val lsum = left[3] + val rbst = right[0] + val rmin = right[1] + val rmax = right[2] + val rsum = right[3] + + if (lbst == 1 && rbst == 1 && lmax < node.`val` && node.`val` < rmin) { + val total = lsum + rsum + node.`val` + best = maxOf(best, total) + val newMin = minOf(lmin, node.`val`) + val newMax = maxOf(rmax, node.`val`) + return intArrayOf(1, newMin, newMax, total) + } + + return intArrayOf(0, Int.MIN_VALUE, Int.MAX_VALUE, 0) + } +} diff --git a/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.py b/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.py new file mode 100644 index 00000000..dc9ca505 --- /dev/null +++ b/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.py @@ -0,0 +1,29 @@ +# 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 maxSumBST(self, root: Optional[TreeNode]) -> int: + + self.best = 0 + + def dfs(node): + if not node: + return True, float("inf"), float("-inf"), 0 + + lbst, lmin, lmax, lsum = dfs(node.left) + rbst, rmin, rmax, rsum = dfs(node.right) + + if lbst and rbst and lmax < node.val < rmin: + total = lsum + rsum + node.val + self.best = max(self.best, total) + + return True, min(lmin, node.val), max(rmax, node.val), total + + return False, float("-inf"), float("inf"), 0 + + dfs(root) + + return self.best diff --git a/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.py2 b/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.py2 new file mode 100644 index 00000000..3d55ad2c --- /dev/null +++ b/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.py2 @@ -0,0 +1,30 @@ +# 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 maxSumBST(self, root): + """ + :type root: Optional[TreeNode] + :rtype: int + """ + self.best = 0 + + def dfs(node): + if not node: + return True, float('inf'), float('-inf'), 0 + + lbst, lmin, lmax, lsum = dfs(node.left) + rbst, rmin, rmax, rsum = dfs(node.right) + + if lbst and rbst and lmax < node.val < rmin: + total = lsum + rsum + node.val + self.best = max(self.best, total) + return True, min(lmin, node.val), max(rmax, node.val), total + + return False, float('-inf'), float('inf'), 0 + + dfs(root) + return self.best diff --git a/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.rb b/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.rb new file mode 100644 index 00000000..8a752d27 --- /dev/null +++ b/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.rb @@ -0,0 +1,32 @@ +# 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 {Integer} +def max_sum_bst(root) + @best = 0 + + dfs = lambda do |node| + return [true, Float::INFINITY, -Float::INFINITY, 0] if node.nil? + + lbst, lmin, lmax, lsum = dfs.call(node.left) + rbst, rmin, rmax, rsum = dfs.call(node.right) + + if lbst && rbst && lmax < node.val && node.val < rmin + total = lsum + rsum + node.val + @best = [@best, total].max + return [true, [lmin, node.val].min, [rmax, node.val].max, total] + end + + return [false, -Float::INFINITY, Float::INFINITY, 0] + end + + dfs.call(root) + @best +end diff --git a/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.rs b/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.rs new file mode 100644 index 00000000..eb906e39 --- /dev/null +++ b/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.rs @@ -0,0 +1,46 @@ +// 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 max_sum_bst(root: Option>>) -> i32 { + fn dfs(node: Option>>, best: &mut i32) -> (bool, i32, i32, i32) { + match node { + None => (true, i32::MAX, i32::MIN, 0), + Some(n) => { + let n = n.borrow(); + let (lbst, lmin, lmax, lsum) = dfs(n.left.clone(), best); + let (rbst, rmin, rmax, rsum) = dfs(n.right.clone(), best); + + if lbst && rbst && lmax < n.val && n.val < rmin { + let total = lsum + rsum + n.val; + *best = (*best).max(total); + let new_min = lmin.min(n.val); + let new_max = rmax.max(n.val); + return (true, new_min, new_max, total); + } + + (false, i32::MIN, i32::MAX, 0) + } + } + } + + let mut best = 0; + dfs(root, &mut best); + best + } +} diff --git a/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.swift b/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.swift new file mode 100644 index 00000000..eb13e24c --- /dev/null +++ b/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.swift @@ -0,0 +1,43 @@ +/** + * 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 { + private var best = 0 + + func maxSumBST(_ root: TreeNode?) -> Int { + best = 0 + let _ = dfs(root) + return best + } + + private func dfs(_ node: TreeNode?) -> (Bool, Int, Int, Int) { + guard let node = node else { + return (true, Int.max, Int.min, 0) + } + + let (lbst, lmin, lmax, lsum) = dfs(node.left) + let (rbst, rmin, rmax, rsum) = dfs(node.right) + + if lbst && rbst && lmax < node.val && node.val < rmin { + let total = lsum + rsum + node.val + best = max(best, total) + let newMin = min(lmin, node.val) + let newMax = max(rmax, node.val) + return (true, newMin, newMax, total) + } + + return (false, Int.min, Int.max, 0) + } +} diff --git a/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.ts b/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.ts new file mode 100644 index 00000000..90ef1c3b --- /dev/null +++ b/tests/1001-1500/1373. maximum-sum-bst-in-binary-tree/sol.ts @@ -0,0 +1,39 @@ +/** + * 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 maxSumBST(root: TreeNode | null): number { + let best = 0; + + function dfs(node: TreeNode | null): [boolean, number, number, number] { + if (!node) { + return [true, Infinity, -Infinity, 0]; + } + + const [lbst, lmin, lmax, lsum] = dfs(node.left); + const [rbst, rmin, rmax, rsum] = dfs(node.right); + + if (lbst && rbst && lmax < node.val && node.val < rmin) { + const total = lsum + rsum + node.val; + best = Math.max(best, total); + const newMin = Math.min(lmin, node.val); + const newMax = Math.max(rmax, node.val); + return [true, newMin, newMax, total]; + } + + return [false, -Infinity, Infinity, 0]; + } + + dfs(root); + return best; +} diff --git a/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/manifest.yaml b/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/manifest.yaml new file mode 100644 index 00000000..cdf3d8e1 --- /dev/null +++ b/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/manifest.yaml @@ -0,0 +1,223 @@ +entry: + id: 1374 + title: "generate-a-string-with-characters-that-have-odd-counts" + params: + n: + type: int + call: + cpp: "Solution().generateTheString({n})" + rust: "Solution::generate_the_string({n})" + python3: "Solution().generateTheString({n})" + python2: "Solution().generateTheString({n})" + ruby: "generate_the_string({n})" + java: "new Solution().generateTheString({n})" + csharp: "new Solution().GenerateTheString({n})" + kotlin: "Solution().generateTheString({n})" + go: "generateTheString({n})" + dart: "Solution().generateTheString({n})" + swift: "Solution().generateTheString({n})" + typescript: "generateTheString({n})" + +judge: + type: "exact" + +limits: + time_ms: 300 + memory_mb: 300 + +oracle: + python3: + call: "Checker().generateTheString(n, {result})" + checker: | + from collections import Counter + + class Checker: + def generateTheString(self, n, result): + if not isinstance(result, str) or len(result) != n: + return False + if any(not ("a" <= char <= "z") for char in result): + return False + return all(count % 2 == 1 for count in Counter(result).values()) + +seed: 1374 + +tests: + - name: "minimum_length" + in: + n: 1 + + - name: "example_even_two" + in: + n: 2 + + - name: "small_odd_three" + in: + n: 3 + + - name: "example_even_four" + in: + n: 4 + + - name: "small_odd_five" + in: + n: 5 + + - name: "small_even_six" + in: + n: 6 + + - name: "example_odd_seven" + in: + n: 7 + + - name: "small_even_eight" + in: + n: 8 + + - name: "small_odd_nine" + in: + n: 9 + + - name: "small_even_ten" + in: + n: 10 + + - name: "quarter_century_odd" + in: + n: 25 + + - name: "quarter_century_even" + in: + n: 26 + + - name: "post_quarter_odd" + in: + n: 27 + + - name: "low_thirties_odd" + in: + n: 31 + + - name: "power_of_two_even" + in: + n: 32 + + - name: "post_power_odd" + in: + n: 33 + + - name: "post_power_even" + in: + n: 34 + + - name: "near_hundred_odd" + in: + n: 97 + + - name: "near_hundred_even" + in: + n: 98 + + - name: "hundred_minus_one" + in: + n: 99 + + - name: "hundred_even" + in: + n: 100 + + - name: "hundred_plus_one" + in: + n: 101 + + - name: "power_of_two_minus_one" + in: + n: 127 + + - name: "power_of_two_128" + in: + n: 128 + + - name: "two_hundred_minus_one" + in: + n: 199 + + - name: "two_hundred_even" + in: + n: 200 + + - name: "two_hundred_plus_one" + in: + n: 201 + + - name: "midrange_odd_255" + in: + n: 255 + + - name: "midrange_even_256" + in: + n: 256 + + - name: "midrange_odd_257" + in: + n: 257 + + - name: "upper_range_odd" + in: + n: 333 + + - name: "upper_range_even" + in: + n: 334 + + - name: "four_hundred_plus_one" + in: + n: 401 + + - name: "maximum_minus_one" + in: + n: 499 + + - name: "maximum_length" + in: + n: 500 + + - name: "generated_full_constraint_range" + seed: 137401 + in: + n: + gen: "int" + min: 1 + max: 500 + + - name: "generated_small_range" + seed: 137402 + in: + n: + gen: "int" + min: 11 + max: 24 + + - name: "generated_lower_midrange" + seed: 137403 + in: + n: + gen: "int" + min: 35 + max: 96 + + - name: "generated_middle_range" + seed: 137404 + in: + n: + gen: "int" + min: 102 + max: 198 + + - name: "generated_upper_range" + seed: 137405 + in: + n: + gen: "int" + min: 335 + max: 498 diff --git a/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.cpp b/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.cpp new file mode 100644 index 00000000..2bad8ed0 --- /dev/null +++ b/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + string generateTheString(int n) { + if (n % 2 == 1) { + return string(n, 'a'); + } else { + return string(n - 1, 'a') + 'b'; + } + } +}; diff --git a/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.cs b/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.cs new file mode 100644 index 00000000..2d138d8b --- /dev/null +++ b/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.cs @@ -0,0 +1,9 @@ +public class Solution { + public string GenerateTheString(int n) { + if (n % 2 == 1) { + return new string('a', n); + } else { + return new string('a', n - 1) + "b"; + } + } +} diff --git a/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.dart b/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.dart new file mode 100644 index 00000000..432da5f1 --- /dev/null +++ b/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.dart @@ -0,0 +1,9 @@ +class Solution { + String generateTheString(int n) { + if (n % 2 == 1) { + return 'a' * n; + } else { + return 'a' * (n - 1) + 'b'; + } + } +} diff --git a/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.go b/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.go new file mode 100644 index 00000000..adc0d44d --- /dev/null +++ b/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.go @@ -0,0 +1,7 @@ +func generateTheString(n int) string { + if n%2 == 1 { + return strings.Repeat("a", n) + } else { + return strings.Repeat("a", n-1) + "b" + } +} diff --git a/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.java b/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.java new file mode 100644 index 00000000..e5888c29 --- /dev/null +++ b/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.java @@ -0,0 +1,9 @@ +class Solution { + public String generateTheString(int n) { + if (n % 2 == 1) { + return "a".repeat(n); + } else { + return "a".repeat(n - 1) + "b"; + } + } +} diff --git a/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.kt b/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.kt new file mode 100644 index 00000000..2b7a95c8 --- /dev/null +++ b/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.kt @@ -0,0 +1,9 @@ +class Solution { + fun generateTheString(n: Int): String { + return if (n % 2 == 1) { + "a".repeat(n) + } else { + "a".repeat(n - 1) + "b" + } + } +} diff --git a/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.py b/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.py new file mode 100644 index 00000000..438e59d1 --- /dev/null +++ b/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.py @@ -0,0 +1,6 @@ +class Solution: + def generateTheString(self, n: int) -> str: + if n % 2 == 1: + return "a" * n + else: + return "a" * (n - 1) + "b" diff --git a/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.py2 b/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.py2 new file mode 100644 index 00000000..327fd8f2 --- /dev/null +++ b/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.py2 @@ -0,0 +1,10 @@ +class Solution(object): + def generateTheString(self, n): + """ + :type n: int + :rtype: str + """ + if n % 2 == 1: + return "a" * n + else: + return "a" * (n - 1) + "b" diff --git a/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.rb b/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.rb new file mode 100644 index 00000000..58a6ce94 --- /dev/null +++ b/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.rb @@ -0,0 +1,9 @@ +# @param {Integer} n +# @return {String} +def generate_the_string(n) + if n % 2 == 1 + "a" * n + else + "a" * (n - 1) + "b" + end +end diff --git a/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.rs b/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.rs new file mode 100644 index 00000000..0f0f4894 --- /dev/null +++ b/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.rs @@ -0,0 +1,10 @@ +impl Solution { + pub fn generate_the_string(n: i32) -> String { + let n = n as usize; + if n % 2 == 1 { + "a".repeat(n) + } else { + "a".repeat(n - 1) + "b" + } + } +} diff --git a/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.swift b/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.swift new file mode 100644 index 00000000..674ec394 --- /dev/null +++ b/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.swift @@ -0,0 +1,9 @@ +class Solution { + func generateTheString(_ n: Int) -> String { + if n % 2 == 1 { + return String(repeating: "a", count: n) + } else { + return String(repeating: "a", count: n - 1) + "b" + } + } +} diff --git a/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.ts b/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.ts new file mode 100644 index 00000000..9160ac9e --- /dev/null +++ b/tests/1001-1500/1374. generate-a-string-with-characters-that-have-odd-counts/sol.ts @@ -0,0 +1,7 @@ +function generateTheString(n: number): string { + if (n % 2 === 1) { + return "a".repeat(n); + } else { + return "a".repeat(n - 1) + "b"; + } +} diff --git a/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/manifest.yaml b/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/manifest.yaml new file mode 100644 index 00000000..0dc3cca1 --- /dev/null +++ b/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/manifest.yaml @@ -0,0 +1,496 @@ +entry: + id: 1375 + title: "number-of-times-binary-string-is-prefix-aligned" + params: + flips: + type: array + items: + type: int + call: + cpp: "Solution().numTimesAllBlue({flips})" + rust: "Solution::num_times_all_blue({flips})" + python3: "Solution().numTimesAllBlue({flips})" + python2: "Solution().numTimesAllBlue({flips})" + ruby: "num_times_all_blue({flips})" + java: "new Solution().numTimesAllBlue({flips})" + csharp: "new Solution().NumTimesAllBlue({flips})" + kotlin: "Solution().numTimesAllBlue({flips})" + go: "numTimesAllBlue({flips})" + dart: "Solution().numTimesAllBlue({flips})" + swift: "Solution().numTimesAllBlue({flips})" + typescript: "numTimesAllBlue({flips})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().numTimesAllBlue(flips, {result})" + checker: | + class Checker: + def numTimesAllBlue(self, flips, result): + if type(result) is not int: + return False + n = len(flips) + bits = [False] * n + first_zero = 0 + aligned = 0 + for step, position in enumerate(flips, 1): + if position < 1 or position > n or bits[position - 1]: + return False + bits[position - 1] = True + while first_zero < n and bits[first_zero]: + first_zero += 1 + if first_zero == step: + aligned += 1 + return result == aligned + +seed: 1375 + +tests: + - name: "single_bit" + in: + flips: [1] + + - name: "two_in_order" + in: + flips: [1, 2] + + - name: "two_reverse_order" + in: + flips: [2, 1] + + - name: "example_one" + in: + flips: [3, 2, 4, 1, 5] + + - name: "example_two" + in: + flips: [4, 1, 2, 3] + + - name: "three_in_order" + in: + flips: [1, 2, 3] + + - name: "three_reverse_order" + in: + flips: [3, 2, 1] + + - name: "first_then_gap" + in: + flips: [1, 3, 2, 5, 4] + + - name: "late_first_bit" + in: + flips: [2, 3, 4, 5, 1] + + - name: "adjacent_swaps" + in: + flips: [2, 1, 4, 3, 6, 5] + + - name: "descending_blocks" + in: + flips: [3, 2, 1, 6, 5, 4, 9, 8, 7] + + - name: "ascending_blocks" + in: + flips: [1, 2, 3, 6, 4, 5, 9, 7, 8] + + - name: "evens_before_odds" + in: + flips: [2, 4, 6, 8, 10, 1, 3, 5, 7, 9] + + - name: "odds_before_evens" + in: + flips: [1, 3, 5, 7, 9, 2, 4, 6, 8, 10] + + - name: "rotation_by_one" + in: + flips: [2, 3, 4, 5, 6, 7, 8, 1] + + - name: "rotation_by_half" + in: + flips: [6, 7, 8, 9, 10, 1, 2, 3, 4, 5] + + - name: "interleaved_prefixes" + in: + flips: [1, 4, 2, 3, 7, 5, 6, 10, 8, 9] + + - name: "nested_delays" + in: + flips: [4, 5, 2, 3, 1, 9, 10, 7, 8, 6] + + - name: "reverse_twelve" + in: + flips: [12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + + - name: "pairwise_swapped_twelve" + in: + flips: [2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11] + + - name: "three_element_cycles" + in: + flips: [2, 3, 1, 5, 6, 4, 8, 9, 7, 11, 12, 10] + + - name: "four_element_cycles" + in: + flips: [2, 3, 4, 1, 6, 7, 8, 5, 10, 11, 12, 9] + + - name: "prefix_then_reverse_tail" + in: + flips: [1, 2, 3, 10, 9, 8, 7, 6, 5, 4] + + - name: "reverse_head_then_suffix" + in: + flips: [5, 4, 3, 2, 1, 6, 7, 8, 9, 10] + + - name: "mixed_fifteen" + in: + flips: [3, 1, 2, 7, 5, 6, 4, 11, 9, 10, 8, 15, 13, 14, 12] + + - name: "single_alignment_at_end" + in: + flips: [16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + + - name: "frequent_alignments" + in: + flips: [1, 2, 4, 3, 5, 7, 6, 8, 10, 9, 11, 12] + + - name: "alternating_far_positions" + in: + flips: [8, 1, 7, 2, 6, 3, 5, 4, 12, 9, 11, 10] + + - name: "large_static_twenty" + in: + flips: + [5, 1, 4, 2, 3, 10, 6, 9, 7, 8, 15, 11, 14, 12, 13, 20, 16, 19, 17, 18] + + - name: "large_static_twenty_five" + in: + flips: + [ + 2, + 5, + 1, + 4, + 3, + 8, + 6, + 10, + 7, + 9, + 13, + 11, + 15, + 12, + 14, + 18, + 16, + 20, + 17, + 19, + 23, + 21, + 25, + 22, + 24, + ] + + - name: "generated_permutation_twenty" + seed: 13751 + in: + flips: + gen: "array" + len: 20 + of: + gen: "int" + min: 1 + max: 20 + distinct: true + sorted: false + elemType: "int" + + - name: "generated_permutation_hundred" + seed: 13752 + in: + flips: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 100 + distinct: true + sorted: false + elemType: "int" + + - name: "generated_permutation_thousand" + seed: 13753 + in: + flips: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 1000 + distinct: true + sorted: false + elemType: "int" + + - name: "generated_permutation_near_maximum" + seed: 13754 + in: + flips: + gen: "array" + len: 49999 + of: + gen: "int" + min: 1 + max: 49999 + distinct: true + sorted: false + elemType: "int" + + - name: "generated_permutation_maximum" + seed: 13755 + in: + flips: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 50000 + distinct: true + sorted: false + elemType: "int" + + - name: "large_identity_hundred" + in: + flips: + [ + 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: "large_reverse_hundred" + in: + flips: + [ + 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, + ] + + - name: "two_phase_delayed_alignment" + in: + flips: [6, 2, 5, 3, 4, 1, 12, 8, 11, 9, 10, 7] + + - name: "irregular_twenty" + in: + flips: + [9, 2, 8, 4, 1, 3, 7, 6, 5, 10, 17, 12, 16, 14, 11, 13, 15, 20, 18, 19] + + - name: "scattered_alignment_boundaries" + in: + flips: [1, 5, 3, 4, 2, 8, 6, 7, 12, 10, 11, 9] diff --git a/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.cpp b/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.cpp new file mode 100644 index 00000000..077e340a --- /dev/null +++ b/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int numTimesAllBlue(vector& flips) { + int res = 0; + int maxFlips = 0; + + for (int i = 0; i < flips.size(); i++) { + maxFlips = max(maxFlips, flips[i]); + if (maxFlips == i + 1) { + res++; + } + } + + return res; + } +}; diff --git a/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.cs b/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.cs new file mode 100644 index 00000000..5f5a705b --- /dev/null +++ b/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.cs @@ -0,0 +1,15 @@ +public class Solution { + public int NumTimesAllBlue(int[] flips) { + int res = 0; + int maxFlips = 0; + + for (int i = 0; i < flips.Length; i++) { + maxFlips = Math.Max(maxFlips, flips[i]); + if (maxFlips == i + 1) { + res++; + } + } + + return res; + } +} diff --git a/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.dart b/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.dart new file mode 100644 index 00000000..1d13c4ea --- /dev/null +++ b/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.dart @@ -0,0 +1,17 @@ +class Solution { + int numTimesAllBlue(List flips) { + int res = 0; + int maxFlips = 0; + + for (int i = 0; i < flips.length; i++) { + if (flips[i] > maxFlips) { + maxFlips = flips[i]; + } + if (maxFlips == i + 1) { + res++; + } + } + + return res; + } +} diff --git a/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.go b/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.go new file mode 100644 index 00000000..f3f2224a --- /dev/null +++ b/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.go @@ -0,0 +1,15 @@ +func numTimesAllBlue(flips []int) int { + res := 0 + maxFlips := 0 + + for i, flip := range flips { + if flip > maxFlips { + maxFlips = flip + } + if maxFlips == i+1 { + res++ + } + } + + return res +} diff --git a/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.java b/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.java new file mode 100644 index 00000000..b62b84b8 --- /dev/null +++ b/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.java @@ -0,0 +1,15 @@ +class Solution { + public int numTimesAllBlue(int[] flips) { + int res = 0; + int maxFlips = 0; + + for (int i = 0; i < flips.length; i++) { + maxFlips = Math.max(maxFlips, flips[i]); + if (maxFlips == i + 1) { + res++; + } + } + + return res; + } +} diff --git a/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.kt b/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.kt new file mode 100644 index 00000000..8f9ffe11 --- /dev/null +++ b/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.kt @@ -0,0 +1,15 @@ +class Solution { + fun numTimesAllBlue(flips: IntArray): Int { + var res = 0 + var maxFlips = 0 + + for (i in flips.indices) { + maxFlips = maxOf(maxFlips, flips[i]) + if (maxFlips == i + 1) { + res++ + } + } + + return res + } +} diff --git a/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.py b/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.py new file mode 100644 index 00000000..7791ea56 --- /dev/null +++ b/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.py @@ -0,0 +1,18 @@ +from typing import List + + +class Solution(object): + def numTimesAllBlue(self, flips): + """ + :type flips: List[int] + :rtype: int + """ + res = 0 + max_flips = 0 + + for i in range(len(flips)): + max_flips = max(max_flips, flips[i]) + if max_flips == i + 1: + res += 1 + + return res diff --git a/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.py2 b/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.py2 new file mode 100644 index 00000000..06af4e4a --- /dev/null +++ b/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.py2 @@ -0,0 +1,15 @@ +class Solution(object): + def numTimesAllBlue(self, flips): + """ + :type flips: List[int] + :rtype: int + """ + res = 0 + max_flips = 0 + + for i in range(len(flips)): + max_flips = max(max_flips, flips[i]) + if max_flips == i + 1: + res += 1 + + return res diff --git a/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.rb b/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.rb new file mode 100644 index 00000000..ec01f440 --- /dev/null +++ b/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.rb @@ -0,0 +1,13 @@ +# @param {Integer[]} flips +# @return {Integer} +def num_times_all_blue(flips) + res = 0 + max_flips = 0 + + flips.each_with_index do |flip, i| + max_flips = [max_flips, flip].max + res += 1 if max_flips == i + 1 + end + + res +end diff --git a/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.rs b/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.rs new file mode 100644 index 00000000..e1b3d379 --- /dev/null +++ b/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn num_times_all_blue(flips: Vec) -> i32 { + let mut res = 0; + let mut max_flips = 0; + + for i in 0..flips.len() { + max_flips = max_flips.max(flips[i]); + if max_flips == (i + 1) as i32 { + res += 1; + } + } + + res + } +} diff --git a/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.swift b/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.swift new file mode 100644 index 00000000..a9ae3f9a --- /dev/null +++ b/tests/1001-1500/1375. number-of-times-binary-string-is-prefix-aligned/sol.swift @@ -0,0 +1,15 @@ +class Solution { + func numTimesAllBlue(_ flips: [Int]) -> Int { + var res = 0 + var maxFlips = 0 + + for i in 0..= n for value in manager): + return False + if any(not isinstance(value, int) or value < 0 or value > 1000 for value in informTime): + return False + if sum(value == -1 for value in manager) != 1: + return False + children = [[] for _ in range(n)] + for employee, parent in enumerate(manager): + if parent != -1: + children[parent].append(employee) + if any(not children[employee] and informTime[employee] != 0 for employee in range(n)): + return False + visited = set() + stack = [headID] + while stack: + employee = stack.pop() + if employee in visited: + return False + visited.add(employee) + stack.extend(children[employee]) + if len(visited) != n: + return False + if not isinstance(result, int) or isinstance(result, bool): + return False + def time(employee): + total = 0 + seen = set() + while manager[employee] != -1: + if employee in seen: + return None + seen.add(employee) + total += informTime[manager[employee]] + employee = manager[employee] + return total + values = [time(employee) for employee in range(n)] + if any(value is None for value in values): + return False + return result == max(values) +seed: 1376 +tests: + - name: single_employee + in: + n: 1 + headID: 0 + manager: [-1] + informTime: [0] + - name: two_employee + in: + n: 2 + headID: 0 + manager: [-1, 0] + informTime: [5, 0] + - name: star_zero + in: + n: 5 + headID: 0 + manager: [-1, 0, 0, 0, 0] + informTime: [0, 0, 0, 0, 0] + - name: star_positive + in: + n: 5 + headID: 0 + manager: [-1, 0, 0, 0, 0] + informTime: [10, 0, 0, 0, 0] + - name: chain_three + in: + n: 3 + headID: 0 + manager: [-1, 0, 1] + informTime: [1, 2, 0] + - name: chain_four + in: + n: 4 + headID: 0 + manager: [-1, 0, 1, 2] + informTime: [2, 3, 4, 0] + - name: chain_reverse_ids + in: + n: 4 + headID: 3 + manager: [1, 2, 3, -1] + informTime: [0, 1, 2, 3] + - name: balanced_tree + in: + n: 7 + headID: 0 + manager: [-1, 0, 0, 1, 1, 2, 2] + informTime: [3, 2, 2, 0, 0, 0, 0] + - name: uneven_tree + in: + n: 7 + headID: 0 + manager: [-1, 0, 0, 1, 1, 4, 4] + informTime: [1, 5, 0, 0, 2, 0, 0] + - name: deep_branch + in: + n: 6 + headID: 0 + manager: [-1, 0, 1, 2, 3, 4] + informTime: [10, 10, 10, 10, 10, 0] + - name: shallow_branch_wins + in: + n: 6 + headID: 0 + manager: [-1, 0, 0, 0, 1, 1] + informTime: [1, 100, 0, 0, 0, 0] + - name: zero_internal_times + in: + n: 6 + headID: 0 + manager: [-1, 0, 1, 1, 2, 2] + informTime: [0, 0, 0, 0, 0, 0] + - name: large_internal_time + in: + n: 4 + headID: 0 + manager: [-1, 0, 1, 1] + informTime: [1000, 1000, 0, 0] + - name: head_middle_id + in: + n: 5 + headID: 2 + manager: [2, 2, -1, 2, 3] + informTime: [0, 0, 4, 5, 0] + - name: broad_then_deep + in: + n: 8 + headID: 0 + manager: [-1, 0, 0, 0, 1, 2, 3, 6] + informTime: [2, 3, 4, 5, 0, 0, 6, 0] + - name: two_level_groups + in: + n: 10 + headID: 0 + manager: [-1, 0, 0, 0, 1, 1, 2, 2, 3, 3] + informTime: [7, 1, 2, 3, 0, 0, 0, 0, 0, 0] + - name: leaf_order_irrelevant + in: + n: 5 + headID: 4 + manager: [4, 4, 4, 4, -1] + informTime: [0, 0, 0, 0, 9] + - name: long_chain_small_times + in: + n: 8 + headID: 0 + manager: [-1, 0, 1, 2, 3, 4, 5, 6] + informTime: [1, 1, 1, 1, 1, 1, 1, 0] + - name: long_chain_large_times + in: + n: 8 + headID: 0 + manager: [-1, 0, 1, 2, 3, 4, 5, 6] + informTime: [10, 20, 30, 40, 50, 60, 70, 0] + - name: asymmetric_tree + in: + n: 9 + headID: 0 + manager: [-1, 0, 0, 1, 1, 1, 2, 6, 6] + informTime: [4, 3, 2, 0, 0, 0, 8, 0, 0] + - name: all_managers_zero + in: + n: 9 + headID: 0 + manager: [-1, 0, 0, 1, 1, 2, 2, 3, 4] + informTime: [0, 0, 0, 0, 0, 0, 0, 0, 0] + - name: max_root_delay + in: + n: 5 + headID: 0 + manager: [-1, 0, 0, 0, 0] + informTime: [1000, 0, 0, 0, 0] + - name: max_nested_delay + in: + n: 5 + headID: 0 + manager: [-1, 0, 1, 2, 3] + informTime: [1000, 1000, 1000, 1000, 0] + - name: root_last_in_array + in: + n: 6 + headID: 5 + manager: [1, 2, 3, 4, 5, -1] + informTime: [0, 0, 0, 0, 0, 1] + - name: many_leaves + in: + n: 12 + headID: 0 + manager: [-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + informTime: [11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - name: nested_many_leaves + in: + n: 12 + headID: 0 + manager: [-1, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 4] + informTime: [2, 4, 1, 3, 5, 0, 0, 0, 0, 0, 0, 0] + - name: alternating_delays + in: + n: 9 + headID: 0 + manager: [-1, 0, 1, 2, 3, 4, 5, 6, 7] + informTime: [1, 100, 1, 100, 1, 100, 1, 100, 0] + - name: two_branches + in: + n: 8 + headID: 0 + manager: [-1, 0, 0, 1, 1, 2, 2, 5] + informTime: [3, 4, 5, 0, 0, 6, 0, 0] + - name: four_depths + in: + n: 10 + headID: 0 + manager: [-1, 0, 0, 1, 2, 3, 4, 5, 6, 7] + informTime: [2, 3, 4, 5, 6, 7, 8, 9, 0, 0] + - name: manager_zero_ids + in: + n: 6 + headID: 0 + manager: [-1, 0, 0, 0, 0, 0] + informTime: [6, 0, 0, 0, 0, 0] + - name: head_two_branch + in: + n: 7 + headID: 2 + manager: [2, 2, -1, 2, 3, 4, 4] + informTime: [0, 0, 2, 3, 4, 0, 0] + - name: maximum_small_tree + in: + n: 15 + headID: 0 + manager: [-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + informTime: [9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - name: final_balanced + in: + n: 7 + headID: 0 + manager: [-1, 0, 0, 1, 1, 2, 2] + informTime: [10, 20, 30, 0, 0, 0, 0] + - name: short_branch_priority + in: + n: 6 + headID: 0 + manager: [-1, 0, 0, 1, 1, 2] + informTime: [5, 20, 1, 0, 0, 0] + - name: zero_head_delay + in: + n: 5 + headID: 0 + manager: [-1, 0, 0, 1, 2] + informTime: [0, 4, 6, 0, 0] + - name: head_nonzero_with_deep_chain + in: + n: 10 + headID: 7 + manager: [1, 2, 7, 0, 3, 4, 5, -1, 7, 8] + informTime: [2, 3, 4, 5, 6, 7, 0, 1, 8, 0] + - name: wide_zero_then_weighted_subtree + in: + n: 13 + headID: 0 + manager: [-1, 0, 0, 0, 0, 1, 1, 2, 2, 3, 4, 10, 10] + informTime: [0, 9, 2, 7, 1, 0, 0, 0, 0, 0, 4, 0, 0] + - name: irregular_high_delays + in: + n: 14 + headID: 9 + manager: [9, 9, 0, 0, 1, 1, 4, 2, 7, -1, 9, 10, 11, 11] + informTime: [1000, 1, 999, 0, 500, 0, 0, 250, 0, 1000, 750, 1000, 0, 0] + - name: long_mixed_chain + in: + n: 20 + headID: 19 + manager: + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, -1] + informTime: + [0, 2, 0, 3, 0, 5, 0, 7, 0, 11, 0, 13, 0, 17, 0, 19, 0, 23, 0, 29] + - name: dense_multi_level_company + in: + n: 31 + headID: 15 + manager: + [ + 15, + 15, + 15, + 15, + 0, + 0, + 1, + 1, + 2, + 2, + 3, + 3, + 4, + 4, + 4, + -1, + 15, + 16, + 16, + 17, + 17, + 18, + 18, + 19, + 19, + 20, + 20, + 21, + 21, + 22, + 22, + ] + informTime: + [ + 3, + 5, + 7, + 11, + 13, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 2, + 19, + 23, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] diff --git a/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.cpp b/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.cpp new file mode 100644 index 00000000..9da5e12b --- /dev/null +++ b/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int numOfMinutes(int n, int headID, vector& manager, vector& informTime) { + vector> children(n); + for (int employee = 0; employee < n; employee++) { + int parent = manager[employee]; + if (parent != -1) { + children[parent].push_back(employee); + } + } + stack> st; + st.push({headID, 0}); + int answer = 0; + while (!st.empty()) { + auto [employee, elapsed] = st.top(); + st.pop(); + answer = max(answer, elapsed); + for (int child : children[employee]) { + st.push({child, elapsed + informTime[employee]}); + } + } + return answer; + } +}; diff --git a/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.cs b/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.cs new file mode 100644 index 00000000..225494c7 --- /dev/null +++ b/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.cs @@ -0,0 +1,25 @@ +public class Solution { + public int NumOfMinutes(int n, int headID, int[] manager, int[] informTime) { + var children = new List[n]; + for (int i = 0; i < n; i++) { + children[i] = new List(); + } + for (int employee = 0; employee < n; employee++) { + int parent = manager[employee]; + if (parent != -1) { + children[parent].Add(employee); + } + } + var stack = new Stack<(int employee, int elapsed)>(); + stack.Push((headID, 0)); + int answer = 0; + while (stack.Count > 0) { + var (employee, elapsed) = stack.Pop(); + answer = Math.Max(answer, elapsed); + foreach (int child in children[employee]) { + stack.Push((child, elapsed + informTime[employee])); + } + } + return answer; + } +} diff --git a/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.dart b/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.dart new file mode 100644 index 00000000..8c6086d6 --- /dev/null +++ b/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.dart @@ -0,0 +1,26 @@ +class Solution { + int numOfMinutes(int n, int headID, List manager, List informTime) { + var children = List.generate(n, (_) => []); + for (int employee = 0; employee < n; employee++) { + int parent = manager[employee]; + if (parent != -1) { + children[parent].add(employee); + } + } + var stack = >[]; + stack.add([headID, 0]); + int answer = 0; + while (stack.isNotEmpty) { + var pair = stack.removeLast(); + int employee = pair[0]; + int elapsed = pair[1]; + if (elapsed > answer) { + answer = elapsed; + } + for (int child in children[employee]) { + stack.add([child, elapsed + informTime[employee]]); + } + } + return answer; + } +} diff --git a/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.go b/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.go new file mode 100644 index 00000000..2e49f878 --- /dev/null +++ b/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.go @@ -0,0 +1,25 @@ +func numOfMinutes(n int, headID int, manager []int, informTime []int) int { + children := make([][]int, n) + for employee, parent := range manager { + if parent != -1 { + children[parent] = append(children[parent], employee) + } + } + type pair struct { + employee int + elapsed int + } + stack := []pair{{headID, 0}} + answer := 0 + for len(stack) > 0 { + p := stack[len(stack)-1] + stack = stack[:len(stack)-1] + if p.elapsed > answer { + answer = p.elapsed + } + for _, child := range children[p.employee] { + stack = append(stack, pair{child, p.elapsed + informTime[p.employee]}) + } + } + return answer +} diff --git a/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.java b/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.java new file mode 100644 index 00000000..46e97110 --- /dev/null +++ b/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.java @@ -0,0 +1,27 @@ +class Solution { + public int numOfMinutes(int n, int headID, int[] manager, int[] informTime) { + List> children = new ArrayList<>(n); + for (int i = 0; i < n; i++) { + children.add(new ArrayList<>()); + } + for (int employee = 0; employee < n; employee++) { + int parent = manager[employee]; + if (parent != -1) { + children.get(parent).add(employee); + } + } + Deque stack = new ArrayDeque<>(); + stack.push(new int[]{headID, 0}); + int answer = 0; + while (!stack.isEmpty()) { + int[] pair = stack.pop(); + int employee = pair[0]; + int elapsed = pair[1]; + answer = Math.max(answer, elapsed); + for (int child : children.get(employee)) { + stack.push(new int[]{child, elapsed + informTime[employee]}); + } + } + return answer; + } +} diff --git a/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.kt b/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.kt new file mode 100644 index 00000000..59c25074 --- /dev/null +++ b/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.kt @@ -0,0 +1,22 @@ +class Solution { + fun numOfMinutes(n: Int, headID: Int, manager: IntArray, informTime: IntArray): Int { + val children = Array(n) { mutableListOf() } + for (employee in 0 until n) { + val parent = manager[employee] + if (parent != -1) { + children[parent].add(employee) + } + } + val stack = ArrayDeque>() + stack.addLast(Pair(headID, 0)) + var answer = 0 + while (stack.isNotEmpty()) { + val (employee, elapsed) = stack.removeLast() + answer = maxOf(answer, elapsed) + for (child in children[employee]) { + stack.addLast(Pair(child, elapsed + informTime[employee])) + } + } + return answer + } +} diff --git a/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.py b/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.py new file mode 100644 index 00000000..c47aa85d --- /dev/null +++ b/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.py @@ -0,0 +1,19 @@ +from typing import List + + +class Solution: + def numOfMinutes( + self, n: int, headID: int, manager: List[int], informTime: List[int] + ) -> int: + children = [[] for _ in range(n)] + for employee, parent in enumerate(manager): + if parent != -1: + children[parent].append(employee) + stack = [(headID, 0)] + answer = 0 + while stack: + employee, elapsed = stack.pop() + answer = max(answer, elapsed) + for child in children[employee]: + stack.append((child, elapsed + informTime[employee])) + return answer diff --git a/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.py2 b/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.py2 new file mode 100644 index 00000000..11fdc099 --- /dev/null +++ b/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.py2 @@ -0,0 +1,21 @@ +class Solution(object): + def numOfMinutes(self, n, headID, manager, informTime): + """ + :type n: int + :type headID: int + :type manager: List[int] + :type informTime: List[int] + :rtype: int + """ + children = [[] for _ in range(n)] + for employee, parent in enumerate(manager): + if parent != -1: + children[parent].append(employee) + stack = [(headID, 0)] + answer = 0 + while stack: + employee, elapsed = stack.pop() + answer = max(answer, elapsed) + for child in children[employee]: + stack.append((child, elapsed + informTime[employee])) + return answer diff --git a/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.rb b/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.rb new file mode 100644 index 00000000..10cb799f --- /dev/null +++ b/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.rb @@ -0,0 +1,21 @@ +# @param {Integer} n +# @param {Integer} head_id +# @param {Integer[]} manager +# @param {Integer[]} inform_time +# @return {Integer} +def num_of_minutes(n, head_id, manager, inform_time) + children = Array.new(n) { [] } + manager.each_with_index do |parent, employee| + children[parent].append(employee) if parent != -1 + end + stack = [[head_id, 0]] + answer = 0 + while !stack.empty? + employee, elapsed = stack.pop + answer = [answer, elapsed].max + children[employee].each do |child| + stack.append([child, elapsed + inform_time[employee]]) + end + end + answer +end diff --git a/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.rs b/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.rs new file mode 100644 index 00000000..5b3e6148 --- /dev/null +++ b/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.rs @@ -0,0 +1,21 @@ +impl Solution { + pub fn num_of_minutes(n: i32, head_id: i32, manager: Vec, inform_time: Vec) -> i32 { + let n = n as usize; + let head_id = head_id as usize; + let mut children: Vec> = vec![vec![]; n]; + for (employee, &parent) in manager.iter().enumerate() { + if parent != -1 { + children[parent as usize].push(employee); + } + } + let mut stack: Vec<(usize, i32)> = vec![(head_id, 0)]; + let mut answer = 0; + while let Some((employee, elapsed)) = stack.pop() { + answer = answer.max(elapsed); + for &child in &children[employee] { + stack.push((child, elapsed + inform_time[employee])); + } + } + answer + } +} diff --git a/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.swift b/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.swift new file mode 100644 index 00000000..b2e7df81 --- /dev/null +++ b/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func numOfMinutes(_ n: Int, _ headID: Int, _ manager: [Int], _ informTime: [Int]) -> Int { + var children = [[Int]](repeating: [], count: n) + for (employee, parent) in manager.enumerated() { + if parent != -1 { + children[parent].append(employee) + } + } + var stack = [(headID, 0)] + var answer = 0 + while !stack.isEmpty { + let (employee, elapsed) = stack.removeLast() + answer = max(answer, elapsed) + for child in children[employee] { + stack.append((child, elapsed + informTime[employee])) + } + } + return answer + } +} diff --git a/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.ts b/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.ts new file mode 100644 index 00000000..fc518795 --- /dev/null +++ b/tests/1001-1500/1376. time-needed-to-inform-all-employees/sol.ts @@ -0,0 +1,24 @@ +function numOfMinutes( + n: number, + headID: number, + manager: number[], + informTime: number[], +): number { + const children: number[][] = Array.from({ length: n }, () => []); + for (let employee = 0; employee < n; employee++) { + const parent = manager[employee]; + if (parent !== -1) { + children[parent].push(employee); + } + } + const stack: [number, number][] = [[headID, 0]]; + let answer = 0; + while (stack.length > 0) { + const [employee, elapsed] = stack.pop()!; + answer = Math.max(answer, elapsed); + for (const child of children[employee]) { + stack.push([child, elapsed + informTime[employee]]); + } + } + return answer; +} diff --git a/tests/1001-1500/1377. frog-position-after-t-seconds/manifest.yaml b/tests/1001-1500/1377. frog-position-after-t-seconds/manifest.yaml new file mode 100644 index 00000000..e3d14478 --- /dev/null +++ b/tests/1001-1500/1377. frog-position-after-t-seconds/manifest.yaml @@ -0,0 +1,773 @@ +entry: + id: 1377 + title: "frog-position-after-t-seconds" + params: + n: + type: int + edges: + type: array + items: + type: array + items: + type: int + t: + type: int + target: + type: int + call: + cpp: "Solution().frogPosition({n}, {edges}, {t}, {target})" + rust: "Solution::frog_position({n}, {edges}, {t}, {target})" + python3: "Solution().frogPosition({n}, {edges}, {t}, {target})" + python2: "Solution().frogPosition({n}, {edges}, {t}, {target})" + ruby: "frog_position({n}, {edges}, {t}, {target})" + java: "new Solution().frogPosition({n}, {edges}, {t}, {target})" + csharp: "new Solution().FrogPosition({n}, {edges}, {t}, {target})" + kotlin: "Solution().frogPosition({n}, {edges}, {t}, {target})" + go: "frogPosition({n}, {edges}, {t}, {target})" + dart: "Solution().frogPosition({n}, {edges}, {t}, {target})" + swift: "Solution().frogPosition({n}, {edges}, {t}, {target})" + typescript: "frogPosition({n}, {edges}, {t}, {target})" +judge: + type: "exact" +limits: + time_ms: 500 + memory_mb: 300 +oracle: + python3: + call: "Checker().frogPosition(n, edges, t, target, {result})" + checker: | + import math + + class Checker: + def frogPosition(self, n, edges, t, target, result): + if not isinstance(result, (int, float)) or not math.isfinite(result): + return False + graph = [[] for _ in range(n + 1)] + for a, b in edges: + graph[a].append(b) + graph[b].append(a) + mass = {1: 1.0} + visited = {1: frozenset((1,))} + for _ in range(t): + next_mass = {} + next_visited = {} + for vertex, probability in mass.items(): + seen = visited[vertex] + choices = [u for u in graph[vertex] if u not in seen] + if not choices: + next_mass[vertex] = next_mass.get(vertex, 0.0) + probability + next_visited[vertex] = seen + else: + share = probability / len(choices) + for child in choices: + next_mass[child] = next_mass.get(child, 0.0) + share + next_visited[child] = seen | frozenset((child,)) + mass, visited = next_mass, next_visited + expected = mass.get(target, 0.0) + return abs(float(result) - expected) <= 1e-5 +seed: 1377 +tests: + - name: "minimum_leaf" + in: + n: 2 + edges: + - [1, 2] + t: 1 + target: 2 + - name: "minimum_root_not_staying" + in: + n: 2 + edges: + - [1, 2] + t: 1 + target: 1 + - name: "path_three_exact_depth" + in: + n: 3 + edges: + - [1, 2] + - [2, 3] + t: 2 + target: 3 + - name: "path_three_internal_at_one" + in: + n: 3 + edges: + - [1, 2] + - [2, 3] + t: 1 + target: 2 + - name: "path_three_leaf_wait" + in: + n: 3 + edges: + - [1, 2] + - [2, 3] + t: 50 + target: 3 + - name: "path_three_root_after_move" + in: + n: 3 + edges: + - [1, 2] + - [2, 3] + t: 4 + target: 1 + - name: "star_first_leaf" + in: + n: 5 + edges: + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + t: 1 + target: 4 + - name: "star_root_after_one" + in: + n: 5 + edges: + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + t: 2 + target: 1 + - name: "star_leaf_wait" + in: + n: 5 + edges: + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + t: 50 + target: 2 + - name: "star_wrong_leaf_after_two" + in: + n: 5 + edges: + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + t: 2 + target: 5 + - name: "balanced_left_leaf" + in: + n: 7 + edges: + - [1, 2] + - [1, 3] + - [2, 4] + - [2, 5] + - [3, 6] + - [3, 7] + t: 2 + target: 4 + - name: "balanced_right_leaf" + in: + n: 7 + edges: + - [1, 2] + - [1, 3] + - [2, 4] + - [2, 5] + - [3, 6] + - [3, 7] + t: 2 + target: 7 + - name: "balanced_internal_at_one" + in: + n: 7 + edges: + - [1, 2] + - [1, 3] + - [2, 4] + - [2, 5] + - [3, 6] + - [3, 7] + t: 1 + target: 3 + - name: "balanced_root_late" + in: + n: 7 + edges: + - [1, 2] + - [1, 3] + - [2, 4] + - [2, 5] + - [3, 6] + - [3, 7] + t: 50 + target: 1 + - name: "uneven_branch_short_leaf" + in: + n: 6 + edges: + - [1, 2] + - [2, 3] + - [2, 4] + - [4, 5] + - [4, 6] + t: 2 + target: 3 + - name: "uneven_branch_deep_leaf" + in: + n: 6 + edges: + - [1, 2] + - [2, 3] + - [2, 4] + - [4, 5] + - [4, 6] + t: 3 + target: 5 + - name: "uneven_branch_deep_wait" + in: + n: 6 + edges: + - [1, 2] + - [2, 3] + - [2, 4] + - [4, 5] + - [4, 6] + t: 5 + target: 6 + - name: "uneven_branch_middle" + in: + n: 6 + edges: + - [1, 2] + - [2, 3] + - [2, 4] + - [4, 5] + - [4, 6] + t: 2 + target: 4 + - name: "uneven_branch_root" + in: + n: 6 + edges: + - [1, 2] + - [2, 3] + - [2, 4] + - [4, 5] + - [4, 6] + t: 4 + target: 1 + - name: "path_four_second_vertex" + in: + n: 4 + edges: + - [1, 2] + - [2, 3] + - [3, 4] + t: 1 + target: 2 + - name: "path_four_middle" + in: + n: 4 + edges: + - [1, 2] + - [2, 3] + - [3, 4] + t: 2 + target: 3 + - name: "path_four_end" + in: + n: 4 + edges: + - [1, 2] + - [2, 3] + - [3, 4] + t: 3 + target: 4 + - name: "path_four_stopped_end" + in: + n: 4 + edges: + - [1, 2] + - [2, 3] + - [3, 4] + t: 10 + target: 4 + - name: "path_four_unreachable_root" + in: + n: 4 + edges: + - [1, 2] + - [2, 3] + - [3, 4] + t: 4 + target: 1 + - name: "root_with_two_paths" + in: + n: 5 + edges: + - [1, 2] + - [1, 3] + - [3, 4] + - [4, 5] + t: 2 + target: 4 + - name: "root_with_two_paths_short_leaf" + in: + n: 5 + edges: + - [1, 2] + - [1, 3] + - [3, 4] + - [4, 5] + t: 2 + target: 2 + - name: "root_with_two_paths_deep_leaf" + in: + n: 5 + edges: + - [1, 2] + - [1, 3] + - [3, 4] + - [4, 5] + t: 4 + target: 5 + - name: "root_with_two_paths_wait" + in: + n: 5 + edges: + - [1, 2] + - [1, 3] + - [3, 4] + - [4, 5] + t: 50 + target: 5 + - name: "root_degree_three_deep" + in: + n: 8 + edges: + - [1, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [4, 6] + - [6, 7] + - [7, 8] + t: 4 + target: 8 + - name: "root_degree_three_short" + in: + n: 8 + edges: + - [1, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [4, 6] + - [6, 7] + - [7, 8] + t: 2 + target: 5 + - name: "root_degree_three_internal" + in: + n: 8 + edges: + - [1, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [4, 6] + - [6, 7] + - [7, 8] + t: 3 + target: 6 + - name: "balanced_leaf_too_early" + in: + n: 7 + edges: + - [1, 2] + - [1, 3] + - [2, 4] + - [2, 5] + - [3, 6] + - [3, 7] + t: 1 + target: 4 + - name: "balanced_leaf_stays_forever" + in: + n: 7 + edges: + - [1, 2] + - [1, 3] + - [2, 4] + - [2, 5] + - [3, 6] + - [3, 7] + t: 50 + target: 5 + - name: "mixed_depth_target_too_late" + in: + n: 8 + edges: + - [1, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [3, 6] + - [6, 7] + - [7, 8] + t: 2 + target: 8 + - name: "mixed_depth_deep_leaf" + in: + n: 8 + edges: + - [1, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [3, 6] + - [6, 7] + - [7, 8] + t: 4 + target: 8 + - name: "path_eight_midpoint" + in: + n: 8 + edges: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + t: 5 + target: 6 + - name: "path_eight_late_root" + in: + n: 8 + edges: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + t: 50 + target: 1 + - name: "maximum_path_end" + in: + n: 100 + 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] + - [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, 50] + - [50, 51] + - [51, 52] + - [52, 53] + - [53, 54] + - [54, 55] + - [55, 56] + - [56, 57] + - [57, 58] + - [58, 59] + - [59, 60] + - [60, 61] + - [61, 62] + - [62, 63] + - [63, 64] + - [64, 65] + - [65, 66] + - [66, 67] + - [67, 68] + - [68, 69] + - [69, 70] + - [70, 71] + - [71, 72] + - [72, 73] + - [73, 74] + - [74, 75] + - [75, 76] + - [76, 77] + - [77, 78] + - [78, 79] + - [79, 80] + - [80, 81] + - [81, 82] + - [82, 83] + - [83, 84] + - [84, 85] + - [85, 86] + - [86, 87] + - [87, 88] + - [88, 89] + - [89, 90] + - [90, 91] + - [91, 92] + - [92, 93] + - [93, 94] + - [94, 95] + - [95, 96] + - [96, 97] + - [97, 98] + - [98, 99] + - [99, 100] + t: 50 + target: 51 + - name: "maximum_star_leaf" + in: + n: 100 + 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] + - [1, 21] + - [1, 22] + - [1, 23] + - [1, 24] + - [1, 25] + - [1, 26] + - [1, 27] + - [1, 28] + - [1, 29] + - [1, 30] + - [1, 31] + - [1, 32] + - [1, 33] + - [1, 34] + - [1, 35] + - [1, 36] + - [1, 37] + - [1, 38] + - [1, 39] + - [1, 40] + - [1, 41] + - [1, 42] + - [1, 43] + - [1, 44] + - [1, 45] + - [1, 46] + - [1, 47] + - [1, 48] + - [1, 49] + - [1, 50] + - [1, 51] + - [1, 52] + - [1, 53] + - [1, 54] + - [1, 55] + - [1, 56] + - [1, 57] + - [1, 58] + - [1, 59] + - [1, 60] + - [1, 61] + - [1, 62] + - [1, 63] + - [1, 64] + - [1, 65] + - [1, 66] + - [1, 67] + - [1, 68] + - [1, 69] + - [1, 70] + - [1, 71] + - [1, 72] + - [1, 73] + - [1, 74] + - [1, 75] + - [1, 76] + - [1, 77] + - [1, 78] + - [1, 79] + - [1, 80] + - [1, 81] + - [1, 82] + - [1, 83] + - [1, 84] + - [1, 85] + - [1, 86] + - [1, 87] + - [1, 88] + - [1, 89] + - [1, 90] + - [1, 91] + - [1, 92] + - [1, 93] + - [1, 94] + - [1, 95] + - [1, 96] + - [1, 97] + - [1, 98] + - [1, 99] + - [1, 100] + t: 1 + target: 100 + - name: "maximum_star_root_late" + in: + n: 100 + 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] + - [1, 21] + - [1, 22] + - [1, 23] + - [1, 24] + - [1, 25] + - [1, 26] + - [1, 27] + - [1, 28] + - [1, 29] + - [1, 30] + - [1, 31] + - [1, 32] + - [1, 33] + - [1, 34] + - [1, 35] + - [1, 36] + - [1, 37] + - [1, 38] + - [1, 39] + - [1, 40] + - [1, 41] + - [1, 42] + - [1, 43] + - [1, 44] + - [1, 45] + - [1, 46] + - [1, 47] + - [1, 48] + - [1, 49] + - [1, 50] + - [1, 51] + - [1, 52] + - [1, 53] + - [1, 54] + - [1, 55] + - [1, 56] + - [1, 57] + - [1, 58] + - [1, 59] + - [1, 60] + - [1, 61] + - [1, 62] + - [1, 63] + - [1, 64] + - [1, 65] + - [1, 66] + - [1, 67] + - [1, 68] + - [1, 69] + - [1, 70] + - [1, 71] + - [1, 72] + - [1, 73] + - [1, 74] + - [1, 75] + - [1, 76] + - [1, 77] + - [1, 78] + - [1, 79] + - [1, 80] + - [1, 81] + - [1, 82] + - [1, 83] + - [1, 84] + - [1, 85] + - [1, 86] + - [1, 87] + - [1, 88] + - [1, 89] + - [1, 90] + - [1, 91] + - [1, 92] + - [1, 93] + - [1, 94] + - [1, 95] + - [1, 96] + - [1, 97] + - [1, 98] + - [1, 99] + - [1, 100] + t: 50 + target: 1 diff --git a/tests/1001-1500/1377. frog-position-after-t-seconds/sol.cpp b/tests/1001-1500/1377. frog-position-after-t-seconds/sol.cpp new file mode 100644 index 00000000..36369d2c --- /dev/null +++ b/tests/1001-1500/1377. frog-position-after-t-seconds/sol.cpp @@ -0,0 +1,44 @@ +class Solution { +public: + double frogPosition(int n, vector>& edges, int t, int target) { + unordered_map> neighbors; + for (int i = 1; i <= n; i++) { + neighbors[i] = unordered_set(); + } + for (const auto& edge : edges) { + int a = edge[0], b = edge[1]; + neighbors[a].insert(b); + neighbors[b].insert(a); + } + + unordered_set visited; + double probability = 0.0; + + function dfs = [&](int vertex, double chance, int elapsed) { + if (elapsed == t) { + if (vertex == target) { + probability = chance; + } + return; + } + visited.insert(vertex); + vector choices; + for (int child : neighbors[vertex]) { + if (visited.find(child) == visited.end()) { + choices.push_back(child); + } + } + + if (choices.empty()) { + dfs(vertex, chance, elapsed + 1); + } else { + for (int child : choices) { + dfs(child, chance / choices.size(), elapsed + 1); + } + } + }; + + dfs(1, 1.0, 0); + return probability; + } +}; diff --git a/tests/1001-1500/1377. frog-position-after-t-seconds/sol.cs b/tests/1001-1500/1377. frog-position-after-t-seconds/sol.cs new file mode 100644 index 00000000..89c1de6c --- /dev/null +++ b/tests/1001-1500/1377. frog-position-after-t-seconds/sol.cs @@ -0,0 +1,39 @@ +public class Solution { + public double FrogPosition(int n, int[][] edges, int t, int target) { + Dictionary> neighbors = new Dictionary>(); + for (int i = 1; i <= n; i++) { + neighbors[i] = new HashSet(); + } + foreach (var edge in edges) { + int a = edge[0], b = edge[1]; + neighbors[a].Add(b); + neighbors[b].Add(a); + } + + HashSet visited = new HashSet(); + double probability = 0.0; + + void dfs(int vertex, double chance, int elapsed) { + if (elapsed == t) { + if (vertex == target) { + probability = chance; + } + return; + } + visited.Add(vertex); + HashSet choices = new HashSet(neighbors[vertex]); + choices.ExceptWith(visited); + + if (choices.Count == 0) { + dfs(vertex, chance, elapsed + 1); + } else { + foreach (int child in choices) { + dfs(child, chance / choices.Count, elapsed + 1); + } + } + } + + dfs(1, 1.0, 0); + return probability; + } +} diff --git a/tests/1001-1500/1377. frog-position-after-t-seconds/sol.dart b/tests/1001-1500/1377. frog-position-after-t-seconds/sol.dart new file mode 100644 index 00000000..e7319aa2 --- /dev/null +++ b/tests/1001-1500/1377. frog-position-after-t-seconds/sol.dart @@ -0,0 +1,39 @@ +class Solution { + double frogPosition(int n, List> edges, int t, int target) { + Map> neighbors = {}; + for (int i = 1; i <= n; i++) { + neighbors[i] = {}; + } + for (var edge in edges) { + int a = edge[0], b = edge[1]; + neighbors[a]!.add(b); + neighbors[b]!.add(a); + } + + Set visited = {}; + double probability = 0.0; + + void dfs(int vertex, double chance, int elapsed) { + if (elapsed == t) { + if (vertex == target) { + probability = chance; + } + return; + } + visited.add(vertex); + Set choices = Set.from(neighbors[vertex]!); + choices.removeAll(visited); + + if (choices.isEmpty) { + dfs(vertex, chance, elapsed + 1); + } else { + for (int child in choices) { + dfs(child, chance / choices.length, elapsed + 1); + } + } + } + + dfs(1, 1.0, 0); + return probability; + } +} diff --git a/tests/1001-1500/1377. frog-position-after-t-seconds/sol.go b/tests/1001-1500/1377. frog-position-after-t-seconds/sol.go new file mode 100644 index 00000000..547ba02a --- /dev/null +++ b/tests/1001-1500/1377. frog-position-after-t-seconds/sol.go @@ -0,0 +1,42 @@ +func frogPosition(n int, edges [][]int, t int, target int) float64 { + neighbors := make(map[int]map[int]bool) + for i := 1; i <= n; i++ { + neighbors[i] = make(map[int]bool) + } + for _, edge := range edges { + a, b := edge[0], edge[1] + neighbors[a][b] = true + neighbors[b][a] = true + } + + visited := make(map[int]bool) + var probability float64 + + var dfs func(vertex int, chance float64, elapsed int) + dfs = func(vertex int, chance float64, elapsed int) { + if elapsed == t { + if vertex == target { + probability = chance + } + return + } + visited[vertex] = true + choices := []int{} + for child := range neighbors[vertex] { + if !visited[child] { + choices = append(choices, child) + } + } + + if len(choices) == 0 { + dfs(vertex, chance, elapsed+1) + } else { + for _, child := range choices { + dfs(child, chance/float64(len(choices)), elapsed+1) + } + } + } + + dfs(1, 1.0, 0) + return probability +} diff --git a/tests/1001-1500/1377. frog-position-after-t-seconds/sol.java b/tests/1001-1500/1377. frog-position-after-t-seconds/sol.java new file mode 100644 index 00000000..a0b4cbef --- /dev/null +++ b/tests/1001-1500/1377. frog-position-after-t-seconds/sol.java @@ -0,0 +1,35 @@ +class Solution { + public double frogPosition(int n, int[][] edges, int t, int target) { + Map> neighbors = new HashMap<>(); + for (int i = 1; i <= n; i++) { + neighbors.put(i, new HashSet<>()); + } + for (int[] edge : edges) { + int a = edge[0], b = edge[1]; + neighbors.get(a).add(b); + neighbors.get(b).add(a); + } + + return dfs(1, 1.0, 0, t, target, neighbors, new HashSet<>()); + } + + private double dfs(int vertex, double chance, int elapsed, int t, int target, + Map> neighbors, Set visited) { + if (elapsed == t) { + return vertex == target ? chance : 0.0; + } + visited.add(vertex); + Set choices = new HashSet<>(neighbors.get(vertex)); + choices.removeAll(visited); + + if (choices.isEmpty()) { + return dfs(vertex, chance, elapsed + 1, t, target, neighbors, visited); + } else { + for (int child : choices) { + double result = dfs(child, chance / choices.size(), elapsed + 1, t, target, neighbors, visited); + if (result > 0) return result; + } + } + return 0.0; + } +} diff --git a/tests/1001-1500/1377. frog-position-after-t-seconds/sol.kt b/tests/1001-1500/1377. frog-position-after-t-seconds/sol.kt new file mode 100644 index 00000000..bba0d650 --- /dev/null +++ b/tests/1001-1500/1377. frog-position-after-t-seconds/sol.kt @@ -0,0 +1,34 @@ +class Solution { + fun frogPosition(n: Int, edges: Array, t: Int, target: Int): Double { + val neighbors = mutableMapOf>() + for (i in 1..n) { + neighbors[i] = mutableSetOf() + } + for (edge in edges) { + val a = edge[0] + val b = edge[1] + neighbors[a]!!.add(b) + neighbors[b]!!.add(a) + } + + fun dfs(vertex: Int, chance: Double, elapsed: Int, visited: MutableSet): Double { + if (elapsed == t) { + return if (vertex == target) chance else 0.0 + } + visited.add(vertex) + val choices = neighbors[vertex]!!.subtract(visited) + + if (choices.isEmpty()) { + return dfs(vertex, chance, elapsed + 1, visited) + } else { + for (child in choices) { + val result = dfs(child, chance / choices.size, elapsed + 1, visited) + if (result > 0) return result + } + } + return 0.0 + } + + return dfs(1, 1.0, 0, mutableSetOf()) + } +} diff --git a/tests/1001-1500/1377. frog-position-after-t-seconds/sol.py b/tests/1001-1500/1377. frog-position-after-t-seconds/sol.py new file mode 100644 index 00000000..bf50f390 --- /dev/null +++ b/tests/1001-1500/1377. frog-position-after-t-seconds/sol.py @@ -0,0 +1,29 @@ +import collections +from typing import List + + +class Solution: + def frogPosition( + self, n: int, edges: List[List[int]], t: int, target: int + ) -> float: + neighbors = collections.defaultdict(set) + for a, b in edges: + neighbors[a].add(b) + neighbors[b].add(a) + + visited = set() + probability = 0.0 + + def dfs(vertex: int, chance: float, elapsed: int) -> None: + nonlocal probability + if elapsed == t: + if vertex == target: + probability = chance + return + visited.add(vertex) + choices = neighbors[vertex] - visited + for child in choices or [vertex]: + dfs(child, chance / (len(choices) or 1), elapsed + 1) + + dfs(1, 1.0, 0) + return probability diff --git a/tests/1001-1500/1377. frog-position-after-t-seconds/sol.py2 b/tests/1001-1500/1377. frog-position-after-t-seconds/sol.py2 new file mode 100644 index 00000000..cc57ea13 --- /dev/null +++ b/tests/1001-1500/1377. frog-position-after-t-seconds/sol.py2 @@ -0,0 +1,34 @@ +class Solution(object): + def frogPosition(self, n, edges, t, target): + """ + :type n: int + :type edges: List[List[int]] + :type t: int + :type target: int + :rtype: float + """ + from collections import defaultdict + + neighbors = defaultdict(set) + for a, b in edges: + neighbors[a].add(b) + neighbors[b].add(a) + + visited = set() + probability = [0.0] + + def dfs(vertex, chance, elapsed): + if elapsed == t: + if vertex == target: + probability[0] = chance + return + visited.add(vertex) + choices = neighbors[vertex] - visited + if not choices: + dfs(vertex, chance, elapsed + 1) + else: + for child in choices: + dfs(child, chance / len(choices), elapsed + 1) + + dfs(1, 1.0, 0) + return probability[0] diff --git a/tests/1001-1500/1377. frog-position-after-t-seconds/sol.rb b/tests/1001-1500/1377. frog-position-after-t-seconds/sol.rb new file mode 100644 index 00000000..3a240992 --- /dev/null +++ b/tests/1001-1500/1377. frog-position-after-t-seconds/sol.rb @@ -0,0 +1,36 @@ +# @param {Integer} n +# @param {Integer[][]} edges +# @param {Integer} t +# @param {Integer} target +# @return {Float} +def frog_position(n, edges, t, target) + neighbors = Hash.new { |h, k| h[k] = Set.new } + edges.each do |a, b| + neighbors[a].add(b) + neighbors[b].add(a) + end + + visited = Set.new + probability = 0.0 + + dfs = lambda do |vertex, chance, elapsed| + if elapsed == t + if vertex == target + probability = chance + end + return + end + visited.add(vertex) + choices = neighbors[vertex] - visited + if choices.empty? + dfs.call(vertex, chance, elapsed + 1) + else + choices.each do |child| + dfs.call(child, chance / choices.size.to_f, elapsed + 1) + end + end + end + + dfs.call(1, 1.0, 0) + probability +end diff --git a/tests/1001-1500/1377. frog-position-after-t-seconds/sol.rs b/tests/1001-1500/1377. frog-position-after-t-seconds/sol.rs new file mode 100644 index 00000000..28b91e77 --- /dev/null +++ b/tests/1001-1500/1377. frog-position-after-t-seconds/sol.rs @@ -0,0 +1,59 @@ +impl Solution { + pub fn frog_position(n: i32, edges: Vec>, t: i32, target: i32) -> f64 { + use std::collections::{HashMap, HashSet}; + + let mut neighbors: HashMap> = HashMap::new(); + for i in 1..=n { + neighbors.insert(i, HashSet::new()); + } + for edge in edges { + let a = edge[0]; + let b = edge[1]; + neighbors.get_mut(&a).unwrap().insert(b); + neighbors.get_mut(&b).unwrap().insert(a); + } + + fn dfs( + vertex: i32, + chance: f64, + elapsed: i32, + t: i32, + target: i32, + neighbors: &HashMap>, + visited: &mut HashSet, + ) -> f64 { + if elapsed == t { + return if vertex == target { chance } else { 0.0 }; + } + visited.insert(vertex); + let choices: Vec = neighbors[&vertex] + .iter() + .filter(|&&child| !visited.contains(&child)) + .cloned() + .collect(); + + if choices.is_empty() { + return dfs(vertex, chance, elapsed + 1, t, target, neighbors, visited); + } else { + let probability = chance / choices.len() as f64; + for child in choices { + let result = dfs( + child, + probability, + elapsed + 1, + t, + target, + neighbors, + visited, + ); + if result > 0.0 { + return result; + } + } + } + 0.0 + } + + dfs(1, 1.0, 0, t, target, &neighbors, &mut HashSet::new()) + } +} diff --git a/tests/1001-1500/1377. frog-position-after-t-seconds/sol.swift b/tests/1001-1500/1377. frog-position-after-t-seconds/sol.swift new file mode 100644 index 00000000..95e2593e --- /dev/null +++ b/tests/1001-1500/1377. frog-position-after-t-seconds/sol.swift @@ -0,0 +1,38 @@ +class Solution { + func frogPosition(_ n: Int, _ edges: [[Int]], _ t: Int, _ target: Int) -> Double { + var neighbors = [Int: Set]() + for i in 1...n { + neighbors[i] = Set() + } + for edge in edges { + let a = edge[0], b = edge[1] + neighbors[a]!.insert(b) + neighbors[b]!.insert(a) + } + + var visited = Set() + var probability = 0.0 + + func dfs(_ vertex: Int, _ chance: Double, _ elapsed: Int) { + if elapsed == t { + if vertex == target { + probability = chance + } + return + } + visited.insert(vertex) + let choices = neighbors[vertex]!.subtracting(visited) + + if choices.isEmpty { + dfs(vertex, chance, elapsed + 1) + } else { + for child in choices { + dfs(child, chance / Double(choices.count), elapsed + 1) + } + } + } + + dfs(1, 1.0, 0) + return probability + } +} diff --git a/tests/1001-1500/1377. frog-position-after-t-seconds/sol.ts b/tests/1001-1500/1377. frog-position-after-t-seconds/sol.ts new file mode 100644 index 00000000..225dadd0 --- /dev/null +++ b/tests/1001-1500/1377. frog-position-after-t-seconds/sol.ts @@ -0,0 +1,43 @@ +function frogPosition( + n: number, + edges: number[][], + t: number, + target: number, +): number { + const neighbors: Map> = new Map(); + for (let i = 1; i <= n; i++) { + neighbors.set(i, new Set()); + } + for (const [a, b] of edges) { + neighbors.get(a)!.add(b); + neighbors.get(b)!.add(a); + } + + const visited: Set = new Set(); + let probability = 0; + + function dfs(vertex: number, chance: number, elapsed: number): void { + if (elapsed === t) { + if (vertex === target) { + probability = chance; + } + return; + } + visited.add(vertex); + const choices = new Set(neighbors.get(vertex)!); + for (const v of visited) { + choices.delete(v); + } + + if (choices.size === 0) { + dfs(vertex, chance, elapsed + 1); + } else { + for (const child of choices) { + dfs(child, chance / choices.size, elapsed + 1); + } + } + } + + dfs(1, 1.0, 0); + return probability; +} diff --git a/tests/1001-1500/1380. lucky-numbers-in-a-matrix/manifest.yaml b/tests/1001-1500/1380. lucky-numbers-in-a-matrix/manifest.yaml new file mode 100644 index 00000000..23197d37 --- /dev/null +++ b/tests/1001-1500/1380. lucky-numbers-in-a-matrix/manifest.yaml @@ -0,0 +1,435 @@ +entry: + id: 1380 + title: "lucky-numbers-in-a-matrix" + params: + matrix: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().luckyNumbers({matrix})" + rust: "Solution::lucky_numbers({matrix})" + python3: "Solution().luckyNumbers({matrix})" + python2: "Solution().luckyNumbers({matrix})" + ruby: "lucky_numbers({matrix})" + java: "new Solution().luckyNumbers({matrix})" + csharp: "new Solution().LuckyNumbers({matrix})" + kotlin: "Solution().luckyNumbers({matrix})" + go: "luckyNumbers({matrix})" + dart: "Solution().luckyNumbers({matrix})" + swift: "Solution().luckyNumbers({matrix})" + typescript: "luckyNumbers({matrix})" + +judge: + type: "ignore_order" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().luckyNumbers(matrix, {result})" + checker: | + class Checker: + def luckyNumbers(self, matrix, result): + if not isinstance(result, list): + return False + if any(type(value) is not int for value in result): + return False + row_mins = [min(row) for row in matrix] + col_maxes = [max(matrix[row][col] for row in range(len(matrix))) for col in range(len(matrix[0]))] + expected = [] + for row_index, row in enumerate(matrix): + for col_index, value in enumerate(row): + if value == row_mins[row_index] and value == col_maxes[col_index]: + expected.append(value) + return len(result) == len(set(result)) and set(result) == set(expected) + +seed: 1380 + +tests: + - name: "example-one" + in: + matrix: + elemType: "int" + value: + - [3, 7, 8] + - [9, 11, 13] + - [15, 16, 17] + - name: "example-two" + in: + matrix: + elemType: "int" + value: + - [1, 10, 4, 2] + - [9, 3, 8, 7] + - [15, 16, 17, 12] + - name: "example-three" + in: + matrix: + elemType: "int" + value: + - [7, 8] + - [1, 2] + - name: "single-cell" + in: + matrix: + elemType: "int" + value: + - [42] + - name: "single-row" + in: + matrix: + elemType: "int" + value: + - [5, 2, 8, 1, 9] + - name: "single-column" + in: + matrix: + elemType: "int" + value: + - [1] + - [7] + - [3] + - [9] + - name: "two-by-two-one" + in: + matrix: + elemType: "int" + value: + - [1, 2] + - [3, 4] + - name: "two-by-two-two" + in: + matrix: + elemType: "int" + value: + - [4, 1] + - [2, 3] + - name: "all-equal" + in: + matrix: + elemType: "int" + value: + - [6, 7, 8] + - [9, 10, 11] + - name: "repeated-minima" + in: + matrix: + elemType: "int" + value: + - [1, 2, 4] + - [3, 5, 6] + - [7, 8, 9] + - name: "negative-values" + in: + matrix: + elemType: "int" + value: + - [5, 2, 8] + - [3, 4, 1] + - name: "mixed-sign" + in: + matrix: + elemType: "int" + value: + - [1, 4, 3] + - [2, 5, 6] + - [7, 8, 9] + - name: "three-by-three-diagonal" + in: + matrix: + elemType: "int" + value: + - [1, 9, 6] + - [8, 2, 7] + - [5, 4, 3] + - name: "three-by-three-no-lucky" + in: + matrix: + elemType: "int" + value: + - [5, 1, 4] + - [2, 6, 3] + - [7, 8, 9] + - name: "three-by-four" + in: + matrix: + elemType: "int" + value: + - [10, 20, 30, 40] + - [9, 19, 29, 39] + - [8, 18, 28, 38] + - name: "four-by-three" + in: + matrix: + elemType: "int" + value: + - [4, 8, 12] + - [3, 7, 11] + - [2, 6, 10] + - [1, 5, 9] + - name: "four-by-four-corners" + in: + matrix: + elemType: "int" + value: + - [1, 9, 8, 7] + - [6, 2, 5, 4] + - [3, 10, 11, 12] + - [16, 13, 14, 15] + - name: "four-by-four-middle" + in: + matrix: + elemType: "int" + value: + - [20, 3, 30, 40] + - [50, 6, 60, 70] + - [80, 9, 90, 100] + - [110, 12, 120, 130] + - name: "five-by-five-rising" + 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] + - name: "five-by-five-falling" + in: + matrix: + elemType: "int" + value: + - [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: "five-by-two" + in: + matrix: + elemType: "int" + value: + - [8, 1] + - [7, 2] + - [6, 3] + - [5, 4] + - [9, 10] + - name: "two-by-five" + in: + matrix: + elemType: "int" + value: + - [9, 8, 7, 6, 5] + - [1, 2, 3, 4, 10] + - name: "six-by-six-center" + in: + matrix: + elemType: "int" + value: + - [30, 31, 32, 33, 34, 35] + - [29, 10, 11, 12, 13, 36] + - [28, 9, 20, 21, 14, 37] + - [27, 8, 19, 22, 15, 38] + - [26, 7, 18, 17, 16, 39] + - [25, 24, 23, 6, 5, 40] + - name: "six-by-four" + in: + matrix: + elemType: "int" + value: + - [14, 24, 34, 44] + - [13, 23, 33, 43] + - [12, 22, 32, 42] + - [11, 21, 31, 41] + - [10, 20, 30, 40] + - [9, 19, 29, 39] + - name: "large-magnitude" + in: + matrix: + elemType: "int" + value: + - [100000, 2, 50000] + - [99999, 3, 49999] + - [99998, 4, 49998] + - name: "duplicate-columns" + in: + matrix: + elemType: "int" + value: + - [2, 5, 8, 11] + - [1, 6, 9, 12] + - [3, 7, 10, 13] + - name: "row-minimum-not-column-max" + in: + matrix: + elemType: "int" + value: + - [1, 100, 101] + - [2, 3, 4] + - [5, 6, 7] + - name: "column-maximum-not-row-minimum" + in: + matrix: + elemType: "int" + value: + - [10, 1, 2] + - [9, 8, 7] + - [6, 5, 4] + - name: "seven-by-three" + in: + matrix: + elemType: "int" + value: + - [7, 20, 30] + - [6, 19, 29] + - [5, 18, 28] + - [4, 17, 27] + - [3, 16, 26] + - [2, 15, 25] + - [1, 14, 24] + - name: "three-by-seven" + in: + matrix: + elemType: "int" + value: + - [1, 8, 7, 6, 5, 4, 3] + - [9, 2, 10, 11, 12, 13, 14] + - [15, 16, 17, 18, 19, 20, 21] + - name: "eight-by-eight" + in: + matrix: + elemType: "int" + value: + - [8, 80, 81, 82, 83, 84, 85, 86] + - [7, 70, 71, 72, 73, 74, 75, 87] + - [6, 60, 61, 62, 63, 64, 88, 89] + - [5, 50, 51, 52, 53, 90, 91, 92] + - [4, 40, 41, 42, 93, 94, 95, 96] + - [3, 30, 31, 97, 98, 99, 100, 101] + - [2, 20, 102, 103, 104, 105, 106, 107] + - [1, 108, 109, 110, 111, 112, 113, 114] + - name: "nine-by-two-ordered" + in: + matrix: + elemType: "int" + value: + - [1, 20] + - [2, 19] + - [3, 18] + - [4, 17] + - [5, 16] + - [6, 15] + - [7, 14] + - [8, 13] + - [9, 12] + - name: "ten-by-ten-pattern" + in: + matrix: + elemType: "int" + value: + - [1, 50, 51, 52, 53, 54, 55, 56, 57, 58] + - [2, 40, 41, 42, 43, 44, 45, 46, 47, 59] + - [3, 30, 31, 32, 33, 34, 35, 36, 60, 61] + - [4, 20, 21, 22, 23, 24, 25, 62, 63, 64] + - [5, 10, 11, 12, 13, 14, 65, 66, 67, 68] + - [6, 7, 8, 9, 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] + - name: "ten-by-one" + in: + matrix: + elemType: "int" + value: + - [10] + - [1] + - [9] + - [2] + - [8] + - [3] + - [7] + - [4] + - [6] + - [5] + - name: "eleven-by-two-ties" + in: + matrix: + elemType: "int" + value: + - [11, 20] + - [10, 21] + - [9, 22] + - [8, 23] + - [7, 24] + - [6, 25] + - [5, 26] + - [4, 27] + - [3, 28] + - [2, 29] + - [1, 30] + - name: "one-by-ten" + in: + matrix: + elemType: "int" + value: + - [19, 4, 27, 13, 8, 31, 2, 25, 16, 10] + - name: "two-by-two-high-values" + in: + matrix: + elemType: "int" + value: + - [99996, 99999] + - [99998, 99997] + - name: "twelve-by-four" + in: + matrix: + elemType: "int" + value: + - [48, 101, 201, 301] + - [47, 100, 200, 300] + - [46, 99, 199, 299] + - [45, 98, 198, 298] + - [44, 97, 197, 297] + - [43, 96, 196, 296] + - [42, 95, 195, 295] + - [41, 94, 194, 294] + - [40, 93, 193, 293] + - [39, 92, 192, 292] + - [38, 91, 191, 291] + - [37, 90, 190, 290] + - name: "four-by-twelve" + in: + matrix: + elemType: "int" + value: + - [1, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60] + - [2, 40, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70] + - [3, 30, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80] + - [4, 20, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90] + - name: "fifteen-by-one" + in: + matrix: + elemType: "int" + value: + - [15] + - [3] + - [14] + - [2] + - [13] + - [4] + - [12] + - [5] + - [11] + - [6] + - [10] + - [7] + - [9] + - [8] + - [1] diff --git a/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.cpp b/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.cpp new file mode 100644 index 00000000..4bb6e697 --- /dev/null +++ b/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + vector luckyNumbers(vector>& matrix) { + int rows = matrix.size(); + int cols = matrix[0].size(); + vector ans; + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + int ele1 = INT_MAX; + for (int k = 0; k < cols; k++) { + if (matrix[i][k] < ele1) ele1 = matrix[i][k]; + } + int ele2 = INT_MIN; + for (int k = 0; k < rows; k++) { + if (matrix[k][j] > ele2) ele2 = matrix[k][j]; + } + if (ele1 == matrix[i][j] && ele2 == matrix[i][j]) { + ans.push_back(matrix[i][j]); + } + } + } + return ans; + } +}; diff --git a/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.cs b/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.cs new file mode 100644 index 00000000..f88dddd5 --- /dev/null +++ b/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.cs @@ -0,0 +1,23 @@ +public class Solution { + public IList LuckyNumbers(int[][] matrix) { + int rows = matrix.Length; + int cols = matrix[0].Length; + IList ans = new List(); + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + int ele1 = int.MaxValue; + for (int k = 0; k < cols; k++) { + if (matrix[i][k] < ele1) ele1 = matrix[i][k]; + } + int ele2 = int.MinValue; + for (int k = 0; k < rows; k++) { + if (matrix[k][j] > ele2) ele2 = matrix[k][j]; + } + if (ele1 == matrix[i][j] && ele2 == matrix[i][j]) { + ans.Add(matrix[i][j]); + } + } + } + return ans; + } +} diff --git a/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.dart b/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.dart new file mode 100644 index 00000000..ab41fd2b --- /dev/null +++ b/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.dart @@ -0,0 +1,23 @@ +class Solution { + List luckyNumbers(List> matrix) { + int rows = matrix.length; + int cols = matrix[0].length; + List ans = []; + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + int ele1 = matrix[i][0]; + for (int k = 1; k < cols; k++) { + if (matrix[i][k] < ele1) ele1 = matrix[i][k]; + } + int ele2 = matrix[0][j]; + for (int k = 1; k < rows; k++) { + if (matrix[k][j] > ele2) ele2 = matrix[k][j]; + } + if (ele1 == matrix[i][j] && ele2 == matrix[i][j]) { + ans.add(matrix[i][j]); + } + } + } + return ans; + } +} diff --git a/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.go b/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.go new file mode 100644 index 00000000..84eaed76 --- /dev/null +++ b/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.go @@ -0,0 +1,25 @@ +func luckyNumbers(matrix [][]int) []int { + rows := len(matrix) + cols := len(matrix[0]) + ans := make([]int, 0) + for i := 0; i < rows; i++ { + for j := 0; j < cols; j++ { + ele1 := matrix[i][0] + for k := 1; k < cols; k++ { + if matrix[i][k] < ele1 { + ele1 = matrix[i][k] + } + } + ele2 := matrix[0][j] + for k := 1; k < rows; k++ { + if matrix[k][j] > ele2 { + ele2 = matrix[k][j] + } + } + if ele1 == matrix[i][j] && ele2 == matrix[i][j] { + ans = append(ans, matrix[i][j]) + } + } + } + return ans +} diff --git a/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.java b/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.java new file mode 100644 index 00000000..826eecc4 --- /dev/null +++ b/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.java @@ -0,0 +1,23 @@ +class Solution { + public List luckyNumbers(int[][] matrix) { + int rows = matrix.length; + int cols = matrix[0].length; + List ans = new ArrayList<>(); + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + int ele1 = Integer.MAX_VALUE; + for (int k = 0; k < cols; k++) { + if (matrix[i][k] < ele1) ele1 = matrix[i][k]; + } + int ele2 = Integer.MIN_VALUE; + for (int k = 0; k < rows; k++) { + if (matrix[k][j] > ele2) ele2 = matrix[k][j]; + } + if (ele1 == matrix[i][j] && ele2 == matrix[i][j]) { + ans.add(matrix[i][j]); + } + } + } + return ans; + } +} diff --git a/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.kt b/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.kt new file mode 100644 index 00000000..f84f9e3b --- /dev/null +++ b/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.kt @@ -0,0 +1,23 @@ +class Solution { + fun luckyNumbers(matrix: Array): List { + val rows = matrix.size + val cols = matrix[0].size + val ans = mutableListOf() + for (i in 0 until rows) { + for (j in 0 until cols) { + var ele1 = Int.MAX_VALUE + for (k in 0 until cols) { + if (matrix[i][k] < ele1) ele1 = matrix[i][k] + } + var ele2 = Int.MIN_VALUE + for (k in 0 until rows) { + if (matrix[k][j] > ele2) ele2 = matrix[k][j] + } + if (ele1 == matrix[i][j] && ele2 == matrix[i][j]) { + ans.add(matrix[i][j]) + } + } + } + return ans + } +} diff --git a/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.py b/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.py new file mode 100644 index 00000000..116fe082 --- /dev/null +++ b/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.py @@ -0,0 +1,11 @@ +class Solution: + def luckyNumbers(self, matrix): + rows, cols = len(matrix), len(matrix[0]) + ans = [] + for i in range(rows): + for j in range(cols): + ele1 = min(matrix[i][k] for k in range(cols)) + ele2 = max(matrix[k][j] for k in range(rows)) + if ele1 == matrix[i][j] and ele2 == matrix[i][j]: + ans.append(matrix[i][j]) + return ans diff --git a/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.py2 b/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.py2 new file mode 100644 index 00000000..9ae18d8d --- /dev/null +++ b/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.py2 @@ -0,0 +1,15 @@ +class Solution(object): + def luckyNumbers(self, matrix): + """ + :type matrix: List[List[int]] + :rtype: List[int] + """ + rows, cols = len(matrix), len(matrix[0]) + ans = [] + for i in range(rows): + for j in range(cols): + ele1 = min(matrix[i][k] for k in range(cols)) + ele2 = max(matrix[k][j] for k in range(rows)) + if ele1 == matrix[i][j] and ele2 == matrix[i][j]: + ans.append(matrix[i][j]) + return ans diff --git a/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.rb b/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.rb new file mode 100644 index 00000000..29708942 --- /dev/null +++ b/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.rb @@ -0,0 +1,17 @@ +# @param {Integer[][]} matrix +# @return {Integer[]} +def lucky_numbers(matrix) + rows = matrix.length + cols = matrix[0].length + ans = [] + (0...rows).each do |i| + (0...cols).each do |j| + ele1 = (0...cols).map { |k| matrix[i][k] }.min + ele2 = (0...rows).map { |k| matrix[k][j] }.max + if ele1 == matrix[i][j] && ele2 == matrix[i][j] + ans << matrix[i][j] + end + end + end + ans +end diff --git a/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.rs b/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.rs new file mode 100644 index 00000000..d2922cd2 --- /dev/null +++ b/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.rs @@ -0,0 +1,27 @@ +impl Solution { + pub fn lucky_numbers(matrix: Vec>) -> Vec { + let rows = matrix.len(); + let cols = matrix[0].len(); + let mut ans = Vec::new(); + for i in 0..rows { + for j in 0..cols { + let mut ele1 = i32::MAX; + for k in 0..cols { + if matrix[i][k] < ele1 { + ele1 = matrix[i][k]; + } + } + let mut ele2 = i32::MIN; + for k in 0..rows { + if matrix[k][j] > ele2 { + ele2 = matrix[k][j]; + } + } + if ele1 == matrix[i][j] && ele2 == matrix[i][j] { + ans.push(matrix[i][j]); + } + } + } + ans + } +} diff --git a/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.swift b/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.swift new file mode 100644 index 00000000..a5763105 --- /dev/null +++ b/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.swift @@ -0,0 +1,27 @@ +class Solution { + func luckyNumbers(_ matrix: [[Int]]) -> [Int] { + let rows = matrix.count + let cols = matrix[0].count + var ans: [Int] = [] + for i in 0.. ele2 { + ele2 = matrix[k][j] + } + } + if ele1 == matrix[i][j] && ele2 == matrix[i][j] { + ans.append(matrix[i][j]) + } + } + } + return ans + } +} diff --git a/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.ts b/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.ts new file mode 100644 index 00000000..fd56819a --- /dev/null +++ b/tests/1001-1500/1380. lucky-numbers-in-a-matrix/sol.ts @@ -0,0 +1,21 @@ +function luckyNumbers(matrix: number[][]): number[] { + const rows = matrix.length; + const cols = matrix[0].length; + const ans: number[] = []; + for (let i = 0; i < rows; i++) { + for (let j = 0; j < cols; j++) { + let ele1 = matrix[i][0]; + for (let k = 1; k < cols; k++) { + if (matrix[i][k] < ele1) ele1 = matrix[i][k]; + } + let ele2 = matrix[0][j]; + for (let k = 1; k < rows; k++) { + if (matrix[k][j] > ele2) ele2 = matrix[k][j]; + } + if (ele1 === matrix[i][j] && ele2 === matrix[i][j]) { + ans.push(matrix[i][j]); + } + } + } + return ans; +} diff --git a/tests/1001-1500/1382. balance-a-binary-search-tree/manifest.yaml b/tests/1001-1500/1382. balance-a-binary-search-tree/manifest.yaml new file mode 100644 index 00000000..35906b8f --- /dev/null +++ b/tests/1001-1500/1382. balance-a-binary-search-tree/manifest.yaml @@ -0,0 +1,544 @@ +entry: + id: 1382 + title: balance-a-binary-search-tree + params: + root: + type: tree_node + call: + cpp: "treeNodeToArray(Solution().balanceBST({root}))" + rust: "TreeNode::tree_node_to_array(Solution::balance_bst({root}))" + python3: "tree_node_to_array(Solution().balanceBST({root}))" + python2: "tree_node_to_array(Solution().balanceBST({root}))" + ruby: "tree_node_to_array(balance_bst({root}))" + java: "TreeNode.treeNodeToArray(new Solution().balanceBST({root}))" + csharp: "TreeNode.TreeNodeToArray(new Solution().BalanceBST({root}))" + kotlin: "treeNodeToArray(Solution().balanceBST({root}))" + go: "treeNodeToArray(balanceBST({root}))" + dart: "tree_node_to_array(Solution().balanceBST({root}))" + swift: "tree_node_to_array(Solution().balanceBST({root}))" + typescript: "treeNodeToArray(balanceBST({root}))" + +judge: + type: exact + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().balanceBST(root, {result})" + checker: | + from collections import Counter + + class Checker: + def parse(self, values): + if not isinstance(values, list) or not values or values[0] is None: + return None + root = [values[0], None, None] + queue = [root] + pos = 1 + for node in queue: + for side in (1, 2): + if pos >= len(values): + break + value = values[pos] + pos += 1 + if value is not None: + if not isinstance(value, int): + return None + child = [value, None, None] + node[side] = child + queue.append(child) + if pos != len(values): + return None + return root + + def inspect(self, node, low, high, values): + if node is None: + return 0 + value = node[0] + if value <= low or value >= high: + return -1 + values.append(value) + left_height = self.inspect(node[1], low, value, values) + right_height = self.inspect(node[2], value, high, values) + if left_height < 0 or right_height < 0 or abs(left_height - right_height) > 1: + return -1 + return max(left_height, right_height) + 1 + + def collect(self, node, low, high, values): + if node is None: + return True + value = node[0] + if value <= low or value >= high: + return False + values.append(value) + return (self.collect(node[1], low, value, values) + and self.collect(node[2], value, high, values)) + + def balanceBST(self, root, result): + source = self.parse(root) + candidate = self.parse(result) + if source is None or candidate is None: + return False + source_values = [] + candidate_values = [] + if not self.collect(source, float("-inf"), float("inf"), source_values): + return False + if self.inspect(candidate, float("-inf"), float("inf"), candidate_values) < 0: + return False + return Counter(source_values) == Counter(candidate_values) + +seed: 1382 + +tests: + - name: example_right_chain + in: + root: [1, null, 2, null, 3, null, 4, null, null] + + - name: example_already_balanced + in: + root: [2, 1, 3] + + - name: single_node_min + in: + root: [1] + + - name: two_nodes + in: + root: [2, 1] + + - name: two_nodes_right + in: + root: [1, null, 2] + + - name: three_left_chain + in: + root: [3, 2, null, 1] + + - name: four_left_chain + in: + root: [4, 3, null, 2, null, 1] + + - name: five_right_chain + in: + root: [1, null, 2, null, 3, null, 4, null, 5] + + - name: six_left_chain + in: + root: [6, 5, null, 4, null, 3, null, 2, null, 1] + + - name: seven_perfect + in: + root: [4, 2, 6, 1, 3, 5, 7] + + - name: seven_right_chain + in: + root: [1, null, 2, null, 3, null, 4, null, 5, null, 6, null, 7] + + - name: seven_left_chain + in: + root: [7, 6, null, 5, null, 4, null, 3, null, 2, null, 1] + + - name: seven_left_heavy + in: + root: [5, 3, 7, 2, 4, 6, null, 1] + + - name: seven_right_heavy + in: + root: [3, 1, 6, null, 2, 4, 7, null, null, null, 5] + + - name: eight_unbalanced + in: + root: [8, 4, null, 2, 6, 1, 3, 5, 7] + + - name: eight_sparse + in: + root: [10, 5, 15, 2, 7, null, 20, 1, 3, 6, 8] + + - name: nine_balanced + in: + root: [5, 3, 8, 2, 4, 7, 9, 1, null, null, null, 6] + + - name: nine_right_heavy + in: + root: [4, 2, 8, 1, 3, 6, 9, null, null, null, null, 5, 7] + + - name: ten_left_chain + in: + root: + [ + 10, + 9, + null, + 8, + null, + 7, + null, + 6, + null, + 5, + null, + 4, + null, + 3, + null, + 2, + null, + 1, + ] + + - name: ten_right_chain + in: + root: + [ + 1, + null, + 2, + null, + 3, + null, + 4, + null, + 5, + null, + 6, + null, + 7, + null, + 8, + null, + 9, + null, + 10, + ] + + - name: ten_sparse + in: + root: [6, 3, 9, 2, 4, 8, 10, 1, null, null, 5, 7] + + - name: eleven_mixed_shape + in: + root: [10, 5, 15, 3, 7, 12, 18, 1, 4, 6, 8] + + - name: eleven_sparse_right + in: + root: [20, 10, 30, null, 15, null, 40, null, 17] + + - name: eleven_sparse_left + in: + root: [20, 10, 30, 5, null, 25, null, 2, 7] + + - name: twelve_chain + in: + root: + [ + 12, + 11, + null, + 10, + null, + 9, + null, + 8, + null, + 7, + null, + 6, + null, + 5, + null, + 4, + null, + 3, + null, + 2, + null, + 1, + ] + + - name: thirteen_balanced + in: + root: [8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13] + + - name: thirteen_irregular + in: + root: [8, 3, 12, 1, 5, 10, 15, null, 2, 4, 7, 9, 11, 14] + + - name: fourteen_left_heavy + in: + root: [10, 5, 13, 3, 8, 12, 14, 1, 4, 6, 9, 11] + + - name: fifteen_perfect + in: + root: [8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15] + + - name: fifteen_right_chain + in: + root: + [ + 1, + null, + 2, + null, + 3, + null, + 4, + null, + 5, + null, + 6, + null, + 7, + null, + 8, + null, + 9, + null, + 10, + null, + 11, + null, + 12, + null, + 13, + null, + 14, + null, + 15, + ] + + - name: sixteen_sparse + in: + root: [9, 4, 13, 2, 6, 11, 15, 1, 3, 5, 7, 10, 12, 14, 16] + + - name: seventeen_unbalanced + in: + root: [12, 6, 16, 3, 9, 14, 18, 1, 4, 7, 10, 13, 15, 17, 20] + + - name: boundary_values + in: + root: [50000, 25000, 75000, 1, 30000, 60000, 100000] + + - name: large_gap_values + in: + root: [50000, 100, 99999, 50, 1000, 75000, 100000, 1, 75] + + - name: twenty_one_balanced + in: + root: + [ + 16, + 8, + 24, + 4, + 12, + 20, + 28, + 2, + 6, + 10, + 14, + 18, + 22, + 26, + 30, + 1, + 3, + 5, + 7, + 9, + 11, + ] + + - name: twenty_three_left_chain + in: + root: + [ + 23, + 22, + null, + 21, + null, + 20, + null, + 19, + null, + 18, + null, + 17, + null, + 16, + null, + 15, + null, + 14, + null, + 13, + null, + 12, + null, + 11, + null, + 10, + null, + 9, + null, + 8, + null, + 7, + null, + 6, + null, + 5, + null, + 4, + null, + 3, + null, + 2, + null, + 1, + ] + + - name: twenty_five_irregular + in: + root: + [ + 50, + 25, + 75, + 10, + 40, + 60, + 90, + 5, + 15, + 35, + 45, + 55, + 65, + 80, + 100, + 1, + 7, + 12, + 20, + 30, + 38, + 42, + 48, + 52, + 58, + ] + + - name: thirty_one_perfect + in: + root: + [ + 16, + 8, + 24, + 4, + 12, + 20, + 28, + 2, + 6, + 10, + 14, + 18, + 22, + 26, + 30, + 1, + 3, + 5, + 7, + 9, + 11, + 13, + 15, + 17, + 19, + 21, + 23, + 25, + 27, + 29, + 31, + ] + + - name: thirty_two_right_chain + in: + root: + [ + 1, + null, + 2, + null, + 3, + null, + 4, + null, + 5, + null, + 6, + null, + 7, + null, + 8, + null, + 9, + null, + 10, + null, + 11, + null, + 12, + null, + 13, + null, + 14, + null, + 15, + null, + 16, + null, + 17, + null, + 18, + null, + 19, + null, + 20, + null, + 21, + null, + 22, + null, + 23, + null, + 24, + null, + 25, + null, + 26, + null, + 27, + null, + 28, + null, + 29, + null, + 30, + null, + 31, + null, + 32, + ] + + - name: forty_mixed_values + in: + root: [25, 10, 40, 5, 15, 30, 50, 1, 7, 12, 20, 27, 35, 45, 60] diff --git a/tests/1001-1500/1382. balance-a-binary-search-tree/sol.cpp b/tests/1001-1500/1382. balance-a-binary-search-tree/sol.cpp new file mode 100644 index 00000000..f062fd6f --- /dev/null +++ b/tests/1001-1500/1382. balance-a-binary-search-tree/sol.cpp @@ -0,0 +1,36 @@ +/** + * 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: + TreeNode* balanceBST(TreeNode* root) { + vector vals; + inorder(root, vals); + return build(vals, 0, vals.size() - 1); + } + +private: + void inorder(TreeNode* node, vector& vals) { + if (!node) return; + inorder(node->left, vals); + vals.push_back(node->val); + inorder(node->right, vals); + } + + TreeNode* build(vector& vals, int l, int r) { + if (l > r) return nullptr; + int mid = (l + r) / 2; + TreeNode* node = new TreeNode(vals[mid]); + node->left = build(vals, l, mid - 1); + node->right = build(vals, mid + 1, r); + return node; + } +}; diff --git a/tests/1001-1500/1382. balance-a-binary-search-tree/sol.cs b/tests/1001-1500/1382. balance-a-binary-search-tree/sol.cs new file mode 100644 index 00000000..9c6bae04 --- /dev/null +++ b/tests/1001-1500/1382. balance-a-binary-search-tree/sol.cs @@ -0,0 +1,36 @@ +/** + * 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 TreeNode BalanceBST(TreeNode root) { + List vals = new List(); + Inorder(root, vals); + return Build(vals, 0, vals.Count - 1); + } + + private void Inorder(TreeNode node, List vals) { + if (node == null) return; + Inorder(node.left, vals); + vals.Add(node.val); + Inorder(node.right, vals); + } + + private TreeNode Build(List vals, int l, int r) { + if (l > r) return null; + int mid = (l + r) / 2; + TreeNode node = new TreeNode(vals[mid]); + node.left = Build(vals, l, mid - 1); + node.right = Build(vals, mid + 1, r); + return node; + } +} diff --git a/tests/1001-1500/1382. balance-a-binary-search-tree/sol.dart b/tests/1001-1500/1382. balance-a-binary-search-tree/sol.dart new file mode 100644 index 00000000..d21d1dbe --- /dev/null +++ b/tests/1001-1500/1382. balance-a-binary-search-tree/sol.dart @@ -0,0 +1,32 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * int val; + * TreeNode? left; + * TreeNode? right; + * TreeNode([this.val = 0, this.left, this.right]); + * } + */ +class Solution { + TreeNode? balanceBST(TreeNode? root) { + List vals = []; + inorder(root, vals); + return build(vals, 0, vals.length - 1); + } + + void inorder(TreeNode? node, List vals) { + if (node == null) return; + inorder(node.left, vals); + vals.add(node.val); + inorder(node.right, vals); + } + + TreeNode? build(List vals, int l, int r) { + if (l > r) return null; + int mid = (l + r) ~/ 2; + TreeNode node = TreeNode(vals[mid]); + node.left = build(vals, l, mid - 1); + node.right = build(vals, mid + 1, r); + return node; + } +} diff --git a/tests/1001-1500/1382. balance-a-binary-search-tree/sol.go b/tests/1001-1500/1382. balance-a-binary-search-tree/sol.go new file mode 100644 index 00000000..0f1f3911 --- /dev/null +++ b/tests/1001-1500/1382. balance-a-binary-search-tree/sol.go @@ -0,0 +1,33 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func balanceBST(root *TreeNode) *TreeNode { + var vals []int + inorder(root, &vals) + return build(vals, 0, len(vals)-1) +} + +func inorder(node *TreeNode, vals *[]int) { + if node == nil { + return + } + inorder(node.Left, vals) + *vals = append(*vals, node.Val) + inorder(node.Right, vals) +} + +func build(vals []int, l, r int) *TreeNode { + if l > r { + return nil + } + mid := (l + r) / 2 + node := &TreeNode{Val: vals[mid]} + node.Left = build(vals, l, mid-1) + node.Right = build(vals, mid+1, r) + return node +} diff --git a/tests/1001-1500/1382. balance-a-binary-search-tree/sol.java b/tests/1001-1500/1382. balance-a-binary-search-tree/sol.java new file mode 100644 index 00000000..7f0cd8ac --- /dev/null +++ b/tests/1001-1500/1382. balance-a-binary-search-tree/sol.java @@ -0,0 +1,38 @@ +/** + * 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 TreeNode balanceBST(TreeNode root) { + List vals = new ArrayList<>(); + inorder(root, vals); + return build(vals, 0, vals.size() - 1); + } + + private void inorder(TreeNode node, List vals) { + if (node == null) return; + inorder(node.left, vals); + vals.add(node.val); + inorder(node.right, vals); + } + + private TreeNode build(List vals, int l, int r) { + if (l > r) return null; + int mid = (l + r) / 2; + TreeNode node = new TreeNode(vals.get(mid)); + node.left = build(vals, l, mid - 1); + node.right = build(vals, mid + 1, r); + return node; + } +} diff --git a/tests/1001-1500/1382. balance-a-binary-search-tree/sol.kt b/tests/1001-1500/1382. balance-a-binary-search-tree/sol.kt new file mode 100644 index 00000000..8cd87214 --- /dev/null +++ b/tests/1001-1500/1382. balance-a-binary-search-tree/sol.kt @@ -0,0 +1,33 @@ +/** + * 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 balanceBST(root: TreeNode?): TreeNode? { + val vals = mutableListOf() + inorder(root, vals) + return build(vals, 0, vals.size - 1) + } + + private fun inorder(node: TreeNode?, vals: MutableList) { + if (node == null) return + inorder(node.left, vals) + vals.add(node.`val`) + inorder(node.right, vals) + } + + private fun build(vals: List, l: Int, r: Int): TreeNode? { + if (l > r) return null + val mid = (l + r) / 2 + val node = TreeNode(vals[mid]) + node.left = build(vals, l, mid - 1) + node.right = build(vals, mid + 1, r) + return node + } +} diff --git a/tests/1001-1500/1382. balance-a-binary-search-tree/sol.py b/tests/1001-1500/1382. balance-a-binary-search-tree/sol.py new file mode 100644 index 00000000..b1b39dc8 --- /dev/null +++ b/tests/1001-1500/1382. balance-a-binary-search-tree/sol.py @@ -0,0 +1,21 @@ +class Solution: + def inorder(self, node, vals): + if not node: + return + self.inorder(node.left, vals) + vals.append(node.val) + self.inorder(node.right, vals) + + def build(self, vals, l, r): + if l > r: + return None + mid = (l + r) // 2 + node = TreeNode(vals[mid]) + node.left = self.build(vals, l, mid - 1) + node.right = self.build(vals, mid + 1, r) + return node + + def balanceBST(self, root): + vals = [] + self.inorder(root, vals) + return self.build(vals, 0, len(vals) - 1) diff --git a/tests/1001-1500/1382. balance-a-binary-search-tree/sol.py2 b/tests/1001-1500/1382. balance-a-binary-search-tree/sol.py2 new file mode 100644 index 00000000..ee6f11b0 --- /dev/null +++ b/tests/1001-1500/1382. balance-a-binary-search-tree/sol.py2 @@ -0,0 +1,31 @@ +# 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 inorder(self, node, vals): + if not node: + return + self.inorder(node.left, vals) + vals.append(node.val) + self.inorder(node.right, vals) + + def build(self, vals, l, r): + if l > r: + return None + mid = (l + r) // 2 + node = TreeNode(vals[mid]) + node.left = self.build(vals, l, mid - 1) + node.right = self.build(vals, mid + 1, r) + return node + + def balanceBST(self, root): + """ + :type root: Optional[TreeNode] + :rtype: Optional[TreeNode] + """ + vals = [] + self.inorder(root, vals) + return self.build(vals, 0, len(vals) - 1) diff --git a/tests/1001-1500/1382. balance-a-binary-search-tree/sol.rb b/tests/1001-1500/1382. balance-a-binary-search-tree/sol.rb new file mode 100644 index 00000000..fac12504 --- /dev/null +++ b/tests/1001-1500/1382. balance-a-binary-search-tree/sol.rb @@ -0,0 +1,32 @@ +# 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 {TreeNode} +def balance_bst(root) + vals = [] + inorder(root, vals) + build(vals, 0, vals.length - 1) +end + +def inorder(node, vals) + return if node.nil? + inorder(node.left, vals) + vals << node.val + inorder(node.right, vals) +end + +def build(vals, l, r) + return nil if l > r + mid = (l + r) / 2 + node = TreeNode.new(vals[mid]) + node.left = build(vals, l, mid - 1) + node.right = build(vals, mid + 1, r) + node +end diff --git a/tests/1001-1500/1382. balance-a-binary-search-tree/sol.rs b/tests/1001-1500/1382. balance-a-binary-search-tree/sol.rs new file mode 100644 index 00000000..eea5824d --- /dev/null +++ b/tests/1001-1500/1382. balance-a-binary-search-tree/sol.rs @@ -0,0 +1,44 @@ +// 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 balance_bst(root: Option>>) -> Option>> { + let mut vals = Vec::new(); + Self::inorder(&root, &mut vals); + Self::build(&vals, 0, vals.len() as i32 - 1) + } + + fn inorder(node: &Option>>, vals: &mut Vec) { + if let Some(n) = node { + Self::inorder(&n.borrow().left, vals); + vals.push(n.borrow().val); + Self::inorder(&n.borrow().right, vals); + } + } + + fn build(vals: &Vec, l: i32, r: i32) -> Option>> { + if l > r { + return None; + } + let mid = (l + r) / 2; + let mut node = TreeNode::new(vals[mid as usize]); + node.left = Self::build(vals, l, mid - 1); + node.right = Self::build(vals, mid + 1, r); + Some(Rc::new(RefCell::new(node))) + } +} diff --git a/tests/1001-1500/1382. balance-a-binary-search-tree/sol.swift b/tests/1001-1500/1382. balance-a-binary-search-tree/sol.swift new file mode 100644 index 00000000..19541ff2 --- /dev/null +++ b/tests/1001-1500/1382. balance-a-binary-search-tree/sol.swift @@ -0,0 +1,38 @@ +/** + * 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 balanceBST(_ root: TreeNode?) -> TreeNode? { + var vals: [Int] = [] + inorder(root, &vals) + return build(vals, 0, vals.count - 1) + } + + private func inorder(_ node: TreeNode?, _ vals: inout [Int]) { + guard let node = node else { return } + inorder(node.left, &vals) + vals.append(node.val) + inorder(node.right, &vals) + } + + private func build(_ vals: [Int], _ l: Int, _ r: Int) -> TreeNode? { + if l > r { return nil } + let mid = (l + r) / 2 + let node = TreeNode(vals[mid]) + node.left = build(vals, l, mid - 1) + node.right = build(vals, mid + 1, r) + return node + } +} diff --git a/tests/1001-1500/1382. balance-a-binary-search-tree/sol.ts b/tests/1001-1500/1382. balance-a-binary-search-tree/sol.ts new file mode 100644 index 00000000..ffb56c1c --- /dev/null +++ b/tests/1001-1500/1382. balance-a-binary-search-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 balanceBST(root: TreeNode | null): TreeNode | null { + const vals: number[] = []; + inorder(root, vals); + return build(vals, 0, vals.length - 1); +} + +function inorder(node: TreeNode | null, vals: number[]): void { + const stack: TreeNode[] = []; + let current = node; + while (current || stack.length > 0) { + while (current) { + stack.push(current); + current = current.left; + } + current = stack.pop()!; + vals.push(current.val); + current = current.right; + } +} + +function build(vals: number[], l: number, r: number): TreeNode | null { + if (l > r) return null; + const mid = Math.floor((l + r) / 2); + const node = new TreeNode(vals[mid]); + node.left = build(vals, l, mid - 1); + node.right = build(vals, mid + 1, r); + return node; +} diff --git a/tests/1001-1500/1383. maximum-performance-of-a-team/manifest.yaml b/tests/1001-1500/1383. maximum-performance-of-a-team/manifest.yaml new file mode 100644 index 00000000..11933a24 --- /dev/null +++ b/tests/1001-1500/1383. maximum-performance-of-a-team/manifest.yaml @@ -0,0 +1,438 @@ +entry: + id: 1383 + title: "maximum-performance-of-a-team" + params: + n: + type: int + speed: + type: array + items: + type: int + efficiency: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().maxPerformance({n}, {speed}, {efficiency}, {k})" + rust: "Solution::max_performance({n}, {speed}, {efficiency}, {k})" + python3: "Solution().maxPerformance({n}, {speed}, {efficiency}, {k})" + python2: "Solution().maxPerformance({n}, {speed}, {efficiency}, {k})" + ruby: "max_performance({n}, {speed}, {efficiency}, {k})" + java: "new Solution().maxPerformance({n}, {speed}, {efficiency}, {k})" + csharp: "new Solution().MaxPerformance({n}, {speed}, {efficiency}, {k})" + kotlin: "Solution().maxPerformance({n}, {speed}, {efficiency}, {k})" + go: "maxPerformance({n}, {speed}, {efficiency}, {k})" + dart: "Solution().maxPerformance({n}, {speed}, {efficiency}, {k})" + swift: "Solution().maxPerformance({n}, {speed}, {efficiency}, {k})" + typescript: "maxPerformance({n}, {speed}, {efficiency}, {k})" +judge: + type: "exact" +limits: + time_ms: 500 + memory_mb: 300 +oracle: + python3: + call: "Checker().maxPerformance(n, speed, efficiency, k, {result})" + checker: | + class Checker: + def maxPerformance(self, n, speed, efficiency, k, result): + if type(result) is not int: + return False + if type(n) is not int or n < 2 or n > 100000: + return False + if type(k) is not int or k < 1 or k > n: + return False + if len(speed) != n or len(efficiency) != n: + return False + if any(type(x) is not int or x < 1 or x > 100000 for x in speed): + return False + if any(type(x) is not int or x < 1 or x > 100000000 for x in efficiency): + return False + mod = 1000000007 + if n <= 12: + from itertools import combinations + best = 0 + for size in range(1, k + 1): + for chosen in combinations(range(n), size): + total_speed = sum(speed[i] for i in chosen) + team_efficiency = min(efficiency[i] for i in chosen) + best = max(best, total_speed * team_efficiency) + expected = best % mod + else: + import heapq + total_speed = 0 + weakest = [] + best = 0 + engineers = sorted(zip(efficiency, speed), key=lambda pair: pair[0], reverse=True) + for team_efficiency, engineer_speed in engineers: + heapq.heappush(weakest, engineer_speed) + total_speed += engineer_speed + if len(weakest) > k: + total_speed -= heapq.heappop(weakest) + candidate = total_speed * team_efficiency + if candidate > best: + best = candidate + expected = best % mod + return result == expected +seed: 1383 +tests: + - name: "example_1" + in: + n: 6 + speed: [2, 10, 3, 1, 5, 8] + efficiency: [5, 4, 3, 9, 7, 2] + k: 2 + out: 60 + - name: "example_2" + in: + n: 6 + speed: [2, 10, 3, 1, 5, 8] + efficiency: [5, 4, 3, 9, 7, 2] + k: 3 + out: 68 + - name: "example_3" + in: + n: 6 + speed: [2, 10, 3, 1, 5, 8] + efficiency: [5, 4, 3, 9, 7, 2] + k: 4 + out: 72 + - name: "single_best" + in: + n: 2 + speed: [1, 100] + efficiency: [100000000, 1] + k: 1 + out: 100000000 + - name: "single_low_efficiency" + in: + n: 3 + speed: [10, 20, 30] + efficiency: [1, 2, 3] + k: 1 + out: 90 + - name: "all_engineers" + in: + n: 3 + speed: [5, 6, 7] + efficiency: [4, 4, 4] + k: 3 + out: 72 + - name: "k_two_pair" + in: + n: 2 + speed: [5, 6] + efficiency: [7, 8] + k: 2 + out: 77 + - name: "equal_speed" + in: + n: 4 + speed: [5, 5, 5, 5] + efficiency: [1, 2, 3, 4] + k: 2 + out: 30 + - name: "equal_efficiency" + in: + n: 4 + speed: [1, 2, 3, 4] + efficiency: [9, 9, 9, 9] + k: 3 + out: 81 + - name: "descending_efficiency" + in: + n: 5 + speed: [10, 9, 8, 7, 6] + efficiency: [5, 4, 3, 2, 1] + k: 2 + out: 76 + - name: "ascending_efficiency" + in: + n: 5 + speed: [10, 9, 8, 7, 6] + efficiency: [1, 2, 3, 4, 5] + k: 2 + out: 52 + - name: "large_values_pair" + in: + n: 2 + speed: [100000, 100000] + efficiency: [100000000, 99999999] + k: 2 + out: 999660007 + - name: "modulo_single" + in: + n: 2 + speed: [100000, 1] + efficiency: [100000000, 1] + k: 1 + out: 999930007 + - name: "zero_tradeoff" + in: + n: 4 + speed: [8, 1, 1, 1] + efficiency: [1, 100, 99, 98] + k: 3 + out: 294 + - name: "high_speed_low_efficiency" + in: + n: 5 + speed: [100, 1, 1, 1, 1] + efficiency: [1, 100, 100, 100, 100] + k: 2 + out: 200 + - name: "high_efficiency_low_speed" + in: + n: 5 + speed: [1, 100, 100, 100, 100] + efficiency: [100000000, 1, 1, 1, 1] + k: 2 + out: 100000000 + - name: "duplicate_pairs" + in: + n: 4 + speed: [2, 2, 3, 3] + efficiency: [4, 4, 5, 5] + k: 2 + out: 30 + - name: "k_one_mixed" + in: + n: 5 + speed: [3, 20, 7, 8, 9] + efficiency: [10, 2, 8, 7, 6] + k: 1 + out: 56 + - name: "k_n_mixed" + in: + n: 5 + speed: [3, 20, 7, 8, 9] + efficiency: [10, 2, 8, 7, 6] + k: 5 + out: 162 + - name: "tiny_1" + in: + n: 2 + speed: [7, 3] + efficiency: [2, 9] + k: 2 + out: 27 + - name: "tiny_2" + in: + n: 2 + speed: [99999, 100000] + efficiency: [99999, 100000] + k: 1 + out: 999999937 + - name: "tiny_3" + in: + n: 3 + speed: [4, 5, 6] + efficiency: [6, 5, 4] + k: 2 + out: 45 + - name: "tiny_4" + in: + n: 3 + speed: [4, 5, 6] + efficiency: [4, 5, 6] + k: 2 + out: 55 + - name: "tiny_5" + in: + n: 4 + speed: [1, 10, 2, 9] + efficiency: [10, 1, 9, 2] + k: 2 + out: 27 + - name: "tiny_6" + in: + n: 4 + speed: [10, 1, 2, 3] + efficiency: [2, 10, 9, 8] + k: 3 + out: 48 + - name: "tiny_7" + in: + n: 5 + speed: [1, 2, 3, 4, 5] + efficiency: [5, 4, 3, 2, 1] + k: 3 + out: 18 + - name: "tiny_8" + in: + n: 5 + speed: [5, 4, 3, 2, 1] + efficiency: [1, 2, 3, 4, 5] + k: 3 + out: 18 + - name: "tiny_9" + in: + n: 6 + speed: [6, 5, 4, 3, 2, 1] + efficiency: [2, 2, 2, 2, 2, 2] + k: 4 + out: 36 + - name: "tiny_10" + in: + n: 6 + speed: [1, 1, 1, 1, 1, 1] + efficiency: [1, 2, 3, 4, 5, 6] + k: 6 + out: 12 + - name: "minimum_efficiency_everywhere" + in: + n: 4 + speed: [100000, 99999, 2, 1] + efficiency: [1, 1, 1, 1] + k: 4 + out: 200002 + - name: "minimum_speed_everywhere" + in: + n: 4 + speed: [1, 1, 1, 1] + efficiency: [100000000, 99999999, 99999998, 99999997] + k: 4 + out: 399999988 + - name: "efficiency_tie_selection" + in: + n: 5 + speed: [100, 90, 80, 70, 60] + efficiency: [7, 7, 7, 6, 6] + k: 3 + out: 1890 + - name: "best_team_is_not_k" + in: + n: 6 + speed: [100, 1, 1, 1, 1, 1] + efficiency: [2, 100, 99, 98, 97, 96] + k: 6 + out: 480 + - name: "modulo_multi_engineer" + in: + n: 3 + speed: [100000, 100000, 100000] + efficiency: [100000000, 99999999, 99999998] + k: 3 + out: 999190007 + - name: "generated_small" + seed: 101 + in: + n: 8 + speed: + gen: "array" + len: 8 + of: + gen: "int" + min: 1 + max: 100 + efficiency: + gen: "array" + len: 8 + of: + gen: "int" + min: 1 + max: 1000 + k: + gen: "int" + min: 1 + max: 8 + - name: "generated_medium" + seed: 202 + in: + n: 20 + speed: + gen: "array" + len: 20 + of: + gen: "int" + min: 1 + max: 100000 + efficiency: + gen: "array" + len: 20 + of: + gen: "int" + min: 1 + max: 100000000 + k: + gen: "int" + min: 1 + max: 20 + - name: "generated_large_a" + seed: 303 + in: + n: 50000 + speed: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 100000 + efficiency: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 100000000 + k: 25000 + - name: "generated_large_b" + seed: 404 + in: + n: 100000 + speed: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 100000 + efficiency: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 100000000 + k: 100000 + - name: "generated_boundary_k_one" + seed: 505 + in: + n: 12 + speed: + gen: "array" + len: 12 + of: + gen: "int" + min: 1 + max: 100000 + efficiency: + gen: "array" + len: 12 + of: + gen: "int" + min: 1 + max: 100000000 + k: 1 + - name: "generated_boundary_all" + seed: 606 + in: + n: 100 + speed: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 100000 + efficiency: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 100000000 + k: 100 diff --git a/tests/1001-1500/1383. maximum-performance-of-a-team/sol.cpp b/tests/1001-1500/1383. maximum-performance-of-a-team/sol.cpp new file mode 100644 index 00000000..085c25a6 --- /dev/null +++ b/tests/1001-1500/1383. maximum-performance-of-a-team/sol.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int maxPerformance(int n, vector& speed, vector& efficiency, int k) { + const int MOD = 1000000007; + vector> engineers; + for (int i = 0; i < n; i++) { + engineers.push_back({efficiency[i], speed[i]}); + } + sort(engineers.begin(), engineers.end(), [](auto& a, auto& b) { + return a.first > b.first; + }); + + priority_queue, greater> pq; + long long curSum = 0; + long long ans = 0; + + for (auto& [e, s] : engineers) { + while (pq.size() > k - 1) { + curSum -= pq.top(); + pq.pop(); + } + pq.push(s); + curSum += s; + ans = max(ans, curSum * e); + } + + return ans % MOD; + } +}; diff --git a/tests/1001-1500/1383. maximum-performance-of-a-team/sol.cs b/tests/1001-1500/1383. maximum-performance-of-a-team/sol.cs new file mode 100644 index 00000000..c883312a --- /dev/null +++ b/tests/1001-1500/1383. maximum-performance-of-a-team/sol.cs @@ -0,0 +1,34 @@ +public class Solution { + public int MaxPerformance(int n, int[] speed, int[] efficiency, int k) { + const int MOD = 1000000007; + int[][] engineers = new int[n][]; + for (int i = 0; i < n; i++) { + engineers[i] = new int[] { efficiency[i], speed[i] }; + } + Array.Sort(engineers, (a, b) => b[0].CompareTo(a[0])); + + var pq = new SortedDictionary(); + int count = 0; + long curSum = 0; + long ans = 0; + + foreach (var eng in engineers) { + while (count > k - 1) { + var iterator = pq.GetEnumerator(); + iterator.MoveNext(); + int smallest = iterator.Current.Key; + curSum -= smallest; + if (pq[smallest] == 1) pq.Remove(smallest); + else pq[smallest]--; + count--; + } + if (!pq.ContainsKey(eng[1])) pq[eng[1]] = 0; + pq[eng[1]]++; + count++; + curSum += eng[1]; + ans = Math.Max(ans, curSum * eng[0]); + } + + return (int)(ans % MOD); + } +} diff --git a/tests/1001-1500/1383. maximum-performance-of-a-team/sol.dart b/tests/1001-1500/1383. maximum-performance-of-a-team/sol.dart new file mode 100644 index 00000000..d498b583 --- /dev/null +++ b/tests/1001-1500/1383. maximum-performance-of-a-team/sol.dart @@ -0,0 +1,72 @@ +class Solution { + int maxPerformance(int n, List speed, List efficiency, int k) { + const int MOD = 1000000007; + List> engineers = []; + for (int i = 0; i < n; i++) { + engineers.add([efficiency[i], speed[i]]); + } + engineers.sort((a, b) => b[0].compareTo(a[0])); + + PriorityQueue pq = PriorityQueue((a, b) => a.compareTo(b)); + int curSum = 0; + int ans = 0; + + for (var eng in engineers) { + while (pq.length > k - 1) { + curSum -= pq.removeFirst(); + } + pq.add(eng[1]); + curSum += eng[1]; + int val = curSum * eng[0]; + if (val > ans) ans = val; + } + + return ans % MOD; + } +} + +class PriorityQueue { + final Comparator comparator; + final List _list = []; + + PriorityQueue(this.comparator); + + void add(T value) { + _list.add(value); + var index = _list.length - 1; + while (index > 0) { + final parent = (index - 1) ~/ 2; + if (comparator(_list[parent], _list[index]) <= 0) break; + final temp = _list[parent]; + _list[parent] = _list[index]; + _list[index] = temp; + index = parent; + } + } + + T removeFirst() { + final result = _list[0]; + final last = _list.removeLast(); + if (_list.isNotEmpty) { + _list[0] = last; + var index = 0; + while (true) { + final left = index * 2 + 1; + final right = left + 1; + var smallest = index; + if (left < _list.length && comparator(_list[left], _list[smallest]) < 0) smallest = left; + if (right < _list.length && comparator(_list[right], _list[smallest]) < 0) smallest = right; + if (smallest == index) break; + final temp = _list[index]; + _list[index] = _list[smallest]; + _list[smallest] = temp; + index = smallest; + } + } + return result; + } + + int get length => _list.length; +} + +typedef Comparator = int Function(T a, T b); diff --git a/tests/1001-1500/1383. maximum-performance-of-a-team/sol.go b/tests/1001-1500/1383. maximum-performance-of-a-team/sol.go new file mode 100644 index 00000000..a41cf433 --- /dev/null +++ b/tests/1001-1500/1383. maximum-performance-of-a-team/sol.go @@ -0,0 +1,50 @@ +func maxPerformance(n int, speed []int, efficiency []int, k int) int { + const MOD = 1000000007 + type Engineer struct { + efficiency int + speed int + } + engineers := make([]Engineer, n) + for i := 0; i < n; i++ { + engineers[i] = Engineer{efficiency[i], speed[i]} + } + sort.Slice(engineers, func(i, j int) bool { + return engineers[i].efficiency > engineers[j].efficiency + }) + + h := &IntHeap{} + heap.Init(h) + var curSum int64 = 0 + var ans int64 = 0 + + for _, eng := range engineers { + for h.Len() > k-1 { + curSum -= int64(heap.Pop(h).(int)) + } + heap.Push(h, eng.speed) + curSum += int64(eng.speed) + if curSum*int64(eng.efficiency) > ans { + ans = curSum * int64(eng.efficiency) + } + } + + return int(ans % MOD) +} + +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 +} diff --git a/tests/1001-1500/1383. maximum-performance-of-a-team/sol.java b/tests/1001-1500/1383. maximum-performance-of-a-team/sol.java new file mode 100644 index 00000000..f23b2ca0 --- /dev/null +++ b/tests/1001-1500/1383. maximum-performance-of-a-team/sol.java @@ -0,0 +1,26 @@ +class Solution { + public int maxPerformance(int n, int[] speed, int[] efficiency, int k) { + int MOD = 1000000007; + int[][] engineers = new int[n][2]; + for (int i = 0; i < n; i++) { + engineers[i][0] = efficiency[i]; + engineers[i][1] = speed[i]; + } + Arrays.sort(engineers, (a, b) -> Integer.compare(b[0], a[0])); + + PriorityQueue pq = new PriorityQueue<>(); + long curSum = 0; + long ans = 0; + + for (int[] eng : engineers) { + while (pq.size() > k - 1) { + curSum -= pq.poll(); + } + pq.offer(eng[1]); + curSum += eng[1]; + ans = Math.max(ans, curSum * eng[0]); + } + + return (int)(ans % MOD); + } +} diff --git a/tests/1001-1500/1383. maximum-performance-of-a-team/sol.kt b/tests/1001-1500/1383. maximum-performance-of-a-team/sol.kt new file mode 100644 index 00000000..0395b088 --- /dev/null +++ b/tests/1001-1500/1383. maximum-performance-of-a-team/sol.kt @@ -0,0 +1,22 @@ +class Solution { + fun maxPerformance(n: Int, speed: IntArray, efficiency: IntArray, k: Int): Int { + val MOD = 1000000007 + val engineers = Array(n) { i -> Pair(efficiency[i], speed[i]) } + engineers.sortByDescending { it.first } + + val pq = java.util.PriorityQueue() + var curSum = 0L + var ans = 0L + + for ((e, s) in engineers) { + while (pq.size > k - 1) { + curSum -= pq.poll() + } + pq.offer(s) + curSum += s + ans = maxOf(ans, curSum * e) + } + + return (ans % MOD).toInt() + } +} diff --git a/tests/1001-1500/1383. maximum-performance-of-a-team/sol.py b/tests/1001-1500/1383. maximum-performance-of-a-team/sol.py new file mode 100644 index 00000000..86ab9cf9 --- /dev/null +++ b/tests/1001-1500/1383. maximum-performance-of-a-team/sol.py @@ -0,0 +1,20 @@ +from typing import List +from heapq import heappop, heappush + + +class Solution: + def maxPerformance( + self, n: int, speed: List[int], efficiency: List[int], k: int + ) -> int: + + cur_sum, h = 0, [] + ans = -float("inf") + + for i, j in sorted(zip(efficiency, speed), reverse=True): + while len(h) > k - 1: + cur_sum -= heappop(h) + heappush(h, j) + cur_sum += j + ans = max(ans, cur_sum * i) + + return ans % (10**9 + 7) diff --git a/tests/1001-1500/1383. maximum-performance-of-a-team/sol.py2 b/tests/1001-1500/1383. maximum-performance-of-a-team/sol.py2 new file mode 100644 index 00000000..80f88345 --- /dev/null +++ b/tests/1001-1500/1383. maximum-performance-of-a-team/sol.py2 @@ -0,0 +1,22 @@ +class Solution(object): + def maxPerformance(self, n, speed, efficiency, k): + """ + :type n: int + :type speed: List[int] + :type efficiency: List[int] + :type k: int + :rtype: int + """ + import heapq + cur_sum = 0 + h = [] + ans = -float('inf') + + for e, s in sorted(zip(efficiency, speed), reverse=True): + while len(h) > k - 1: + cur_sum -= heapq.heappop(h) + heapq.heappush(h, s) + cur_sum += s + ans = max(ans, cur_sum * e) + + return ans % (10 ** 9 + 7) diff --git a/tests/1001-1500/1383. maximum-performance-of-a-team/sol.rb b/tests/1001-1500/1383. maximum-performance-of-a-team/sol.rb new file mode 100644 index 00000000..491e6b2c --- /dev/null +++ b/tests/1001-1500/1383. maximum-performance-of-a-team/sol.rb @@ -0,0 +1,46 @@ +def heap_push(heap, value) + heap << value + index = heap.length - 1 + while index > 0 + parent = (index - 1) / 2 + break if heap[parent] <= heap[index] + heap[parent], heap[index] = heap[index], heap[parent] + index = parent + end +end + +def heap_pop(heap) + result = heap[0] + last = heap.pop + if !heap.empty? + heap[0] = last + index = 0 + loop do + left = index * 2 + 1 + right = left + 1 + smallest = index + smallest = left if left < heap.length && heap[left] < heap[smallest] + smallest = right if right < heap.length && heap[right] < heap[smallest] + break if smallest == index + heap[index], heap[smallest] = heap[smallest], heap[index] + index = smallest + end + end + result +end + +def max_performance(n, speed, efficiency, k) + pairs = efficiency.zip(speed).sort_by { |pair| -pair[0] } + heap = [] + sum = 0 + best = 0 + pairs.each do |efficiency_value, speed_value| + if heap.length == k + sum -= heap_pop(heap) + end + heap_push(heap, speed_value) + sum += speed_value + best = [best, sum * efficiency_value].max + end + best % 1_000_000_007 +end diff --git a/tests/1001-1500/1383. maximum-performance-of-a-team/sol.rs b/tests/1001-1500/1383. maximum-performance-of-a-team/sol.rs new file mode 100644 index 00000000..996e0bde --- /dev/null +++ b/tests/1001-1500/1383. maximum-performance-of-a-team/sol.rs @@ -0,0 +1,24 @@ +impl Solution { + pub fn max_performance(n: i32, speed: Vec, efficiency: Vec, k: i32) -> i32 { + const MOD: i64 = 1_000_000_007; + let n = n as usize; + let k = k as usize; + let mut engineers: Vec<(i32, i32)> = efficiency.into_iter().zip(speed.into_iter()).collect(); + engineers.sort_unstable_by(|a, b| b.0.cmp(&a.0)); + + let mut pq: std::collections::BinaryHeap = std::collections::BinaryHeap::new(); + let mut cur_sum: i64 = 0; + let mut ans: i64 = 0; + + for (e, s) in engineers { + while pq.len() > k - 1 { + cur_sum -= -pq.pop().unwrap() as i64; + } + pq.push(-s); + cur_sum += s as i64; + ans = ans.max(cur_sum * e as i64); + } + + (ans % MOD) as i32 + } +} diff --git a/tests/1001-1500/1383. maximum-performance-of-a-team/sol.swift b/tests/1001-1500/1383. maximum-performance-of-a-team/sol.swift new file mode 100644 index 00000000..03236c91 --- /dev/null +++ b/tests/1001-1500/1383. maximum-performance-of-a-team/sol.swift @@ -0,0 +1,71 @@ +class Solution { + func maxPerformance(_ n: Int, _ speed: [Int], _ efficiency: [Int], _ k: Int) -> Int { + let MOD = 1000000007 + var engineers = zip(efficiency, speed).map { ($0, $1) } + engineers.sort { $0.0 > $1.0 } + + var pq = MinHeap() + var curSum = 0 + var ans = 0 + + for (e, s) in engineers { + while pq.count > k - 1 { + curSum -= pq.remove() + } + pq.insert(s) + curSum += s + ans = max(ans, curSum * e) + } + + return ans % MOD + } +} + +struct MinHeap { + private var heap: [T] = [] + + var count: Int { heap.count } + + mutating func insert(_ value: T) { + heap.append(value) + siftUp(heap.count - 1) + } + + mutating func remove() -> T { + let result = heap[0] + heap[0] = heap[heap.count - 1] + heap.removeLast() + if !heap.isEmpty { + siftDown(0) + } + return result + } + + private mutating func siftUp(_ index: Int) { + var child = index + var parent = (child - 1) / 2 + while child > 0 && heap[child] < heap[parent] { + heap.swapAt(child, parent) + 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 smallest = parent + if left < heap.count && heap[left] < heap[smallest] { + smallest = left + } + if right < heap.count && heap[right] < heap[smallest] { + smallest = right + } + if smallest == parent { break } + heap.swapAt(parent, smallest) + parent = smallest + } + } +} diff --git a/tests/1001-1500/1383. maximum-performance-of-a-team/sol.ts b/tests/1001-1500/1383. maximum-performance-of-a-team/sol.ts new file mode 100644 index 00000000..efa9f232 --- /dev/null +++ b/tests/1001-1500/1383. maximum-performance-of-a-team/sol.ts @@ -0,0 +1,82 @@ +function maxPerformance( + n: number, + speed: number[], + efficiency: number[], + k: number, +): number { + const MOD = 1000000007n; + const engineers: [number, number][] = []; + for (let i = 0; i < n; i++) { + engineers.push([efficiency[i], speed[i]]); + } + engineers.sort((a, b) => b[0] - a[0]); + + const pq = new MinPriorityQueue(); + let curSum = 0n; + let ans = 0n; + + for (const [e, s] of engineers) { + while (pq.size() > k - 1) { + curSum -= BigInt(pq.dequeue().element); + } + pq.enqueue(s); + curSum += BigInt(s); + const performance = curSum * BigInt(e); + if (performance > ans) ans = performance; + } + + return Number(ans % MOD); +} + +class MinPriorityQueue { + private heap: T[] = []; + + enqueue(value: T): void { + this.heap.push(value); + let index = this.heap.length - 1; + while (index > 0) { + const parent = Math.floor((index - 1) / 2); + if ((this.heap[parent] as any) <= (this.heap[index] as any)) break; + [this.heap[parent], this.heap[index]] = [ + this.heap[index], + this.heap[parent], + ]; + index = parent; + } + } + + dequeue(): { element: T } { + const element = this.heap[0]; + const last = this.heap.pop()!; + if (this.heap.length > 0) { + this.heap[0] = last; + let index = 0; + while (true) { + const left = index * 2 + 1; + const right = left + 1; + let smallest = index; + if ( + left < this.heap.length && + (this.heap[left] as any) < (this.heap[smallest] as any) + ) + smallest = left; + if ( + right < this.heap.length && + (this.heap[right] as any) < (this.heap[smallest] as any) + ) + smallest = right; + if (smallest === index) break; + [this.heap[index], this.heap[smallest]] = [ + this.heap[smallest], + this.heap[index], + ]; + index = smallest; + } + } + return { element }; + } + + size(): number { + return this.heap.length; + } +} diff --git a/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/manifest.yaml b/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/manifest.yaml new file mode 100644 index 00000000..3c1b8085 --- /dev/null +++ b/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/manifest.yaml @@ -0,0 +1,354 @@ +entry: + id: 1385 + title: "find-the-distance-value-between-two-arrays" + params: + arr1: + type: array + items: + type: int + arr2: + type: array + items: + type: int + d: + type: int + call: + cpp: "Solution().findTheDistanceValue({arr1}, {arr2}, {d})" + rust: "Solution::find_the_distance_value({arr1}, {arr2}, {d})" + python3: "Solution().findTheDistanceValue({arr1}, {arr2}, {d})" + python2: "Solution().findTheDistanceValue({arr1}, {arr2}, {d})" + ruby: "find_the_distance_value({arr1}, {arr2}, {d})" + java: "new Solution().findTheDistanceValue({arr1}, {arr2}, {d})" + csharp: "new Solution().FindTheDistanceValue({arr1}, {arr2}, {d})" + kotlin: "Solution().findTheDistanceValue({arr1}, {arr2}, {d})" + go: "findTheDistanceValue({arr1}, {arr2}, {d})" + dart: "Solution().findTheDistanceValue({arr1}, {arr2}, {d})" + swift: "Solution().findTheDistanceValue({arr1}, {arr2}, {d})" + typescript: "findTheDistanceValue({arr1}, {arr2}, {d})" +judge: + type: "exact" +limits: + time_ms: 500 + memory_mb: 300 +oracle: + python3: + call: "Checker().findTheDistanceValue(arr1, arr2, d, {result})" + checker: | + class Checker: + def findTheDistanceValue(self, arr1, arr2, d, result): + if type(result) is not int: + return False + expected = 0 + for x in arr1: + if all(abs(x - y) > d for y in arr2): + expected += 1 + return result == expected +seed: 1385 +tests: + - name: "example_1" + in: + arr1: [4, 5, 8] + arr2: [10, 9, 1, 8] + d: 2 + - name: "example_2" + in: + arr1: [1, 4, 2, 3] + arr2: [-4, -3, 6, 10, 20, 30] + d: 3 + - name: "example_3" + in: + arr1: [2, 1, 100, 3] + arr2: [-5, -2, 10, -3, 7] + d: 6 + - name: "single_far_positive" + in: + arr1: [1000] + arr2: [-1000] + d: 100 + - name: "single_far_negative" + in: + arr1: [-1000] + arr2: [1000] + d: 0 + - name: "single_equal_zero_d" + in: + arr1: [17] + arr2: [17] + d: 0 + - name: "single_boundary_match" + in: + arr1: [0] + arr2: [100] + d: 100 + - name: "single_just_outside" + in: + arr1: [0] + arr2: [101] + d: 100 + - name: "all_equal_duplicates" + in: + arr1: [5, 5, 5, 5] + arr2: [5, 5] + d: 0 + - name: "duplicate_unmatched_values" + in: + arr1: [-10, -10, 10, 10] + arr2: [0, 0] + d: 0 + - name: "zero_d_exact_filter" + in: + arr1: [-2, -1, 0, 1, 2] + arr2: [-1, 1] + d: 0 + - name: "negative_boundary" + in: + arr1: [-100, -50, 0] + arr2: [-49, 50] + d: 1 + - name: "positive_boundary" + in: + arr1: [49, 50, 51] + arr2: [50] + d: 1 + - name: "maximum_d_all_match" + in: + arr1: [-100, 0, 100] + arr2: [-1, 1] + d: 100 + - name: "maximum_d_extremes" + in: + arr1: [-1000, 1000] + arr2: [0] + d: 100 + - name: "arr2_unsorted" + in: + arr1: [8, 4, 12, 0] + arr2: [10, -2, 6, 20] + d: 2 + - name: "arr1_order_irrelevant" + in: + arr1: [30, 1, 20, 2, 10] + arr2: [0, 15, 25] + d: 4 + - name: "overlapping_windows" + in: + arr1: [-5, 0, 5, 10] + arr2: [-2, 3, 8] + d: 2 + - name: "no_matches_small_d" + in: + arr1: [-9, 0, 9] + arr2: [-5, 5] + d: 0 + - name: "all_matches_small_range" + in: + arr1: [-3, -2, -1, 0, 1, 2, 3] + arr2: [0] + d: 3 + - name: "mixed_duplicates" + in: + arr1: [1, 1, 2, 8, 8, 20] + arr2: [0, 3, 10, 10] + d: 1 + - name: "negative_cluster" + in: + arr1: [-100, -99, -98, -50] + arr2: [-101, -49] + d: 1 + - name: "extreme_values_d_zero" + in: + arr1: [-1000, -999, 999, 1000] + arr2: [-1000, 1000] + d: 0 + - name: "extreme_values_d_one" + in: + arr1: [-1000, -998, 998, 1000] + arr2: [-999, 999] + d: 1 + - name: "sparse_arr2" + in: + arr1: [-900, -100, 0, 100, 900] + arr2: [-901, 101] + d: 1 + - name: "dense_arr2" + in: + arr1: [-5, 0, 5, 10] + arr2: + [ + -10, + -9, + -8, + -7, + -6, + -5, + -4, + -3, + -2, + -1, + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + ] + d: 0 + - name: "asymmetric_lengths" + in: + arr1: [1, 2, 3, 100, 101, 102] + arr2: [2] + d: 1 + - name: "large_value_window" + in: + arr1: [-1000, -900, 0, 900, 1000] + arr2: [-950, 950] + d: 50 + - name: "near_zero_negative" + in: + arr1: [-3, -2, -1, 0] + arr2: [2] + d: 1 + - name: "near_zero_positive" + in: + arr1: [0, 1, 2, 3] + arr2: [-2] + d: 1 + - name: "repeated_arr1_match_count" + in: + arr1: [7, 7, 7, 9, 9] + arr2: [8] + d: 1 + - name: "repeated_arr1_unmatched_count" + in: + arr1: [-20, -20, 20, 20] + arr2: [0] + d: 100 + - name: "max_coordinate_gap" + in: + arr1: [-1000, 1000] + arr2: [-999, 999] + d: 0 + - name: "middle_only_match" + in: + arr1: [-100, 0, 100] + arr2: [0] + d: 0 + - name: "generator_small" + seed: 101 + in: + arr1: + gen: "array" + len: 1 + of: + gen: "int" + min: -1000 + max: 1000 + arr2: + gen: "array" + len: 1 + of: + gen: "int" + min: -1000 + max: 1000 + d: + gen: "int" + min: 0 + max: 100 + - name: "generator_duplicates" + seed: 202 + in: + arr1: + gen: "array" + len: 25 + of: + gen: "int" + min: -5 + max: 5 + arr2: + gen: "array" + len: 7 + of: + gen: "int" + min: -5 + max: 5 + d: 0 + - name: "generator_full_range" + seed: 303 + in: + arr1: + gen: "array" + len: 120 + of: + gen: "int" + min: -1000 + max: 1000 + arr2: + gen: "array" + len: 80 + of: + gen: "int" + min: -1000 + max: 1000 + d: + gen: "int" + min: 0 + max: 100 + - name: "generator_dense" + seed: 404 + in: + arr1: + gen: "array" + len: 300 + of: + gen: "int" + min: -20 + max: 20 + arr2: + gen: "array" + len: 300 + of: + gen: "int" + min: -20 + max: 20 + d: 3 + - name: "stress_maximum" + seed: 505 + in: + arr1: + gen: "array" + len: 500 + of: + gen: "int" + min: -1000 + max: 1000 + arr2: + gen: "array" + len: 500 + of: + gen: "int" + min: -1000 + max: 1000 + d: 100 + - name: "stress_maximum_zero_d" + seed: 606 + in: + arr1: + gen: "array" + len: 500 + of: + gen: "int" + min: -1000 + max: 1000 + arr2: + gen: "array" + len: 500 + of: + gen: "int" + min: -1000 + max: 1000 + d: 0 diff --git a/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.cpp b/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.cpp new file mode 100644 index 00000000..1ac52fab --- /dev/null +++ b/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int findTheDistanceValue(vector& arr1, vector& arr2, int d) { + sort(arr2.begin(), arr2.end()); + int count = 0; + for (int num : arr1) { + auto left = lower_bound(arr2.begin(), arr2.end(), num - d); + auto right = upper_bound(arr2.begin(), arr2.end(), num + d); + if (left == right) { + count++; + } + } + return count; + } +}; diff --git a/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.cs b/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.cs new file mode 100644 index 00000000..6c419a1d --- /dev/null +++ b/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.cs @@ -0,0 +1,40 @@ +public class Solution { + public int FindTheDistanceValue(int[] arr1, int[] arr2, int d) { + Array.Sort(arr2); + int count = 0; + foreach (int num in arr1) { + int leftIndex = LowerBound(arr2, num - d); + int rightIndex = UpperBound(arr2, num + d); + if (leftIndex == rightIndex) { + count++; + } + } + return count; + } + + private int LowerBound(int[] arr, int target) { + int left = 0, right = arr.Length; + while (left < right) { + int mid = left + (right - left) / 2; + if (arr[mid] < target) { + left = mid + 1; + } else { + right = mid; + } + } + return left; + } + + private int UpperBound(int[] arr, int target) { + int left = 0, right = arr.Length; + while (left < right) { + int mid = left + (right - left) / 2; + if (arr[mid] <= target) { + left = mid + 1; + } else { + right = mid; + } + } + return left; + } +} diff --git a/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.dart b/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.dart new file mode 100644 index 00000000..2da83f17 --- /dev/null +++ b/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.dart @@ -0,0 +1,40 @@ +class Solution { + int findTheDistanceValue(List arr1, List arr2, int d) { + arr2.sort(); + int count = 0; + for (int num in arr1) { + int leftIndex = lowerBound(arr2, num - d); + int rightIndex = upperBound(arr2, num + d); + if (leftIndex == rightIndex) { + count++; + } + } + return count; + } + + int lowerBound(List arr, int target) { + int left = 0, right = arr.length; + while (left < right) { + int mid = left + (right - left) ~/ 2; + if (arr[mid] < target) { + left = mid + 1; + } else { + right = mid; + } + } + return left; + } + + int upperBound(List arr, int target) { + int left = 0, right = arr.length; + while (left < right) { + int mid = left + (right - left) ~/ 2; + if (arr[mid] <= target) { + left = mid + 1; + } else { + right = mid; + } + } + return left; + } +} diff --git a/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.go b/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.go new file mode 100644 index 00000000..634fa910 --- /dev/null +++ b/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.go @@ -0,0 +1,12 @@ +func findTheDistanceValue(arr1 []int, arr2 []int, d int) int { + sort.Ints(arr2) + count := 0 + for _, num := range arr1 { + leftIndex := sort.SearchInts(arr2, num-d) + rightIndex := sort.SearchInts(arr2, num+d+1) + if leftIndex == rightIndex { + count++ + } + } + return count +} diff --git a/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.java b/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.java new file mode 100644 index 00000000..56d159fa --- /dev/null +++ b/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.java @@ -0,0 +1,40 @@ +class Solution { + public int findTheDistanceValue(int[] arr1, int[] arr2, int d) { + java.util.Arrays.sort(arr2); + int count = 0; + for (int num : arr1) { + int leftIndex = lowerBound(arr2, num - d); + int rightIndex = upperBound(arr2, num + d); + if (leftIndex == rightIndex) { + count++; + } + } + return count; + } + + private int lowerBound(int[] arr, int target) { + int left = 0, right = arr.length; + while (left < right) { + int mid = left + (right - left) / 2; + if (arr[mid] < target) { + left = mid + 1; + } else { + right = mid; + } + } + return left; + } + + private int upperBound(int[] arr, int target) { + int left = 0, right = arr.length; + while (left < right) { + int mid = left + (right - left) / 2; + if (arr[mid] <= target) { + left = mid + 1; + } else { + right = mid; + } + } + return left; + } +} diff --git a/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.kt b/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.kt new file mode 100644 index 00000000..551db2f4 --- /dev/null +++ b/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.kt @@ -0,0 +1,42 @@ +class Solution { + fun findTheDistanceValue(arr1: IntArray, arr2: IntArray, d: Int): Int { + arr2.sort() + var count = 0 + for (num in arr1) { + val leftIndex = lowerBound(arr2, num - d) + val rightIndex = upperBound(arr2, num + d) + if (leftIndex == rightIndex) { + count++ + } + } + return count + } + + private fun lowerBound(arr: IntArray, target: Int): Int { + var left = 0 + var right = arr.size + while (left < right) { + val mid = left + (right - left) / 2 + if (arr[mid] < target) { + left = mid + 1 + } else { + right = mid + } + } + return left + } + + private fun upperBound(arr: IntArray, target: Int): Int { + var left = 0 + var right = arr.size + while (left < right) { + val mid = left + (right - left) / 2 + if (arr[mid] <= target) { + left = mid + 1 + } else { + right = mid + } + } + return left + } +} diff --git a/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.py b/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.py new file mode 100644 index 00000000..526bf448 --- /dev/null +++ b/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.py @@ -0,0 +1,17 @@ +from typing import List +import bisect + + +class Solution: + def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int: + arr2.sort() + count = 0 + + for num in arr1: + left_index = bisect.bisect_left(arr2, num - d) + right_index = bisect.bisect_right(arr2, num + d) + + if left_index == right_index: + count += 1 + + return count diff --git a/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.py2 b/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.py2 new file mode 100644 index 00000000..a3f344d6 --- /dev/null +++ b/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.py2 @@ -0,0 +1,17 @@ +class Solution(object): + def findTheDistanceValue(self, arr1, arr2, d): + """ + :type arr1: List[int] + :type arr2: List[int] + :type d: int + :rtype: int + """ + import bisect + arr2.sort() + count = 0 + for num in arr1: + left_index = bisect.bisect_left(arr2, num - d) + right_index = bisect.bisect_right(arr2, num + d) + if left_index == right_index: + count += 1 + return count diff --git a/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.rb b/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.rb new file mode 100644 index 00000000..1cf96c1a --- /dev/null +++ b/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.rb @@ -0,0 +1,14 @@ +# @param {Integer[]} arr1 +# @param {Integer[]} arr2 +# @param {Integer} d +# @return {Integer} +def find_the_distance_value(arr1, arr2, d) + arr2.sort! + count = 0 + arr1.each do |num| + left_index = arr2.bsearch_index { |x| x >= num - d } || arr2.length + right_index = arr2.bsearch_index { |x| x > num + d } || arr2.length + count += 1 if left_index == right_index + end + count +end diff --git a/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.rs b/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.rs new file mode 100644 index 00000000..4a3d3ec5 --- /dev/null +++ b/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn find_the_distance_value(arr1: Vec, arr2: Vec, d: i32) -> i32 { + let mut arr2 = arr2; + arr2.sort(); + let mut count = 0; + for num in arr1 { + let left_index = arr2.partition_point(|&x| x < num - d); + let right_index = arr2.partition_point(|&x| x <= num + d); + if left_index == right_index { + count += 1; + } + } + count + } +} diff --git a/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.swift b/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.swift new file mode 100644 index 00000000..13c9701d --- /dev/null +++ b/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.swift @@ -0,0 +1,40 @@ +class Solution { + func findTheDistanceValue(_ arr1: [Int], _ arr2: [Int], _ d: Int) -> Int { + let sortedArr2 = arr2.sorted() + var count = 0 + for num in arr1 { + let leftIndex = lowerBound(sortedArr2, num - d) + let rightIndex = upperBound(sortedArr2, num + d) + if leftIndex == rightIndex { + count += 1 + } + } + return count + } + + private func lowerBound(_ arr: [Int], _ target: Int) -> Int { + var left = 0, right = arr.count + while left < right { + let mid = left + (right - left) / 2 + if arr[mid] < target { + left = mid + 1 + } else { + right = mid + } + } + return left + } + + private func upperBound(_ arr: [Int], _ target: Int) -> Int { + var left = 0, right = arr.count + while left < right { + let mid = left + (right - left) / 2 + if arr[mid] <= target { + left = mid + 1 + } else { + right = mid + } + } + return left + } +} diff --git a/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.ts b/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.ts new file mode 100644 index 00000000..c093a4b5 --- /dev/null +++ b/tests/1001-1500/1385. find-the-distance-value-between-two-arrays/sol.ts @@ -0,0 +1,44 @@ +function findTheDistanceValue( + arr1: number[], + arr2: number[], + d: number, +): number { + arr2.sort((a, b) => a - b); + let count = 0; + for (const num of arr1) { + const leftIndex = lowerBound(arr2, num - d); + const rightIndex = upperBound(arr2, num + d); + if (leftIndex === rightIndex) { + count++; + } + } + return count; +} + +function lowerBound(arr: number[], target: number): number { + let left = 0, + right = arr.length; + while (left < right) { + const mid = left + Math.floor((right - left) / 2); + if (arr[mid] < target) { + left = mid + 1; + } else { + right = mid; + } + } + return left; +} + +function upperBound(arr: number[], target: number): number { + let left = 0, + right = arr.length; + while (left < right) { + const mid = left + Math.floor((right - left) / 2); + if (arr[mid] <= target) { + left = mid + 1; + } else { + right = mid; + } + } + return left; +} diff --git a/tests/1001-1500/1386. cinema-seat-allocation/manifest.yaml b/tests/1001-1500/1386. cinema-seat-allocation/manifest.yaml new file mode 100644 index 00000000..99805ca8 --- /dev/null +++ b/tests/1001-1500/1386. cinema-seat-allocation/manifest.yaml @@ -0,0 +1,436 @@ +entry: + id: 1386 + title: "cinema-seat-allocation" + params: + n: + type: int + reservedSeats: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().maxNumberOfFamilies({n}, {reservedSeats})" + rust: "Solution::max_number_of_families({n}, {reservedSeats})" + python3: "Solution().maxNumberOfFamilies({n}, {reservedSeats})" + python2: "Solution().maxNumberOfFamilies({n}, {reservedSeats})" + ruby: "max_number_of_families({n}, {reservedSeats})" + java: "new Solution().maxNumberOfFamilies({n}, {reservedSeats})" + csharp: "new Solution().MaxNumberOfFamilies({n}, {reservedSeats})" + kotlin: "Solution().maxNumberOfFamilies({n}, {reservedSeats})" + go: "maxNumberOfFamilies({n}, {reservedSeats})" + dart: "Solution().maxNumberOfFamilies({n}, {reservedSeats})" + swift: "Solution().maxNumberOfFamilies({n}, {reservedSeats})" + typescript: "maxNumberOfFamilies({n}, {reservedSeats})" + +judge: + type: "exact" + +limits: + time_ms: 400 + memory_mb: 300 + +oracle: + python3: + call: "Checker().maxNumberOfFamilies(n, reservedSeats, {result})" + checker: | + class Checker: + def maxNumberOfFamilies(self, n, reservedSeats, result): + if not isinstance(result, int) or isinstance(result, bool) or result < 0: + return False + rows = {} + for row, seat in reservedSeats: + rows.setdefault(row, set()).add(seat) + expected = (n - len(rows)) * 2 + blocks = ((2, 3, 4, 5), (4, 5, 6, 7), (6, 7, 8, 9)) + for seats in rows.values(): + usable = [all(seat not in seats for seat in block) for block in blocks] + expected += (2 if usable[0] and usable[2] else 1 if any(usable) else 0) + return result == expected + +seed: 1386001 + +tests: + - name: "example_1" + in: + n: 3 + reservedSeats: + - [1, 2] + - [1, 3] + - [1, 8] + - [2, 6] + - [3, 1] + - [3, 10] + - name: "example_2" + in: + n: 2 + reservedSeats: + - [2, 1] + - [1, 8] + - [2, 6] + - name: "example_3" + in: + n: 4 + reservedSeats: + - [4, 3] + - [1, 4] + - [4, 6] + - [1, 7] + - name: "one_empty_row" + in: + n: 1 + reservedSeats: + - [1, 1] + - name: "one_full_row" + in: + n: 1 + reservedSeats: + - [1, 1] + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [1, 6] + - [1, 7] + - [1, 8] + - [1, 9] + - [1, 10] + - name: "no_reservations" + in: + n: 10 + reservedSeats: + - [1, 1] + - name: "middle_only_free" + in: + n: 1 + reservedSeats: + - [1, 2] + - [1, 3] + - [1, 8] + - [1, 9] + - name: "left_block_blocked" + in: + n: 1 + reservedSeats: + - [1, 2] + - name: "right_block_blocked" + in: + n: 1 + reservedSeats: + - [1, 8] + - name: "middle_block_blocked" + in: + n: 1 + reservedSeats: + - [1, 5] + - name: "two_rows_distinct" + in: + n: 2 + reservedSeats: + - [1, 2] + - [2, 6] + - name: "reserved_outside_blocks" + in: + n: 3 + reservedSeats: + - [1, 1] + - [1, 10] + - [2, 2] + - [3, 5] + - name: "all_rows_touched" + in: + n: 5 + reservedSeats: + - [1, 1] + - [2, 1] + - [3, 1] + - [4, 1] + - [5, 1] + - name: "overlap_prefers_outer" + in: + n: 1 + reservedSeats: + - [1, 4] + - name: "overlap_prefers_middle" + in: + n: 1 + reservedSeats: + - [1, 2] + - [1, 8] + - name: "single_seat_each" + in: + n: 6 + reservedSeats: + - [1, 2] + - [2, 4] + - [3, 6] + - [4, 8] + - [5, 5] + - [6, 10] + - name: "large_n_few_rows" + in: + n: 1000000000 + reservedSeats: + - [1, 2] + - [500000000, 6] + - [1000000000, 9] + - name: "adjacent_reserved" + in: + n: 2 + reservedSeats: + - [1, 3] + - [1, 4] + - [1, 7] + - [2, 5] + - [2, 6] + - name: "edge_seats_only" + in: + n: 4 + reservedSeats: + - [1, 1] + - [1, 10] + - [2, 1] + - [2, 10] + - [3, 1] + - [4, 10] + - name: "all_left_reserved" + in: + n: 3 + reservedSeats: + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [2, 2] + - [2, 5] + - name: "all_right_reserved" + in: + n: 3 + reservedSeats: + - [1, 6] + - [1, 7] + - [1, 8] + - [1, 9] + - [3, 7] + - name: "middle_reservation_patterns" + in: + n: 4 + reservedSeats: + - [1, 4] + - [2, 5] + - [3, 6] + - [4, 7] + - name: "many_empty_rows" + in: + n: 20 + reservedSeats: + - [2, 2] + - [10, 8] + - name: "ten_reserved_rows" + in: + n: 10 + reservedSeats: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 1] + - [10, 10] + - name: "duplicate_block_boundary" + in: + n: 2 + reservedSeats: + - [1, 5] + - [1, 6] + - [2, 4] + - [2, 7] + - name: "left_and_right_free" + in: + n: 2 + reservedSeats: + - [1, 4] + - [1, 5] + - [1, 6] + - [1, 7] + - name: "only_middle_free" + in: + n: 2 + reservedSeats: + - [1, 2] + - [1, 3] + - [1, 8] + - [1, 9] + - name: "seat_ten_boundary" + in: + n: 5 + reservedSeats: + - [5, 10] + - [4, 1] + - [3, 2] + - name: "maximal_sparse_input" + in: + n: 1000000000 + reservedSeats: + - [1, 1] + - [2, 2] + - [3, 3] + - [4, 4] + - [5, 5] + - [6, 6] + - [7, 7] + - [8, 8] + - [9, 9] + - [10, 10] + - name: "mixed_three_rows" + in: + n: 3 + reservedSeats: + - [1, 2] + - [1, 9] + - [2, 4] + - [2, 7] + - [3, 5] + - [3, 6] + - name: "alternating_rows" + in: + n: 8 + reservedSeats: + - [1, 2] + - [3, 2] + - [5, 2] + - [7, 2] + - name: "full_middle_reservations" + in: + n: 3 + reservedSeats: + - [1, 4] + - [1, 5] + - [1, 6] + - [1, 7] + - [2, 4] + - [2, 5] + - [2, 6] + - [2, 7] + - [3, 4] + - [3, 5] + - [3, 6] + - [3, 7] + - name: "near_limit_rows" + in: + n: 999999999 + reservedSeats: + - [999999999, 2] + - [999999998, 8] + - [999999997, 5] + - name: "mixed_edge_and_overlap" + in: + n: 7 + reservedSeats: + - [1, 1] + - [1, 4] + - [2, 10] + - [3, 2] + - [4, 5] + - [5, 7] + - [6, 3] + - [7, 9] + - name: "single_row_seat_one_to_ten" + in: + n: 1 + reservedSeats: + - [1, 1] + - [1, 10] + + - name: "generated_small_sparse" + seed: 138601 + in: + n: 1000000000 + reservedSeats: + gen: "array" + len: + gen: "int" + min: 1 + max: 20 + distinct: true + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 1 + max: 1000000000 + + - name: "generated_small_mixed" + seed: 138602 + in: + n: 1000000000 + reservedSeats: + gen: "array" + len: + gen: "int" + min: 10 + max: 40 + distinct: true + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 1 + max: 1000000000 + + - name: "generated_boundary_seats" + seed: 138603 + in: + n: 1000000000 + reservedSeats: + gen: "array" + len: + gen: "int" + min: 1 + max: 50 + distinct: true + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 1 + max: 10 + + - name: "generated_large_maximum" + seed: 138604 + in: + n: 1000000000 + reservedSeats: + gen: "array" + len: 10000 + distinct: true + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 1 + max: 1000000000 + + - name: "generated_large_near_maximum" + seed: 138605 + in: + n: 999999999 + reservedSeats: + gen: "array" + len: 9999 + distinct: true + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 1 + max: 999999999 diff --git a/tests/1001-1500/1386. cinema-seat-allocation/sol.cpp b/tests/1001-1500/1386. cinema-seat-allocation/sol.cpp new file mode 100644 index 00000000..240a2145 --- /dev/null +++ b/tests/1001-1500/1386. cinema-seat-allocation/sol.cpp @@ -0,0 +1,53 @@ +class Solution { +public: + int maxNumberOfFamilies(int n, vector>& reservedSeats) { + unordered_map> rowSeats; + + for (auto& reservation : reservedSeats) { + int row = reservation[0]; + int seat = reservation[1]; + rowSeats[row].insert(seat); + } + + int ans = (n - rowSeats.size()) * 2; + + unordered_set option1 = {2, 3, 4, 5}; + unordered_set option2 = {6, 7, 8, 9}; + unordered_set option3 = {4, 5, 6, 7}; + + for (auto& [row, seats] : rowSeats) { + int available = 0; + + bool disjoint1 = true; + for (int s : option1) { + if (seats.count(s)) { + disjoint1 = false; + break; + } + } + if (disjoint1) available++; + + bool disjoint2 = true; + for (int s : option2) { + if (seats.count(s)) { + disjoint2 = false; + break; + } + } + if (disjoint2) available++; + + bool disjoint3 = true; + for (int s : option3) { + if (seats.count(s)) { + disjoint3 = false; + break; + } + } + if (disjoint3) available = max(available, 1); + + ans += available; + } + + return ans; + } +}; diff --git a/tests/1001-1500/1386. cinema-seat-allocation/sol.cs b/tests/1001-1500/1386. cinema-seat-allocation/sol.cs new file mode 100644 index 00000000..988cdd21 --- /dev/null +++ b/tests/1001-1500/1386. cinema-seat-allocation/sol.cs @@ -0,0 +1,36 @@ +public class Solution { + public int MaxNumberOfFamilies(int n, int[][] reservedSeats) { + Dictionary> rowSeats = new Dictionary>(); + + foreach (var reservation in reservedSeats) { + int row = reservation[0]; + int seat = reservation[1]; + if (!rowSeats.ContainsKey(row)) { + rowSeats[row] = new HashSet(); + } + rowSeats[row].Add(seat); + } + + int ans = (n - rowSeats.Count) * 2; + + HashSet option1 = new HashSet { 2, 3, 4, 5 }; + HashSet option2 = new HashSet { 6, 7, 8, 9 }; + HashSet option3 = new HashSet { 4, 5, 6, 7 }; + + foreach (var seats in rowSeats.Values) { + int available = 0; + if (!seats.Overlaps(option1)) { + available += 1; + } + if (!seats.Overlaps(option2)) { + available += 1; + } + if (!seats.Overlaps(option3)) { + available = Math.Max(available, 1); + } + ans += available; + } + + return ans; + } +} diff --git a/tests/1001-1500/1386. cinema-seat-allocation/sol.dart b/tests/1001-1500/1386. cinema-seat-allocation/sol.dart new file mode 100644 index 00000000..abf209f8 --- /dev/null +++ b/tests/1001-1500/1386. cinema-seat-allocation/sol.dart @@ -0,0 +1,33 @@ +class Solution { + int maxNumberOfFamilies(int n, List> reservedSeats) { + Map> rowSeats = {}; + + for (var reservation in reservedSeats) { + int row = reservation[0]; + int seat = reservation[1]; + rowSeats.putIfAbsent(row, () => {}).add(seat); + } + + int ans = (n - rowSeats.length) * 2; + + Set option1 = {2, 3, 4, 5}; + Set option2 = {6, 7, 8, 9}; + Set option3 = {4, 5, 6, 7}; + + for (var seats in rowSeats.values) { + int available = 0; + if (seats.intersection(option1).isEmpty) { + available += 1; + } + if (seats.intersection(option2).isEmpty) { + available += 1; + } + if (seats.intersection(option3).isEmpty) { + available = available > 1 ? available : 1; + } + ans += available; + } + + return ans; + } +} diff --git a/tests/1001-1500/1386. cinema-seat-allocation/sol.go b/tests/1001-1500/1386. cinema-seat-allocation/sol.go new file mode 100644 index 00000000..956b1d7f --- /dev/null +++ b/tests/1001-1500/1386. cinema-seat-allocation/sol.go @@ -0,0 +1,58 @@ +func maxNumberOfFamilies(n int, reservedSeats [][]int) int { + rowSeats := make(map[int]map[int]bool) + + for _, reservation := range reservedSeats { + row, seat := reservation[0], reservation[1] + if rowSeats[row] == nil { + rowSeats[row] = make(map[int]bool) + } + rowSeats[row][seat] = true + } + + ans := (n - len(rowSeats)) * 2 + + option1 := map[int]bool{2: true, 3: true, 4: true, 5: true} + option2 := map[int]bool{6: true, 7: true, 8: true, 9: true} + option3 := map[int]bool{4: true, 5: true, 6: true, 7: true} + + for _, seats := range rowSeats { + available := 0 + + disjoint1 := true + for seat := range option1 { + if seats[seat] { + disjoint1 = false + break + } + } + if disjoint1 { + available++ + } + + disjoint2 := true + for seat := range option2 { + if seats[seat] { + disjoint2 = false + break + } + } + if disjoint2 { + available++ + } + + disjoint3 := true + for seat := range option3 { + if seats[seat] { + disjoint3 = false + break + } + } + if disjoint3 && available < 1 { + available = 1 + } + + ans += available + } + + return ans +} diff --git a/tests/1001-1500/1386. cinema-seat-allocation/sol.java b/tests/1001-1500/1386. cinema-seat-allocation/sol.java new file mode 100644 index 00000000..8e218cdc --- /dev/null +++ b/tests/1001-1500/1386. cinema-seat-allocation/sol.java @@ -0,0 +1,35 @@ +import java.util.*; + +class Solution { + public int maxNumberOfFamilies(int n, int[][] reservedSeats) { + Map> rowSeats = new HashMap<>(); + + for (int[] reservation : reservedSeats) { + int row = reservation[0]; + int seat = reservation[1]; + rowSeats.computeIfAbsent(row, k -> new HashSet<>()).add(seat); + } + + int ans = (n - rowSeats.size()) * 2; + + Set option1 = new HashSet<>(Arrays.asList(2, 3, 4, 5)); + Set option2 = new HashSet<>(Arrays.asList(6, 7, 8, 9)); + Set option3 = new HashSet<>(Arrays.asList(4, 5, 6, 7)); + + for (Set seats : rowSeats.values()) { + int available = 0; + if (Collections.disjoint(option1, seats)) { + available += 1; + } + if (Collections.disjoint(option2, seats)) { + available += 1; + } + if (Collections.disjoint(option3, seats)) { + available = Math.max(available, 1); + } + ans += available; + } + + return ans; + } +} diff --git a/tests/1001-1500/1386. cinema-seat-allocation/sol.kt b/tests/1001-1500/1386. cinema-seat-allocation/sol.kt new file mode 100644 index 00000000..3d24dad4 --- /dev/null +++ b/tests/1001-1500/1386. cinema-seat-allocation/sol.kt @@ -0,0 +1,31 @@ +class Solution { + fun maxNumberOfFamilies(n: Int, reservedSeats: Array): Int { + val rowSeats = mutableMapOf>() + + for ((row, seat) in reservedSeats) { + rowSeats.getOrPut(row) { mutableSetOf() }.add(seat) + } + + var ans = (n - rowSeats.size) * 2 + + val option1 = setOf(2, 3, 4, 5) + val option2 = setOf(6, 7, 8, 9) + val option3 = setOf(4, 5, 6, 7) + + for (seats in rowSeats.values) { + var available = 0 + if (seats.intersect(option1).isEmpty()) { + available += 1 + } + if (seats.intersect(option2).isEmpty()) { + available += 1 + } + if (seats.intersect(option3).isEmpty()) { + available = maxOf(available, 1) + } + ans += available + } + + return ans + } +} diff --git a/tests/1001-1500/1386. cinema-seat-allocation/sol.py b/tests/1001-1500/1386. cinema-seat-allocation/sol.py new file mode 100644 index 00000000..8d89e3df --- /dev/null +++ b/tests/1001-1500/1386. cinema-seat-allocation/sol.py @@ -0,0 +1,31 @@ +from collections import defaultdict + + +class Solution: + def maxNumberOfFamilies(self, n: int, reservedSeats: List[List[int]]) -> int: + row_seats = defaultdict(set) + + for row, seat in reservedSeats: + row_seats[row].add(seat) + + # all the empty rows are available so start your answer with those + ans = (n - len(row_seats)) * 2 + + # iterate over the row_seats that were allocated + for row, seats in row_seats.items(): + available = 0 + # chech non overlapping two seats first + option1 = {2, 3, 4, 5} + option2 = {6, 7, 8, 9} + if option1.isdisjoint(seats): + available += 1 + if option2.isdisjoint(seats): + available += 1 + + option3 = {4, 5, 6, 7} # if in the middle + if option3.isdisjoint(seats): + available = max(available, 1) + + ans += available + + return ans diff --git a/tests/1001-1500/1386. cinema-seat-allocation/sol.py2 b/tests/1001-1500/1386. cinema-seat-allocation/sol.py2 new file mode 100644 index 00000000..01c066e6 --- /dev/null +++ b/tests/1001-1500/1386. cinema-seat-allocation/sol.py2 @@ -0,0 +1,30 @@ +class Solution(object): + def maxNumberOfFamilies(self, n, reservedSeats): + """ + :type n: int + :type reservedSeats: List[List[int]] + :rtype: int + """ + from collections import defaultdict + row_seats = defaultdict(set) + + for row, seat in reservedSeats: + row_seats[row].add(seat) + + ans = (n - len(row_seats)) * 2 + + option1 = {2, 3, 4, 5} + option2 = {6, 7, 8, 9} + option3 = {4, 5, 6, 7} + + for seats in row_seats.values(): + available = 0 + if option1.isdisjoint(seats): + available += 1 + if option2.isdisjoint(seats): + available += 1 + if option3.isdisjoint(seats): + available = max(available, 1) + ans += available + + return ans diff --git a/tests/1001-1500/1386. cinema-seat-allocation/sol.rb b/tests/1001-1500/1386. cinema-seat-allocation/sol.rb new file mode 100644 index 00000000..2abcc380 --- /dev/null +++ b/tests/1001-1500/1386. cinema-seat-allocation/sol.rb @@ -0,0 +1,32 @@ +# @param {Integer} n +# @param {Integer[][]} reserved_seats +# @return {Integer} +def max_number_of_families(n, reserved_seats) + row_seats = Hash.new { |hash, key| hash[key] = Set.new } + + reserved_seats.each do |row, seat| + row_seats[row].add(seat) + end + + ans = (n - row_seats.size) * 2 + + option1 = Set.new([2, 3, 4, 5]) + option2 = Set.new([6, 7, 8, 9]) + option3 = Set.new([4, 5, 6, 7]) + + row_seats.each_value do |seats| + available = 0 + if (option1 & seats).empty? + available += 1 + end + if (option2 & seats).empty? + available += 1 + end + if (option3 & seats).empty? + available = [available, 1].max + end + ans += available + end + + ans +end diff --git a/tests/1001-1500/1386. cinema-seat-allocation/sol.rs b/tests/1001-1500/1386. cinema-seat-allocation/sol.rs new file mode 100644 index 00000000..c6d140f3 --- /dev/null +++ b/tests/1001-1500/1386. cinema-seat-allocation/sol.rs @@ -0,0 +1,35 @@ +use std::collections::{HashMap, HashSet}; + +impl Solution { + pub fn max_number_of_families(n: i32, reserved_seats: Vec>) -> i32 { + let mut row_seats: HashMap> = HashMap::new(); + + for reservation in reserved_seats { + let row = reservation[0]; + let seat = reservation[1]; + row_seats.entry(row).or_insert_with(HashSet::new).insert(seat); + } + + let mut ans = (n - row_seats.len() as i32) * 2; + + let option1: HashSet = [2, 3, 4, 5].iter().cloned().collect(); + let option2: HashSet = [6, 7, 8, 9].iter().cloned().collect(); + let option3: HashSet = [4, 5, 6, 7].iter().cloned().collect(); + + for seats in row_seats.values() { + let mut available = 0; + if seats.is_disjoint(&option1) { + available += 1; + } + if seats.is_disjoint(&option2) { + available += 1; + } + if seats.is_disjoint(&option3) { + available = available.max(1); + } + ans += available; + } + + ans + } +} diff --git a/tests/1001-1500/1386. cinema-seat-allocation/sol.swift b/tests/1001-1500/1386. cinema-seat-allocation/sol.swift new file mode 100644 index 00000000..18590bf8 --- /dev/null +++ b/tests/1001-1500/1386. cinema-seat-allocation/sol.swift @@ -0,0 +1,33 @@ +class Solution { + func maxNumberOfFamilies(_ n: Int, _ reservedSeats: [[Int]]) -> Int { + var rowSeats: [Int: Set] = [:] + + for reservation in reservedSeats { + let row = reservation[0] + let seat = reservation[1] + rowSeats[row, default: Set()].insert(seat) + } + + var ans = (n - rowSeats.count) * 2 + + let option1: Set = [2, 3, 4, 5] + let option2: Set = [6, 7, 8, 9] + let option3: Set = [4, 5, 6, 7] + + for seats in rowSeats.values { + var available = 0 + if seats.isDisjoint(with: option1) { + available += 1 + } + if seats.isDisjoint(with: option2) { + available += 1 + } + if seats.isDisjoint(with: option3) { + available = max(available, 1) + } + ans += available + } + + return ans + } +} diff --git a/tests/1001-1500/1386. cinema-seat-allocation/sol.ts b/tests/1001-1500/1386. cinema-seat-allocation/sol.ts new file mode 100644 index 00000000..a3903493 --- /dev/null +++ b/tests/1001-1500/1386. cinema-seat-allocation/sol.ts @@ -0,0 +1,32 @@ +function maxNumberOfFamilies(n: number, reservedSeats: number[][]): number { + const rowSeats: Map> = new Map(); + + for (const [row, seat] of reservedSeats) { + if (!rowSeats.has(row)) { + rowSeats.set(row, new Set()); + } + rowSeats.get(row)!.add(seat); + } + + let ans = (n - rowSeats.size) * 2; + + const option1 = new Set([2, 3, 4, 5]); + const option2 = new Set([6, 7, 8, 9]); + const option3 = new Set([4, 5, 6, 7]); + + for (const seats of rowSeats.values()) { + let available = 0; + if (![...option1].some((s) => seats.has(s))) { + available += 1; + } + if (![...option2].some((s) => seats.has(s))) { + available += 1; + } + if (![...option3].some((s) => seats.has(s))) { + available = Math.max(available, 1); + } + ans += available; + } + + return ans; +} diff --git a/tests/1001-1500/1387. sort-integers-by-the-power-value/manifest.yaml b/tests/1001-1500/1387. sort-integers-by-the-power-value/manifest.yaml new file mode 100644 index 00000000..6d8b7e11 --- /dev/null +++ b/tests/1001-1500/1387. sort-integers-by-the-power-value/manifest.yaml @@ -0,0 +1,303 @@ +entry: + id: 1387 + title: "sort-integers-by-the-power-value" + params: + lo: + type: int + hi: + type: int + k: + type: int + call: + cpp: "Solution().getKth({lo}, {hi}, {k})" + rust: "Solution::get_kth({lo}, {hi}, {k})" + python3: "Solution().getKth({lo}, {hi}, {k})" + python2: "Solution().getKth({lo}, {hi}, {k})" + ruby: "get_kth({lo}, {hi}, {k})" + java: "new Solution().getKth({lo}, {hi}, {k})" + csharp: "new Solution().GetKth({lo}, {hi}, {k})" + kotlin: "Solution().getKth({lo}, {hi}, {k})" + go: "getKth({lo}, {hi}, {k})" + dart: "Solution().getKth({lo}, {hi}, {k})" + swift: "Solution().getKth({lo}, {hi}, {k})" + typescript: "getKth({lo}, {hi}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().getKth(lo, hi, k, {result})" + checker: | + class Checker: + def getKth(self, lo, hi, k, result): + def power(x): + steps = 0 + while x != 1: + x = x // 2 if x % 2 == 0 else 3 * x + 1 + steps += 1 + return steps + expected = sorted(range(lo, hi + 1), key=lambda x: (power(x), x))[k - 1] + return result == expected + +seed: 1387 + +tests: + - name: "singleton_one" + in: + lo: 1 + hi: 1 + k: 1 + out: 1 + - name: "singleton_four" + in: + lo: 4 + hi: 4 + k: 1 + out: 4 + - name: "short_interval_first" + in: + lo: 5 + hi: 8 + k: 1 + out: 8 + - name: "short_interval_last" + in: + lo: 5 + hi: 8 + k: 4 + out: 7 + - name: "example_two_first" + in: + lo: 7 + hi: 11 + k: 1 + out: 8 + - name: "example_two_fourth" + in: + lo: 7 + hi: 11 + k: 4 + out: 7 + - name: "example_two_last" + in: + lo: 7 + hi: 11 + k: 5 + out: 9 + - name: "medium_first" + in: + lo: 10 + hi: 15 + k: 1 + out: 10 + - name: "medium_last" + in: + lo: 10 + hi: 15 + k: 6 + out: 15 + - name: "example_one_tie" + in: + lo: 12 + hi: 15 + k: 2 + out: 13 + - name: "example_one_last" + in: + lo: 12 + hi: 15 + k: 4 + out: 15 + - name: "powers_of_two_first" + in: + lo: 16 + hi: 20 + k: 1 + out: 16 + - name: "powers_of_two_range_last" + in: + lo: 16 + hi: 20 + k: 5 + out: 19 + - name: "twenties_middle" + in: + lo: 20 + hi: 25 + k: 3 + out: 24 + - name: "late_twenties" + in: + lo: 25 + hi: 30 + k: 2 + out: 28 + - name: "thirties_first" + in: + lo: 30 + hi: 40 + k: 1 + out: 32 + - name: "thirties_last" + in: + lo: 30 + hi: 40 + k: 11 + out: 31 + - name: "fifties_middle" + in: + lo: 50 + hi: 60 + k: 5 + out: 60 + - name: "fifties_last" + in: + lo: 50 + hi: 60 + k: 11 + out: 55 + - name: "hundreds_first" + in: + lo: 100 + hi: 110 + k: 1 + out: 104 + - name: "hundreds_middle" + in: + lo: 100 + hi: 110 + k: 6 + out: 105 + - name: "hundreds_last" + in: + lo: 100 + hi: 110 + k: 11 + out: 110 + - name: "two_hundreds_middle" + in: + lo: 200 + hi: 220 + k: 10 + out: 203 + - name: "three_hundreds_first" + in: + lo: 300 + hi: 350 + k: 1 + out: 320 + - name: "three_hundreds_last" + in: + lo: 300 + hi: 350 + k: 51 + out: 327 + - name: "five_hundreds_middle" + in: + lo: 500 + hi: 550 + k: 25 + out: 509 + - name: "five_hundreds_last" + in: + lo: 500 + hi: 550 + k: 51 + out: 543 + - name: "nine_hundreds_early" + in: + lo: 900 + hi: 950 + k: 7 + out: 938 + - name: "nine_hundreds_late" + in: + lo: 900 + hi: 950 + k: 44 + out: 925 + - name: "maximum_range_first_half" + in: + lo: 950 + hi: 1000 + k: 1 + out: 960 + - name: "maximum_range_last" + in: + lo: 950 + hi: 1000 + k: 51 + out: 983 + - name: "full_constraints_first" + in: + lo: 1 + hi: 1000 + k: 1 + out: 1 + - name: "full_constraints_middle" + in: + lo: 1 + hi: 1000 + k: 500 + out: 606 + - name: "full_constraints_near_last" + in: + lo: 1 + hi: 1000 + k: 999 + - name: "full_constraints_last" + in: + lo: 1 + hi: 1000 + k: 1000 + out: 871 + - name: "generated_full_range_low_rank" + seed: 138701 + in: + lo: 1 + hi: 1000 + k: + gen: "int" + min: 1 + max: 1000 + - name: "generated_full_range_early_rank" + seed: 138702 + in: + lo: 1 + hi: 1000 + k: + gen: "int" + min: 1 + max: 1000 + - name: "generated_full_range_middle_rank" + seed: 138703 + in: + lo: 1 + hi: 1000 + k: + gen: "int" + min: 1 + max: 1000 + - name: "generated_full_range_late_rank" + seed: 138704 + in: + lo: 1 + hi: 1000 + k: + gen: "int" + min: 1 + max: 1000 + - name: "generated_full_range_high_rank" + seed: 138705 + in: + lo: 1 + hi: 1000 + k: + gen: "int" + min: 1 + max: 1000 diff --git a/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.cpp b/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.cpp new file mode 100644 index 00000000..36a7b637 --- /dev/null +++ b/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int getKth(int lo, int hi, int k) { + vector> vc; + for (int i = lo; i <= hi; i++) { + int num = i; + int count = 0; + while (num != 1) { + if (num % 2 == 0) { + num /= 2; + } else { + num = 3 * num + 1; + } + count++; + } + vc.push_back({i, count}); + } + sort(vc.begin(), vc.end(), [](const pair& a, const pair& b) { + if (a.second != b.second) return a.second < b.second; + return a.first < b.first; + }); + return vc[k - 1].first; + } +}; diff --git a/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.cs b/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.cs new file mode 100644 index 00000000..87ca25b0 --- /dev/null +++ b/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.cs @@ -0,0 +1,23 @@ +public class Solution { + public int GetKth(int lo, int hi, int k) { + var vc = new List<(int, int)>(); + for (int i = lo; i <= hi; i++) { + int num = i; + int count = 0; + while (num != 1) { + if (num % 2 == 0) { + num /= 2; + } else { + num = 3 * num + 1; + } + count++; + } + vc.Add((i, count)); + } + vc.Sort((a, b) => { + if (a.Item2 != b.Item2) return a.Item2.CompareTo(b.Item2); + return a.Item1.CompareTo(b.Item1); + }); + return vc[k - 1].Item1; + } +} diff --git a/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.dart b/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.dart new file mode 100644 index 00000000..718d5569 --- /dev/null +++ b/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.dart @@ -0,0 +1,23 @@ +class Solution { + int getKth(int lo, int hi, int k) { + List> vc = []; + for (int i = lo; i <= hi; i++) { + int num = i; + int count = 0; + while (num != 1) { + if (num % 2 == 0) { + num ~/= 2; + } else { + num = 3 * num + 1; + } + count++; + } + vc.add([i, count]); + } + vc.sort((a, b) { + if (a[1] != b[1]) return a[1].compareTo(b[1]); + return a[0].compareTo(b[0]); + }); + return vc[k - 1][0]; + } +} diff --git a/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.go b/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.go new file mode 100644 index 00000000..c6681acc --- /dev/null +++ b/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.go @@ -0,0 +1,26 @@ +func getKth(lo int, hi int, k int) int { + type pair struct { + val, steps int + } + vc := make([]pair, 0, hi-lo+1) + for i := lo; i <= hi; i++ { + num := i + count := 0 + for num != 1 { + if num%2 == 0 { + num /= 2 + } else { + num = 3*num + 1 + } + count++ + } + vc = append(vc, pair{i, count}) + } + sort.Slice(vc, func(i, j int) bool { + if vc[i].steps != vc[j].steps { + return vc[i].steps < vc[j].steps + } + return vc[i].val < vc[j].val + }) + return vc[k-1].val +} diff --git a/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.java b/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.java new file mode 100644 index 00000000..e56dfaa4 --- /dev/null +++ b/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.java @@ -0,0 +1,27 @@ +class Solution { + public int getKth(int lo, int hi, int k) { + int n = hi - lo + 1; + int[][] vc = new int[n][2]; + int idx = 0; + for (int i = lo; i <= hi; i++) { + int num = i; + int count = 0; + while (num != 1) { + if (num % 2 == 0) { + num /= 2; + } else { + num = 3 * num + 1; + } + count++; + } + vc[idx][0] = i; + vc[idx][1] = count; + idx++; + } + java.util.Arrays.sort(vc, (a, b) -> { + if (a[1] != b[1]) return Integer.compare(a[1], b[1]); + return Integer.compare(a[0], b[0]); + }); + return vc[k - 1][0]; + } +} diff --git a/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.kt b/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.kt new file mode 100644 index 00000000..16e6771d --- /dev/null +++ b/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.kt @@ -0,0 +1,20 @@ +class Solution { + fun getKth(lo: Int, hi: Int, k: Int): Int { + val vc = mutableListOf>() + for (i in lo..hi) { + var num = i + var count = 0 + while (num != 1) { + if (num % 2 == 0) { + num /= 2 + } else { + num = 3 * num + 1 + } + count++ + } + vc.add(Pair(i, count)) + } + vc.sortWith(compareBy> { it.second }.thenBy { it.first }) + return vc[k - 1].first + } +} diff --git a/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.py b/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.py new file mode 100644 index 00000000..94cb0bac --- /dev/null +++ b/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.py @@ -0,0 +1,22 @@ +class Solution: + def getKth(self, lo, hi, k): + + vc = [] + + for i in range(lo, hi + 1): + num = i + count = 0 + + while num != 1: + if num % 2 == 0: + num //= 2 + else: + num = 3 * num + 1 + + count += 1 + + vc.append((i, count)) + + vc.sort(key=lambda x: (x[1], x[0])) + + return vc[k - 1][0] diff --git a/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.py2 b/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.py2 new file mode 100644 index 00000000..625bab94 --- /dev/null +++ b/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.py2 @@ -0,0 +1,21 @@ +class Solution(object): + def getKth(self, lo, hi, k): + """ + :type lo: int + :type hi: int + :type k: int + :rtype: int + """ + vc = [] + for i in range(lo, hi + 1): + num = i + count = 0 + while num != 1: + if num % 2 == 0: + num //= 2 + else: + num = 3 * num + 1 + count += 1 + vc.append((i, count)) + vc.sort(key=lambda x: (x[1], x[0])) + return vc[k - 1][0] diff --git a/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.rb b/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.rb new file mode 100644 index 00000000..03325cd8 --- /dev/null +++ b/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.rb @@ -0,0 +1,22 @@ +# @param {Integer} lo +# @param {Integer} hi +# @param {Integer} k +# @return {Integer} +def get_kth(lo, hi, k) + vc = [] + (lo..hi).each do |i| + num = i + count = 0 + while num != 1 + if num % 2 == 0 + num /= 2 + else + num = 3 * num + 1 + end + count += 1 + end + vc << [i, count] + end + vc.sort_by! { |x| [x[1], x[0]] } + vc[k - 1][0] +end diff --git a/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.rs b/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.rs new file mode 100644 index 00000000..ade6fd42 --- /dev/null +++ b/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.rs @@ -0,0 +1,20 @@ +impl Solution { + pub fn get_kth(lo: i32, hi: i32, k: i32) -> i32 { + let mut vc: Vec<(i32, i32)> = Vec::new(); + for i in lo..=hi { + let mut num = i; + let mut count = 0; + while num != 1 { + if num % 2 == 0 { + num /= 2; + } else { + num = 3 * num + 1; + } + count += 1; + } + vc.push((i, count)); + } + vc.sort_by_key(|x| (x.1, x.0)); + vc[(k - 1) as usize].0 + } +} diff --git a/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.swift b/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.swift new file mode 100644 index 00000000..3956757e --- /dev/null +++ b/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.swift @@ -0,0 +1,25 @@ +class Solution { + func getKth(_ lo: Int, _ hi: Int, _ k: Int) -> Int { + var vc: [(Int, Int)] = [] + for i in lo...hi { + var num = i + var count = 0 + while num != 1 { + if num % 2 == 0 { + num /= 2 + } else { + num = 3 * num + 1 + } + count += 1 + } + vc.append((i, count)) + } + vc.sort { + if $0.1 != $1.1 { + return $0.1 < $1.1 + } + return $0.0 < $1.0 + } + return vc[k - 1].0 + } +} diff --git a/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.ts b/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.ts new file mode 100644 index 00000000..0876006f --- /dev/null +++ b/tests/1001-1500/1387. sort-integers-by-the-power-value/sol.ts @@ -0,0 +1,21 @@ +function getKth(lo: number, hi: number, k: number): number { + const vc: [number, number][] = []; + for (let i = lo; i <= hi; i++) { + let num = i; + let count = 0; + while (num !== 1) { + if (num % 2 === 0) { + num = Math.floor(num / 2); + } else { + num = 3 * num + 1; + } + count++; + } + vc.push([i, count]); + } + vc.sort((a, b) => { + if (a[1] !== b[1]) return a[1] - b[1]; + return a[0] - b[0]; + }); + return vc[k - 1][0]; +} diff --git a/tests/1001-1500/1388. pizza-with-3n-slices/manifest.yaml b/tests/1001-1500/1388. pizza-with-3n-slices/manifest.yaml new file mode 100644 index 00000000..b4ea4589 --- /dev/null +++ b/tests/1001-1500/1388. pizza-with-3n-slices/manifest.yaml @@ -0,0 +1,408 @@ +entry: + id: 1388 + title: pizza-with-3n-slices + params: + slices: + type: array + items: + type: int + call: + cpp: "Solution().maxSizeSlices({slices})" + rust: "Solution::max_size_slices({slices})" + python3: "Solution().maxSizeSlices({slices})" + python2: "Solution().maxSizeSlices({slices})" + ruby: "max_size_slices({slices})" + java: "new Solution().maxSizeSlices({slices})" + csharp: "new Solution().MaxSizeSlices({slices})" + kotlin: "Solution().maxSizeSlices({slices})" + go: "maxSizeSlices({slices})" + dart: "Solution().maxSizeSlices({slices})" + swift: "Solution().maxSizeSlices({slices})" + typescript: "maxSizeSlices({slices})" +judge: + type: exact +limits: + time_ms: 1000 + memory_mb: 256 +oracle: + python3: + call: "Checker().maxSizeSlices(slices, {result})" + checker: | + class Checker: + def maxSizeSlices(self, slices, result): + if not isinstance(slices, list) or len(slices) < 3 or len(slices) > 500 or len(slices) % 3 != 0: + return False + if any(not isinstance(value, int) or isinstance(value, bool) or value < 1 or value > 1000 for value in slices): + return False + if not isinstance(result, int) or isinstance(result, bool): + return False + picks = len(slices) // 3 + def solve(values): + impossible = -10**18 + rows = len(values) + dp = [[impossible] * (picks + 1) for _ in range(rows + 1)] + for row in range(rows + 1): + dp[row][0] = 0 + for row in range(1, rows + 1): + limit = min(picks, (row + 1) // 2) + for count in range(1, limit + 1): + skip = dp[row - 1][count] + take = values[0] if row == 1 and count == 1 else (dp[row - 2][count - 1] + values[row - 1] if row > 1 else impossible) + dp[row][count] = max(skip, take) + return dp[rows][picks] + expected = max(solve(slices[1:]), solve(slices[:-1])) + return result == expected +seed: 1388 +tests: + - name: minimum_three + in: + slices: [1, 2, 3] + - name: six_basic + in: + slices: [1, 2, 3, 4, 5, 6] + - name: six_high_edges + in: + slices: [100, 1, 1, 1, 1, 100] + - name: six_middle_high + in: + slices: [1, 100, 1, 100, 1, 1] + - name: nine_increasing + in: + slices: [1, 2, 3, 4, 5, 6, 7, 8, 9] + - name: nine_decreasing + in: + slices: [9, 8, 7, 6, 5, 4, 3, 2, 1] + - name: nine_alternating + in: + slices: [100, 1, 100, 1, 100, 1, 100, 1, 100] + - name: nine_edges_low + in: + slices: [1, 50, 40, 30, 20, 10, 9, 8, 1] + - name: twelve_basic + in: + slices: [1, 4, 2, 8, 5, 7, 3, 9, 6, 10, 2, 11] + - name: twelve_spikes + in: + slices: [1000, 1, 1, 1000, 1, 1, 1000, 1, 1, 1000, 1, 1] + - name: twelve_sparse_high + in: + slices: [1, 1, 1, 1, 500, 1, 1, 1, 1, 1, 1, 500] + - name: twelve_pattern + in: + slices: [3, 9, 2, 8, 1, 7, 4, 6, 5, 5, 4, 4] + - name: fifteen_increasing + in: + slices: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] + - name: fifteen_decreasing + in: + slices: [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + - name: fifteen_alternating + in: + slices: [90, 2, 90, 2, 90, 2, 90, 2, 90, 2, 90, 2, 90, 2, 90] + - name: fifteen_mixed + in: + slices: [11, 3, 17, 2, 8, 20, 4, 13, 6, 19, 1, 12, 7, 15, 5] + - name: eighteen_increasing + in: + slices: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18] + - name: eighteen_blocks + in: + slices: [100, 1, 1, 90, 2, 2, 80, 3, 3, 70, 4, 4, 60, 5, 5, 50, 6, 6] + - name: eighteen_edges + in: + slices: + [1000, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1000] + - name: twenty_one_pattern + in: + slices: + [2, 10, 3, 9, 4, 8, 5, 7, 6, 6, 7, 5, 8, 4, 9, 3, 10, 2, 11, 1, 12] + - name: twenty_four_increasing + in: + slices: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + ] + - name: twenty_four_spikes + in: + slices: + [ + 1000, + 1, + 1, + 1, + 1000, + 1, + 1, + 1, + 1000, + 1, + 1, + 1, + 1000, + 1, + 1, + 1, + 1000, + 1, + 1, + 1, + 1000, + 1, + 1, + 1, + ] + - name: twenty_four_mixed + in: + slices: + [ + 37, + 12, + 88, + 4, + 65, + 23, + 91, + 7, + 42, + 56, + 3, + 79, + 18, + 100, + 9, + 31, + 72, + 6, + 54, + 20, + 83, + 11, + 46, + 29, + ] + - name: twenty_seven_descending + in: + slices: + [ + 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: thirty_maximum + in: + slices: + [ + 1000, + 999, + 998, + 997, + 996, + 995, + 994, + 993, + 992, + 991, + 990, + 989, + 988, + 987, + 986, + 985, + 984, + 983, + 982, + 981, + 980, + 979, + 978, + 977, + 976, + 975, + 974, + 973, + 972, + 971, + ] + - name: thirty_alternating + in: + slices: + [ + 1000, + 1, + 999, + 2, + 998, + 3, + 997, + 4, + 996, + 5, + 995, + 6, + 994, + 7, + 993, + 8, + 992, + 9, + 991, + 10, + 990, + 11, + 989, + 12, + 988, + 13, + 987, + 14, + 986, + 15, + ] + - name: six_circular_conflict + in: + slices: [100, 90, 1, 1, 1, 90] + - name: twelve_boundary_choice + in: + slices: [500, 1, 2, 3, 500, 4, 5, 6, 500, 7, 8, 9] + - name: three_all_minimum + in: + slices: [1, 1, 1] + - name: six_all_maximum + in: + slices: [1000, 1000, 1000, 1000, 1000, 1000] + - name: nine_boundary_wave + in: + slices: [1, 1000, 1, 1000, 1, 1000, 1, 1000, 1] + - name: twelve_low_high_pairs + in: + slices: [1, 1000, 2, 999, 3, 998, 4, 997, 5, 996, 6, 995] + - name: fifteen_rotated_peak + in: + slices: [1, 2, 3, 1000, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] + - name: eighteen_repeated_ridges + in: + slices: + [1000, 1, 2, 3, 1000, 1, 2, 3, 1000, 1, 2, 3, 1000, 1, 2, 3, 1000, 1] + - name: twenty_one_endpoints + in: + slices: + [ + 1000, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 1000, + ] + - name: generated_minimum + in: + slices: + gen: "array" + len: 3 + of: + gen: "int" + min: 1 + max: 1000 + elemType: "int" + - name: generated_small + in: + slices: + gen: "array" + len: 30 + of: + gen: "int" + min: 1 + max: 1000 + elemType: "int" + - name: generated_medium + in: + slices: + gen: "array" + len: 90 + of: + gen: "int" + min: 1 + max: 1000 + elemType: "int" + - name: generated_near_maximum + in: + slices: + gen: "array" + len: 498 + of: + gen: "int" + min: 1 + max: 1000 + elemType: "int" + - name: generated_maximum + in: + slices: + gen: "array" + len: 495 + of: + gen: "int" + min: 1 + max: 1000 + elemType: "int" diff --git a/tests/1001-1500/1388. pizza-with-3n-slices/sol.cpp b/tests/1001-1500/1388. pizza-with-3n-slices/sol.cpp new file mode 100644 index 00000000..d2b75954 --- /dev/null +++ b/tests/1001-1500/1388. pizza-with-3n-slices/sol.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int maxSizeSlices(vector& slices) { + int n = slices.size(); + int m = n / 3; + return max(dp(slices, 0, n - 2, m), dp(slices, 1, n - 1, m)); + } + +private: + int dp(vector& slices, int start, int end, int m) { + int k = end - start + 1; + vector> dpTable(k + 1, vector(m + 1, 0)); + for (int i = 1; i <= k; i++) { + for (int j = 1; j <= min(i, m); j++) { + dpTable[i][j] = max(dpTable[i - 1][j], (i > 1 ? dpTable[i - 2][j - 1] : 0) + slices[start + i - 1]); + } + } + return dpTable[k][m]; + } +}; diff --git a/tests/1001-1500/1388. pizza-with-3n-slices/sol.cs b/tests/1001-1500/1388. pizza-with-3n-slices/sol.cs new file mode 100644 index 00000000..6dadbae6 --- /dev/null +++ b/tests/1001-1500/1388. pizza-with-3n-slices/sol.cs @@ -0,0 +1,18 @@ +public class Solution { + public int MaxSizeSlices(int[] slices) { + int n = slices.Length; + int m = n / 3; + return Math.Max(DP(slices, 0, n - 2, m), DP(slices, 1, n - 1, m)); + } + + private int DP(int[] slices, int start, int end, int m) { + int k = end - start + 1; + int[,] dpTable = new int[k + 1, m + 1]; + for (int i = 1; i <= k; i++) { + for (int j = 1; j <= Math.Min(i, m); j++) { + dpTable[i, j] = Math.Max(dpTable[i - 1, j], (i > 1 ? dpTable[i - 2, j - 1] : 0) + slices[start + i - 1]); + } + } + return dpTable[k, m]; + } +} diff --git a/tests/1001-1500/1388. pizza-with-3n-slices/sol.dart b/tests/1001-1500/1388. pizza-with-3n-slices/sol.dart new file mode 100644 index 00000000..a6f4b4aa --- /dev/null +++ b/tests/1001-1500/1388. pizza-with-3n-slices/sol.dart @@ -0,0 +1,22 @@ +class Solution { + int maxSizeSlices(List slices) { + int n = slices.length; + int m = n ~/ 3; + + int dp(List slicesSubset) { + int k = slicesSubset.length; + List> dpTable = List.generate(k + 1, (_) => List.filled(m + 1, 0)); + for (int i = 1; i <= k; i++) { + for (int j = 1; j <= (i < m ? i : m); j++) { + final take = (i > 1 ? dpTable[i - 2][j - 1] : 0) + slicesSubset[i - 1]; + dpTable[i][j] = max(dpTable[i - 1][j], take); + } + } + return dpTable[k][m]; + } + + return max(dp(slices.sublist(0, n - 1)), dp(slices.sublist(1))); + } + + int max(int a, int b) => a > b ? a : b; +} diff --git a/tests/1001-1500/1388. pizza-with-3n-slices/sol.go b/tests/1001-1500/1388. pizza-with-3n-slices/sol.go new file mode 100644 index 00000000..c453219f --- /dev/null +++ b/tests/1001-1500/1388. pizza-with-3n-slices/sol.go @@ -0,0 +1,36 @@ +func maxSizeSlices(slices []int) int { + n := len(slices) + m := n / 3 + + dp := func(slicesSubset []int) int { + k := len(slicesSubset) + dpTable := make([][]int, k+1) + for i := range dpTable { + dpTable[i] = make([]int, m+1) + } + for i := 1; i <= k; i++ { + for j := 1; j <= min(i, m); j++ { + take := slicesSubset[i-1] + if i > 1 { take += dpTable[i-2][j-1] } + dpTable[i][j] = max(dpTable[i-1][j], take) + } + } + return dpTable[k][m] + } + + return max(dp(slices[:n-1]), dp(slices[1:])) +} + +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/1001-1500/1388. pizza-with-3n-slices/sol.java b/tests/1001-1500/1388. pizza-with-3n-slices/sol.java new file mode 100644 index 00000000..2d2c09dd --- /dev/null +++ b/tests/1001-1500/1388. pizza-with-3n-slices/sol.java @@ -0,0 +1,18 @@ +class Solution { + public int maxSizeSlices(int[] slices) { + int n = slices.length; + int m = n / 3; + return Math.max(dp(slices, 0, n - 2, m), dp(slices, 1, n - 1, m)); + } + + private int dp(int[] slices, int start, int end, int m) { + int k = end - start + 1; + int[][] dp_table = new int[k + 1][m + 1]; + for (int i = 1; i <= k; i++) { + for (int j = 1; j <= Math.min(i, m); j++) { + dp_table[i][j] = Math.max(dp_table[i - 1][j], (i > 1 ? dp_table[i - 2][j - 1] : 0) + slices[start + i - 1]); + } + } + return dp_table[k][m]; + } +} diff --git a/tests/1001-1500/1388. pizza-with-3n-slices/sol.kt b/tests/1001-1500/1388. pizza-with-3n-slices/sol.kt new file mode 100644 index 00000000..28bf16df --- /dev/null +++ b/tests/1001-1500/1388. pizza-with-3n-slices/sol.kt @@ -0,0 +1,24 @@ +class Solution { + fun maxSizeSlices(slices: IntArray): Int { + val n = slices.size + val m = n / 3 + return maxOf( + dp(slices, 0, n - 2, m), + dp(slices, 1, n - 1, m) + ) + } + + private fun dp(slices: IntArray, start: Int, end: Int, m: Int): Int { + val k = end - start + 1 + val dpTable = Array(k + 1) { IntArray(m + 1) } + for (i in 1..k) { + for (j in 1..minOf(i, m)) { + dpTable[i][j] = maxOf( + dpTable[i - 1][j], + (if (i > 1) dpTable[i - 2][j - 1] else 0) + slices[start + i - 1] + ) + } + } + return dpTable[k][m] + } +} diff --git a/tests/1001-1500/1388. pizza-with-3n-slices/sol.py b/tests/1001-1500/1388. pizza-with-3n-slices/sol.py new file mode 100644 index 00000000..d7fd89be --- /dev/null +++ b/tests/1001-1500/1388. pizza-with-3n-slices/sol.py @@ -0,0 +1,26 @@ +from typing import List + + +class Solution: + def maxSizeSlices(self, slices: List[int]) -> int: + n = len(slices) # Total number of slices + m = n // 3 # Maximum slices we can take + + # Function to perform dynamic programming + def dp(slices_subset): + k = len(slices_subset) + # dp[i][j] = max sum using first i slices with j picks + dp_table = [[0] * (m + 1) for _ in range(k + 1)] + for i in range(1, k + 1): + for j in range(1, min(i, m) + 1): + # Choose current slice or skip it + take = (dp_table[i - 2][j - 1] if i > 1 else 0) + slices_subset[ + i - 1 + ] + dp_table[i][j] = max(dp_table[i - 1][j], take) + return dp_table[k][m] + + # We need to consider two scenarios due to the circular nature: + # 1. Including the first slice and excluding the last + # 2. Excluding the first slice and including the last + return max(dp(slices[:-1]), dp(slices[1:])) diff --git a/tests/1001-1500/1388. pizza-with-3n-slices/sol.py2 b/tests/1001-1500/1388. pizza-with-3n-slices/sol.py2 new file mode 100644 index 00000000..a2c9bb1c --- /dev/null +++ b/tests/1001-1500/1388. pizza-with-3n-slices/sol.py2 @@ -0,0 +1,19 @@ +class Solution(object): + def maxSizeSlices(self, slices): + """ + :type slices: List[int] + :rtype: int + """ + n = len(slices) + m = n // 3 + + def dp(slices_subset): + k = len(slices_subset) + dp_table = [[0] * (m + 1) for _ in range(k + 1)] + for i in range(1, k + 1): + for j in range(1, min(i, m) + 1): + take = (dp_table[i - 2][j - 1] if i > 1 else 0) + slices_subset[i - 1] + dp_table[i][j] = max(dp_table[i - 1][j], take) + return dp_table[k][m] + + return max(dp(slices[:-1]), dp(slices[1:])) diff --git a/tests/1001-1500/1388. pizza-with-3n-slices/sol.rb b/tests/1001-1500/1388. pizza-with-3n-slices/sol.rb new file mode 100644 index 00000000..d59bec8e --- /dev/null +++ b/tests/1001-1500/1388. pizza-with-3n-slices/sol.rb @@ -0,0 +1,20 @@ +# @param {Integer[]} slices +# @return {Integer} +def max_size_slices(slices) + n = slices.length + m = n / 3 + + dp = lambda do |slices_subset| + k = slices_subset.length + dp_table = Array.new(k + 1) { Array.new(m + 1, 0) } + (1..k).each do |i| + (1..[i, m].min).each do |j| + take = (i > 1 ? dp_table[i - 2][j - 1] : 0) + slices_subset[i - 1] + dp_table[i][j] = [dp_table[i - 1][j], take].max + end + end + dp_table[k][m] + end + + [dp.call(slices[0...-1]), dp.call(slices[1..-1])].max +end diff --git a/tests/1001-1500/1388. pizza-with-3n-slices/sol.rs b/tests/1001-1500/1388. pizza-with-3n-slices/sol.rs new file mode 100644 index 00000000..4e79a54d --- /dev/null +++ b/tests/1001-1500/1388. pizza-with-3n-slices/sol.rs @@ -0,0 +1,25 @@ +impl Solution { + pub fn max_size_slices(slices: Vec) -> i32 { + let n = slices.len(); + let m = n / 3; + + fn dp(slices_subset: &[i32], m: usize) -> i32 { + let k = slices_subset.len(); + let mut dp_table = vec![vec![0; m + 1]; k + 1]; + for i in 1..=k { + for j in 1..=std::cmp::min(i, m) { + dp_table[i][j] = std::cmp::max( + dp_table[i - 1][j], + (if i > 1 { dp_table[i - 2][j - 1] } else { 0 }) + slices_subset[i - 1], + ); + } + } + dp_table[k][m] + } + + std::cmp::max( + dp(&slices[..n - 1], m), + dp(&slices[1..], m), + ) + } +} diff --git a/tests/1001-1500/1388. pizza-with-3n-slices/sol.swift b/tests/1001-1500/1388. pizza-with-3n-slices/sol.swift new file mode 100644 index 00000000..6d9fe3c7 --- /dev/null +++ b/tests/1001-1500/1388. pizza-with-3n-slices/sol.swift @@ -0,0 +1,19 @@ +class Solution { + func maxSizeSlices(_ slices: [Int]) -> Int { + let n = slices.count + let m = n / 3 + + func dp(_ slicesSubset: [Int]) -> Int { + let k = slicesSubset.count + var dpTable = Array(repeating: Array(repeating: 0, count: m + 1), count: k + 1) + for i in 1...k { + for j in 1...min(i, m) { + dpTable[i][j] = max(dpTable[i - 1][j], (i > 1 ? dpTable[i - 2][j - 1] : 0) + slicesSubset[i - 1]) + } + } + return dpTable[k][m] + } + + return max(dp(Array(slices[0.. + Array(m + 1).fill(0), + ); + for (let i = 1; i <= k; i++) { + for (let j = 1; j <= Math.min(i, m); j++) { + dpTable[i][j] = Math.max( + dpTable[i - 1][j], + (i > 1 ? dpTable[i - 2][j - 1] : 0) + slicesSubset[i - 1], + ); + } + } + return dpTable[k][m]; + } + + return Math.max(dp(slices.slice(0, -1)), dp(slices.slice(1))); +} diff --git a/tests/1001-1500/1389. create-target-array-in-the-given-order/manifest.yaml b/tests/1001-1500/1389. create-target-array-in-the-given-order/manifest.yaml new file mode 100644 index 00000000..7d00cb24 --- /dev/null +++ b/tests/1001-1500/1389. create-target-array-in-the-given-order/manifest.yaml @@ -0,0 +1,471 @@ +entry: + id: 1389 + title: "create-target-array-in-the-given-order" + params: + nums: + type: array + items: + type: int + index: + type: array + items: + type: int + call: + cpp: "Solution().createTargetArray({nums}, {index})" + rust: "Solution::create_target_array({nums}, {index})" + python3: "Solution().createTargetArray({nums}, {index})" + python2: "Solution().createTargetArray({nums}, {index})" + ruby: "create_target_array({nums}, {index})" + java: "new Solution().createTargetArray({nums}, {index})" + csharp: "new Solution().CreateTargetArray({nums}, {index})" + kotlin: "Solution().createTargetArray({nums}, {index})" + go: "createTargetArray({nums}, {index})" + dart: "Solution().createTargetArray({nums}, {index})" + swift: "Solution().createTargetArray({nums}, {index})" + typescript: "createTargetArray({nums}, {index})" +judge: + type: exact +limits: + time_ms: 1000 + memory_mb: 256 +oracle: + python3: + call: "Checker().createTargetArray(nums, index, {result})" + checker: | + class Checker: + def createTargetArray(self, nums, index, result): + if not isinstance(nums, list) or not isinstance(index, list): + return False + if not 1 <= len(nums) <= 100 or len(nums) != len(index): + return False + for i, (value, position) in enumerate(zip(nums, index)): + if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 100: + return False + if isinstance(position, bool) or not isinstance(position, int) or not 0 <= position <= i: + return False + if not isinstance(result, list) or len(result) != len(nums): + return False + if any(isinstance(value, bool) or not isinstance(value, int) for value in result): + return False + remaining = list(result) + for i in range(len(nums) - 1, -1, -1): + position = index[i] + if position >= len(remaining) or remaining[position] != nums[i]: + return False + remaining.pop(position) + return not remaining +seed: 1389 +tests: + - name: "example_one" + in: + nums: [0, 1, 2, 3, 4] + index: [0, 1, 2, 2, 1] + - name: "example_two" + in: + nums: [1, 2, 3, 4, 0] + index: [0, 1, 2, 3, 0] + - name: "single_element" + in: + nums: [1] + index: [0] + - name: "single_zero" + in: + nums: [0] + index: [0] + - name: "two_front" + in: + nums: [1, 2] + index: [0, 0] + - name: "two_back" + in: + nums: [1, 2] + index: [0, 1] + - name: "three_front" + in: + nums: [1, 2, 3] + index: [0, 0, 0] + - name: "three_back" + in: + nums: [1, 2, 3] + index: [0, 1, 2] + - name: "three_middle" + in: + nums: [9, 4, 7] + index: [0, 1, 1] + - name: "duplicate_values" + in: + nums: [5, 5, 5, 5, 5] + index: [0, 1, 0, 2, 1] + - name: "all_zero_values" + in: + nums: [0, 0, 0, 0, 0] + index: [0, 0, 0, 0, 0] + - name: "maximum_values" + in: + nums: [100, 99, 98, 97] + index: [0, 1, 0, 2] + - name: "alternating_extremes" + in: + nums: [0, 100, 0, 100, 0, 100] + index: [0, 0, 2, 1, 3, 0] + - name: "front_inserts" + in: + nums: [4, 3, 2, 1, 0] + index: [0, 0, 0, 0, 0] + - name: "back_inserts" + in: + nums: [0, 1, 2, 3, 4, 5] + index: [0, 1, 2, 3, 4, 5] + - name: "mixed_six" + in: + nums: [10, 20, 30, 40, 50, 60] + index: [0, 1, 1, 3, 2, 4] + - name: "repeated_positions" + in: + nums: [5, 6, 7, 8, 9, 10] + index: [0, 0, 1, 1, 2, 2] + - name: "alternating_positions" + in: + nums: [1, 2, 3, 4, 5, 6, 7] + index: [0, 1, 0, 1, 0, 1, 0] + - name: "nested_middle" + in: + nums: [11, 22, 33, 44, 55, 66, 77] + index: [0, 1, 1, 2, 2, 3, 3] + - name: "reverse_values_mixed" + in: + nums: [7, 6, 5, 4, 3, 2, 1] + index: [0, 1, 0, 2, 1, 3, 2] + - name: "eight_front" + in: + nums: [8, 7, 6, 5, 4, 3, 2, 1] + index: [0, 0, 0, 0, 0, 0, 0, 0] + - name: "eight_back" + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8] + index: [0, 1, 2, 3, 4, 5, 6, 7] + - name: "eight_balanced" + in: + nums: [80, 10, 70, 20, 60, 30, 50, 40] + index: [0, 1, 0, 2, 1, 3, 2, 4] + - name: "nine_duplicates" + in: + nums: [1, 1, 2, 2, 3, 3, 4, 4, 5] + index: [0, 1, 0, 2, 1, 3, 2, 4, 3] + - name: "ten_pattern" + in: + nums: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + index: [0, 1, 0, 2, 1, 3, 2, 4, 3, 5] + - name: "ten_maximum" + in: + nums: [100, 100, 100, 100, 100, 100, 100, 100, 100, 100] + index: [0, 0, 1, 1, 2, 2, 3, 3, 4, 4] + - name: "eleven_staircase" + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] + index: [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5] + - name: "twelve_back" + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] + index: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] + - name: "twelve_front" + in: + nums: [12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + index: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - name: "thirteen_varied" + in: + nums: [13, 1, 12, 2, 11, 3, 10, 4, 9, 5, 8, 6, 7] + index: [0, 1, 1, 2, 0, 3, 2, 4, 3, 5, 4, 6, 5] + - name: "fifteen_mixed" + in: + nums: [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + index: [0, 1, 0, 2, 1, 3, 2, 4, 3, 5, 4, 6, 5, 7, 6] + - name: "twenty_boundary_values" + in: + nums: + [0, 100, 1, 99, 2, 98, 3, 97, 4, 96, 5, 95, 6, 94, 7, 93, 8, 92, 9, 91] + index: [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9] + - name: "twenty_five_front_loaded" + in: + nums: + [ + 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, + ] + index: + [ + 0, + 0, + 1, + 0, + 2, + 1, + 3, + 2, + 4, + 3, + 5, + 4, + 6, + 5, + 7, + 6, + 8, + 7, + 9, + 8, + 10, + 9, + 11, + 10, + 12, + ] + - name: "thirty_all_same" + in: + nums: + [ + 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, + ] + index: + [ + 0, + 1, + 0, + 2, + 1, + 3, + 2, + 4, + 3, + 5, + 4, + 6, + 5, + 7, + 6, + 8, + 7, + 9, + 8, + 10, + 9, + 11, + 10, + 12, + 11, + 13, + 12, + 14, + 13, + 15, + ] + - name: "thirty_five_mixed" + in: + nums: + [ + 0, + 100, + 50, + 25, + 75, + 1, + 99, + 49, + 51, + 2, + 98, + 48, + 52, + 3, + 97, + 47, + 53, + 4, + 96, + 46, + 54, + 5, + 95, + 45, + 55, + 6, + 94, + 44, + 56, + 7, + 93, + 43, + 57, + 8, + 92, + ] + index: + [ + 0, + 0, + 1, + 1, + 2, + 0, + 3, + 2, + 4, + 1, + 5, + 3, + 6, + 2, + 7, + 4, + 8, + 3, + 9, + 5, + 10, + 4, + 11, + 6, + 12, + 5, + 13, + 7, + 14, + 6, + 15, + 8, + 16, + 7, + 17, + ] + - name: "generated_length_one" + in: + nums: + gen: "array" + len: 1 + of: + gen: "int" + min: 0 + max: 100 + index: + gen: "array" + len: 1 + of: + gen: "int" + min: 0 + max: 0 + - name: "generated_small_front" + in: + nums: + gen: "array" + len: 7 + of: + gen: "int" + min: 0 + max: 100 + index: + gen: "array" + len: 7 + of: + gen: "int" + min: 0 + max: 0 + - name: "generated_medium_front" + in: + nums: + gen: "array" + len: 25 + of: + gen: "int" + min: 0 + max: 100 + index: + gen: "array" + len: 25 + of: + gen: "int" + min: 0 + max: 0 + - name: "generated_large_front" + in: + nums: + gen: "array" + len: 75 + of: + gen: "int" + min: 0 + max: 100 + index: + gen: "array" + len: 75 + of: + gen: "int" + min: 0 + max: 0 + - name: "generated_maximum_front" + in: + nums: + gen: "array" + len: 100 + of: + gen: "int" + min: 0 + max: 100 + index: + gen: "array" + len: 100 + of: + gen: "int" + min: 0 + max: 0 diff --git a/tests/1001-1500/1389. create-target-array-in-the-given-order/sol.cpp b/tests/1001-1500/1389. create-target-array-in-the-given-order/sol.cpp new file mode 100644 index 00000000..3f53685c --- /dev/null +++ b/tests/1001-1500/1389. create-target-array-in-the-given-order/sol.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + vector createTargetArray(vector& nums, vector& index) { + vector target; + for (int i = 0; i < nums.size(); i++) { + target.insert(target.begin() + index[i], nums[i]); + } + return target; + } +}; diff --git a/tests/1001-1500/1389. create-target-array-in-the-given-order/sol.cs b/tests/1001-1500/1389. create-target-array-in-the-given-order/sol.cs new file mode 100644 index 00000000..f04d34a6 --- /dev/null +++ b/tests/1001-1500/1389. create-target-array-in-the-given-order/sol.cs @@ -0,0 +1,9 @@ +public class Solution { + public int[] CreateTargetArray(int[] nums, int[] index) { + List target = new List(); + for (int i = 0; i < nums.Length; i++) { + target.Insert(index[i], nums[i]); + } + return target.ToArray(); + } +} diff --git a/tests/1001-1500/1389. create-target-array-in-the-given-order/sol.dart b/tests/1001-1500/1389. create-target-array-in-the-given-order/sol.dart new file mode 100644 index 00000000..09d168c5 --- /dev/null +++ b/tests/1001-1500/1389. create-target-array-in-the-given-order/sol.dart @@ -0,0 +1,9 @@ +class Solution { + List createTargetArray(List nums, List index) { + List target = []; + for (int i = 0; i < nums.length; i++) { + target.insert(index[i], nums[i]); + } + return target; + } +} diff --git a/tests/1001-1500/1389. create-target-array-in-the-given-order/sol.go b/tests/1001-1500/1389. create-target-array-in-the-given-order/sol.go new file mode 100644 index 00000000..a57796cb --- /dev/null +++ b/tests/1001-1500/1389. create-target-array-in-the-given-order/sol.go @@ -0,0 +1,9 @@ +func createTargetArray(nums []int, index []int) []int { + target := make([]int, 0, len(nums)) + for i := 0; i < len(nums); i++ { + target = append(target, 0) + copy(target[index[i]+1:], target[index[i]:]) + target[index[i]] = nums[i] + } + return target +} diff --git a/tests/1001-1500/1389. create-target-array-in-the-given-order/sol.java b/tests/1001-1500/1389. create-target-array-in-the-given-order/sol.java new file mode 100644 index 00000000..736346b0 --- /dev/null +++ b/tests/1001-1500/1389. create-target-array-in-the-given-order/sol.java @@ -0,0 +1,13 @@ +class Solution { + public int[] createTargetArray(int[] nums, int[] index) { + List target = new ArrayList<>(); + for (int i = 0; i < nums.length; i++) { + target.add(index[i], nums[i]); + } + int[] result = new int[nums.length]; + for (int i = 0; i < nums.length; i++) { + result[i] = target.get(i); + } + return result; + } +} diff --git a/tests/1001-1500/1389. create-target-array-in-the-given-order/sol.kt b/tests/1001-1500/1389. create-target-array-in-the-given-order/sol.kt new file mode 100644 index 00000000..8e185b0c --- /dev/null +++ b/tests/1001-1500/1389. create-target-array-in-the-given-order/sol.kt @@ -0,0 +1,9 @@ +class Solution { + fun createTargetArray(nums: IntArray, index: IntArray): IntArray { + val target = mutableListOf() + for (i in nums.indices) { + target.add(index[i], nums[i]) + } + return target.toIntArray() + } +} diff --git a/tests/1001-1500/1389. create-target-array-in-the-given-order/sol.py b/tests/1001-1500/1389. create-target-array-in-the-given-order/sol.py new file mode 100644 index 00000000..95e126b2 --- /dev/null +++ b/tests/1001-1500/1389. create-target-array-in-the-given-order/sol.py @@ -0,0 +1,9 @@ +from typing import List + + +class Solution: + def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]: + target = [] + for i in range(len(nums)): + target.insert(index[i], nums[i]) + return target diff --git a/tests/1001-1500/1389. create-target-array-in-the-given-order/sol.py2 b/tests/1001-1500/1389. create-target-array-in-the-given-order/sol.py2 new file mode 100644 index 00000000..a53d71ef --- /dev/null +++ b/tests/1001-1500/1389. create-target-array-in-the-given-order/sol.py2 @@ -0,0 +1,11 @@ +class Solution(object): + def createTargetArray(self, nums, index): + """ + :type nums: List[int] + :type index: List[int] + :rtype: List[int] + """ + target = [] + for i in range(len(nums)): + target.insert(index[i], nums[i]) + return target diff --git a/tests/1001-1500/1389. create-target-array-in-the-given-order/sol.rb b/tests/1001-1500/1389. create-target-array-in-the-given-order/sol.rb new file mode 100644 index 00000000..bb83e1c7 --- /dev/null +++ b/tests/1001-1500/1389. create-target-array-in-the-given-order/sol.rb @@ -0,0 +1,10 @@ +# @param {Integer[]} nums +# @param {Integer[]} index +# @return {Integer[]} +def create_target_array(nums, index) + target = [] + nums.each_with_index do |num, i| + target.insert(index[i], num) + end + target +end diff --git a/tests/1001-1500/1389. create-target-array-in-the-given-order/sol.rs b/tests/1001-1500/1389. create-target-array-in-the-given-order/sol.rs new file mode 100644 index 00000000..3c2a71ad --- /dev/null +++ b/tests/1001-1500/1389. create-target-array-in-the-given-order/sol.rs @@ -0,0 +1,9 @@ +impl Solution { + pub fn create_target_array(nums: Vec, index: Vec) -> Vec { + let mut target = Vec::new(); + for i in 0..nums.len() { + target.insert(index[i] as usize, nums[i]); + } + target + } +} diff --git a/tests/1001-1500/1389. create-target-array-in-the-given-order/sol.swift b/tests/1001-1500/1389. create-target-array-in-the-given-order/sol.swift new file mode 100644 index 00000000..f78a6f58 --- /dev/null +++ b/tests/1001-1500/1389. create-target-array-in-the-given-order/sol.swift @@ -0,0 +1,9 @@ +class Solution { + func createTargetArray(_ nums: [Int], _ index: [Int]) -> [Int] { + var target: [Int] = [] + for i in 0..& nums) { + if (nums.empty()) return 0; + int maxNum = *max_element(nums.begin(), nums.end()); + if (maxNum < 2) return 0; + + vector sieve(maxNum + 1, true); + if (maxNum >= 0) sieve[0] = false; + if (maxNum >= 1) sieve[1] = false; + + for (int p = 2; p * p <= maxNum; ++p) { + if (sieve[p]) { + for (int multiple = p * p; multiple <= maxNum; multiple += p) { + sieve[multiple] = false; + } + } + } + + int total = 0; + for (int x : nums) { + // p^3 case + int p = round(pow(x, 1.0 / 3)); + if (p >= 0 && p <= maxNum && p * p * p == x && sieve[p]) { + total += 1 + p + p * p + x; + continue; + } + + // p * q case + for (int i = 2; i * i <= x; ++i) { + if (x % i == 0) { + int j = x / i; + if (i != j && i <= maxNum && j <= maxNum && sieve[i] && sieve[j]) { + total += 1 + i + j + x; + } + break; + } + } + } + return total; + } +}; diff --git a/tests/1001-1500/1390. four-divisors/sol.cs b/tests/1001-1500/1390. four-divisors/sol.cs new file mode 100644 index 00000000..27d2af9e --- /dev/null +++ b/tests/1001-1500/1390. four-divisors/sol.cs @@ -0,0 +1,41 @@ +public class Solution { + public int SumFourDivisors(int[] nums) { + if (nums.Length == 0) return 0; + int maxNum = 0; + foreach (int num in nums) if (num > maxNum) maxNum = num; + if (maxNum < 2) return 0; + + bool[] sieve = new bool[maxNum + 1]; + for (int i = 2; i <= maxNum; i++) sieve[i] = true; + + for (int p = 2; p * p <= maxNum; p++) { + if (sieve[p]) { + for (int multiple = p * p; multiple <= maxNum; multiple += p) { + sieve[multiple] = false; + } + } + } + + int total = 0; + foreach (int x in nums) { + // p^3 case + int p = (int)Math.Round(Math.Pow(x, 1.0 / 3)); + if (p >= 0 && p <= maxNum && p * p * p == x && sieve[p]) { + total += 1 + p + p * p + x; + continue; + } + + // p * q case + for (int i = 2; i * i <= x; i++) { + if (x % i == 0) { + int j = x / i; + if (i != j && i <= maxNum && j <= maxNum && sieve[i] && sieve[j]) { + total += 1 + i + j + x; + } + break; + } + } + } + return total; + } +} diff --git a/tests/1001-1500/1390. four-divisors/sol.dart b/tests/1001-1500/1390. four-divisors/sol.dart new file mode 100644 index 00000000..9e8521b8 --- /dev/null +++ b/tests/1001-1500/1390. four-divisors/sol.dart @@ -0,0 +1,43 @@ +import 'dart:math' as math; + +class Solution { + int sumFourDivisors(List nums) { + if (nums.isEmpty) return 0; + int maxNum = nums.reduce((a, b) => a > b ? a : b); + if (maxNum < 2) return 0; + + List sieve = List.filled(maxNum + 1, true); + if (maxNum >= 0) sieve[0] = false; + if (maxNum >= 1) sieve[1] = false; + + for (int p = 2; p * p <= maxNum; p++) { + if (sieve[p]) { + for (int multiple = p * p; multiple <= maxNum; multiple += p) { + sieve[multiple] = false; + } + } + } + + int total = 0; + for (int x in nums) { + // p^3 case + int p = math.pow(x.toDouble(), 1.0 / 3).round(); + if (p >= 0 && p <= maxNum && p * p * p == x && sieve[p]) { + total += 1 + p + p * p + x; + continue; + } + + // p * q case + for (int i = 2; i * i <= x; i++) { + if (x % i == 0) { + int j = x ~/ i; + if (i != j && i <= maxNum && j <= maxNum && sieve[i] && sieve[j]) { + total += 1 + i + j + x; + } + break; + } + } + } + return total; + } +} diff --git a/tests/1001-1500/1390. four-divisors/sol.go b/tests/1001-1500/1390. four-divisors/sol.go new file mode 100644 index 00000000..470bd71f --- /dev/null +++ b/tests/1001-1500/1390. four-divisors/sol.go @@ -0,0 +1,49 @@ +func sumFourDivisors(nums []int) int { + if len(nums) == 0 { + return 0 + } + maxNum := nums[0] + for _, num := range nums { + if num > maxNum { + maxNum = num + } + } + if maxNum < 2 { + return 0 + } + + sieve := make([]bool, maxNum+1) + for i := 2; i <= maxNum; i++ { + sieve[i] = true + } + + for p := 2; p*p <= maxNum; p++ { + if sieve[p] { + for multiple := p * p; multiple <= maxNum; multiple += p { + sieve[multiple] = false + } + } + } + + total := 0 + for _, x := range nums { + // p^3 case + p := int(math.Round(math.Pow(float64(x), 1.0/3.0))) + if p >= 0 && p <= maxNum && p*p*p == x && sieve[p] { + total += 1 + p + p*p + x + continue + } + + // p * q case + for i := 2; i*i <= x; i++ { + if x%i == 0 { + j := x / i + if i != j && i <= maxNum && j <= maxNum && sieve[i] && sieve[j] { + total += 1 + i + j + x + } + break + } + } + } + return total +} diff --git a/tests/1001-1500/1390. four-divisors/sol.java b/tests/1001-1500/1390. four-divisors/sol.java new file mode 100644 index 00000000..fa8885fc --- /dev/null +++ b/tests/1001-1500/1390. four-divisors/sol.java @@ -0,0 +1,41 @@ +class Solution { + public int sumFourDivisors(int[] nums) { + if (nums.length == 0) return 0; + int maxNum = 0; + for (int num : nums) if (num > maxNum) maxNum = num; + if (maxNum < 2) return 0; + + boolean[] sieve = new boolean[maxNum + 1]; + for (int i = 2; i <= maxNum; i++) sieve[i] = true; + + for (int p = 2; p * p <= maxNum; p++) { + if (sieve[p]) { + for (int multiple = p * p; multiple <= maxNum; multiple += p) { + sieve[multiple] = false; + } + } + } + + int total = 0; + for (int x : nums) { + // p^3 case + int p = (int) Math.round(Math.pow(x, 1.0 / 3)); + if (p >= 0 && p <= maxNum && p * p * p == x && sieve[p]) { + total += 1 + p + p * p + x; + continue; + } + + // p * q case + for (int i = 2; i * i <= x; i++) { + if (x % i == 0) { + int j = x / i; + if (i != j && i <= maxNum && j <= maxNum && sieve[i] && sieve[j]) { + total += 1 + i + j + x; + } + break; + } + } + } + return total; + } +} diff --git a/tests/1001-1500/1390. four-divisors/sol.kt b/tests/1001-1500/1390. four-divisors/sol.kt new file mode 100644 index 00000000..94014f94 --- /dev/null +++ b/tests/1001-1500/1390. four-divisors/sol.kt @@ -0,0 +1,47 @@ +class Solution { + fun sumFourDivisors(nums: IntArray): Int { + if (nums.isEmpty()) return 0 + val maxNum = nums.max() + if (maxNum < 2) return 0 + + val sieve = BooleanArray(maxNum + 1) { true } + if (maxNum >= 0) sieve[0] = false + if (maxNum >= 1) sieve[1] = false + + var p = 2 + while (p * p <= maxNum) { + if (sieve[p]) { + var multiple = p * p + while (multiple <= maxNum) { + sieve[multiple] = false + multiple += p + } + } + p++ + } + + var total = 0 + for (x in nums) { + // p^3 case + val p3 = Math.round(Math.pow(x.toDouble(), 1.0 / 3)).toInt() + if (p3 >= 0 && p3 <= maxNum && p3 * p3 * p3 == x && sieve[p3]) { + total += 1 + p3 + p3 * p3 + x + continue + } + + // p * q case + var i = 2 + while (i * i <= x) { + if (x % i == 0) { + val j = x / i + if (i != j && i <= maxNum && j <= maxNum && sieve[i] && sieve[j]) { + total += 1 + i + j + x + } + break + } + i++ + } + } + return total + } +} diff --git a/tests/1001-1500/1390. four-divisors/sol.py b/tests/1001-1500/1390. four-divisors/sol.py new file mode 100644 index 00000000..6a06d3c3 --- /dev/null +++ b/tests/1001-1500/1390. four-divisors/sol.py @@ -0,0 +1,51 @@ +from typing import List +import math + + +class Solution: + def build_sieve(self, n: int): + sieve = [True] * (n + 1) + if n >= 0: + sieve[0] = False + if n >= 1: + sieve[1] = False + p = 2 + while p * p <= n: + if sieve[p]: + for multiple in range(p * p, n + 1, p): + sieve[multiple] = False + p += 1 + return sieve + + def sumFourDivisors(self, nums: List[int]) -> int: + if not nums: + return 0 + max_num = max(nums) + if max_num < 2: + return 0 + sieve = self.build_sieve(max_num) + + total = 0 + for x in nums: + # p^3 case + p = round(x ** (1 / 3)) + if p >= 0 and p <= max_num and p**3 == x and sieve[p]: + total += 1 + p + p * p + x + continue + + # p * q case + i = 2 + while i * i <= x: + if x % i == 0: + j = x // i + if ( + i != j + and i <= max_num + and j <= max_num + and sieve[i] + and sieve[j] + ): + total += 1 + i + j + x + break + i += 1 + return total diff --git a/tests/1001-1500/1390. four-divisors/sol.py2 b/tests/1001-1500/1390. four-divisors/sol.py2 new file mode 100644 index 00000000..217c430f --- /dev/null +++ b/tests/1001-1500/1390. four-divisors/sol.py2 @@ -0,0 +1,42 @@ +class Solution(object): + def sumFourDivisors(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + if not nums: + return 0 + max_num = max(nums) + if max_num < 2: + return 0 + + sieve = [True] * (max_num + 1) + if max_num >= 0: + sieve[0] = False + if max_num >= 1: + sieve[1] = False + p = 2 + while p * p <= max_num: + if sieve[p]: + for multiple in range(p * p, max_num + 1, p): + sieve[multiple] = False + p += 1 + + total = 0 + for x in nums: + # p^3 case + p = int(round(x ** (1.0/3))) + if p >= 0 and p <= max_num and p * p * p == x and sieve[p]: + total += 1 + p + p * p + x + continue + + # p * q case + i = 2 + while i * i <= x: + if x % i == 0: + j = x // i + if i != j and i <= max_num and j <= max_num and sieve[i] and sieve[j]: + total += 1 + i + j + x + break + i += 1 + return total diff --git a/tests/1001-1500/1390. four-divisors/sol.rb b/tests/1001-1500/1390. four-divisors/sol.rb new file mode 100644 index 00000000..b5dd27f9 --- /dev/null +++ b/tests/1001-1500/1390. four-divisors/sol.rb @@ -0,0 +1,47 @@ +# @param {Integer[]} nums +# @return {Integer} +def sum_four_divisors(nums) + return 0 if nums.empty? + max_num = nums.max + return 0 if max_num < 2 + + sieve = Array.new(max_num + 1, true) + sieve[0] = false if max_num >= 0 + sieve[1] = false if max_num >= 1 + + p = 2 + while p * p <= max_num + if sieve[p] + multiple = p * p + while multiple <= max_num + sieve[multiple] = false + multiple += p + end + end + p += 1 + end + + total = 0 + nums.each do |x| + # p^3 case + p = (x ** (1.0/3)).round + if p >= 0 && p <= max_num && p * p * p == x && sieve[p] + total += 1 + p + p * p + x + next + end + + # p * q case + i = 2 + while i * i <= x + if x % i == 0 + j = x / i + if i != j && i <= max_num && j <= max_num && sieve[i] && sieve[j] + total += 1 + i + j + x + end + break + end + i += 1 + end + end + total +end diff --git a/tests/1001-1500/1390. four-divisors/sol.rs b/tests/1001-1500/1390. four-divisors/sol.rs new file mode 100644 index 00000000..6b17ce09 --- /dev/null +++ b/tests/1001-1500/1390. four-divisors/sol.rs @@ -0,0 +1,56 @@ +impl Solution { + pub fn sum_four_divisors(nums: Vec) -> i32 { + if nums.is_empty() { + return 0; + } + let max_num = *nums.iter().max().unwrap() as usize; + if max_num < 2 { + return 0; + } + + let mut sieve = vec![true; max_num + 1]; + if max_num >= 0 { + sieve[0] = false; + } + if max_num >= 1 { + sieve[1] = false; + } + + let mut p = 2; + while p * p <= max_num { + if sieve[p] { + let mut multiple = p * p; + while multiple <= max_num { + sieve[multiple] = false; + multiple += p; + } + } + p += 1; + } + + let mut total = 0; + for &x in &nums { + let x = x as i64; + // p^3 case + let p = (x as f64).cbrt().round() as i64; + if p >= 0 && p <= max_num as i64 && p * p * p == x && sieve[p as usize] { + total += (1 + p + p * p + x) as i32; + continue; + } + + // p * q case + let mut i = 2i64; + while i * i <= x { + if x % i == 0 { + let j = x / i; + if i != j && i <= max_num as i64 && j <= max_num as i64 && sieve[i as usize] && sieve[j as usize] { + total += (1 + i + j + x) as i32; + } + break; + } + i += 1; + } + } + total + } +} diff --git a/tests/1001-1500/1390. four-divisors/sol.swift b/tests/1001-1500/1390. four-divisors/sol.swift new file mode 100644 index 00000000..a33b2750 --- /dev/null +++ b/tests/1001-1500/1390. four-divisors/sol.swift @@ -0,0 +1,47 @@ +class Solution { + func sumFourDivisors(_ nums: [Int]) -> Int { + if nums.isEmpty { return 0 } + let maxNum = nums.max()! + if maxNum < 2 { return 0 } + + var sieve = [Bool](repeating: true, count: maxNum + 1) + if maxNum >= 0 { sieve[0] = false } + if maxNum >= 1 { sieve[1] = false } + + var p = 2 + while p * p <= maxNum { + if sieve[p] { + var multiple = p * p + while multiple <= maxNum { + sieve[multiple] = false + multiple += p + } + } + p += 1 + } + + var total = 0 + for x in nums { + // p^3 case + let p = Int(round(pow(Double(x), 1.0/3.0))) + if p >= 0 && p <= maxNum && p * p * p == x && sieve[p] { + total += 1 + p + p * p + x + continue + } + + // p * q case + var i = 2 + while i * i <= x { + if x % i == 0 { + let j = x / i + if i != j && i <= maxNum && j <= maxNum && sieve[i] && sieve[j] { + total += 1 + i + j + x + } + break + } + i += 1 + } + } + return total + } +} diff --git a/tests/1001-1500/1390. four-divisors/sol.ts b/tests/1001-1500/1390. four-divisors/sol.ts new file mode 100644 index 00000000..54af519f --- /dev/null +++ b/tests/1001-1500/1390. four-divisors/sol.ts @@ -0,0 +1,39 @@ +function sumFourDivisors(nums: number[]): number { + if (nums.length === 0) return 0; + const maxNum = Math.max(...nums); + if (maxNum < 2) return 0; + + const sieve: boolean[] = new Array(maxNum + 1).fill(true); + if (maxNum >= 0) sieve[0] = false; + if (maxNum >= 1) sieve[1] = false; + + for (let p = 2; p * p <= maxNum; p++) { + if (sieve[p]) { + for (let multiple = p * p; multiple <= maxNum; multiple += p) { + sieve[multiple] = false; + } + } + } + + let total = 0; + for (const x of nums) { + // p^3 case + const p = Math.round(Math.pow(x, 1 / 3)); + if (p >= 0 && p <= maxNum && p * p * p === x && sieve[p]) { + total += 1 + p + p * p + x; + continue; + } + + // p * q case + for (let i = 2; i * i <= x; i++) { + if (x % i === 0) { + const j = Math.floor(x / i); + if (i !== j && i <= maxNum && j <= maxNum && sieve[i] && sieve[j]) { + total += 1 + i + j + x; + } + break; + } + } + } + return total; +} diff --git a/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/manifest.yaml b/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/manifest.yaml new file mode 100644 index 00000000..adbe480a --- /dev/null +++ b/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/manifest.yaml @@ -0,0 +1,422 @@ +entry: + id: 1391 + title: "check-if-there-is-a-valid-path-in-a-grid" + params: + grid: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().hasValidPath({grid})" + rust: "Solution::has_valid_path({grid})" + python3: "Solution().hasValidPath({grid})" + python2: "Solution().hasValidPath({grid})" + ruby: "has_valid_path({grid})" + java: "new Solution().hasValidPath({grid})" + csharp: "new Solution().HasValidPath({grid})" + kotlin: "Solution().hasValidPath({grid})" + go: "hasValidPath({grid})" + dart: "Solution().hasValidPath({grid})" + swift: "Solution().hasValidPath({grid})" + typescript: "hasValidPath({grid})" + +judge: + type: "exact" + +limits: + time_ms: 500 + memory_mb: 400 + +oracle: + python3: + call: "Checker().hasValidPath(grid, {result})" + checker: | + class Checker: + def hasValidPath(self, grid, result): + if not isinstance(result, bool): + return False + dirs = { + 1: ((0, -1), (0, 1)), + 2: ((-1, 0), (1, 0)), + 3: ((0, -1), (1, 0)), + 4: ((0, 1), (1, 0)), + 5: ((0, -1), (-1, 0)), + 6: ((0, 1), (-1, 0)), + } + m, n = len(grid), len(grid[0]) + seen = {(0, 0)} + queue = [(0, 0)] + for r, c in queue: + for dr, dc in dirs[grid[r][c]]: + nr, nc = r + dr, c + dc + if not (0 <= nr < m and 0 <= nc < n) or (nr, nc) in seen: + continue + if any(nr + bdr == r and nc + bdc == c for bdr, bdc in dirs[grid[nr][nc]]): + seen.add((nr, nc)) + queue.append((nr, nc)) + return result == ((m - 1, n - 1) in seen) + +seed: 1391001 + +tests: + - name: "example_1" + in: + grid: + elemType: "int" + value: + - [2, 4, 3] + - [6, 5, 2] + out: true + - name: "example_2" + in: + grid: + elemType: "int" + value: + - [1, 2, 1] + - [1, 2, 1] + out: false + - name: "example_3" + in: + grid: + elemType: "int" + value: + - [1, 1, 2] + out: false + - name: "single_cell_1" + in: + grid: + elemType: "int" + value: + - [1] + out: true + - name: "single_cell_6" + in: + grid: + elemType: "int" + value: + - [6] + out: true + - name: "horizontal_valid" + in: + grid: + elemType: "int" + value: + - [1, 1, 1, 1] + out: true + - name: "horizontal_broken" + in: + grid: + elemType: "int" + value: + - [1, 2, 1, 1] + out: false + - name: "vertical_valid" + in: + grid: + elemType: "int" + value: + - [2] + - [2] + - [2] + out: true + - name: "vertical_broken" + in: + grid: + elemType: "int" + value: + - [2] + - [1] + - [2] + out: false + - name: "two_by_two_valid" + in: + grid: + elemType: "int" + value: + - [4, 3] + - [6, 5] + out: true + - name: "two_by_two_dead_end" + in: + grid: + elemType: "int" + value: + - [4, 1] + - [2, 5] + out: false + - name: "turning_path" + in: + grid: + elemType: "int" + value: + - [4, 3, 4] + - [1, 2, 3] + - [1, 2, 2] + out: false + - name: "wrong_entry_connector" + in: + grid: + elemType: "int" + value: + - [4, 1] + - [6, 5] + out: true + - name: "left_down_path" + in: + grid: + elemType: "int" + value: + - [3, 3, 4] + - [1, 2, 3] + - [1, 1, 1] + out: false + - name: "right_up_trap" + in: + grid: + elemType: "int" + value: + - [4, 5, 2] + - [1, 6, 3] + out: false + - name: "all_horizontal_rows" + in: + grid: + elemType: "int" + value: + - [1, 1, 1] + - [1, 1, 1] + out: false + - name: "all_vertical_columns" + in: + grid: + elemType: "int" + value: + - [2, 2] + - [2, 2] + out: false + - name: "closed_loop" + in: + grid: + elemType: "int" + value: + - [4, 3, 3, 4] + - [6, 1, 1, 5] + - [6, 1, 1, 5] + - [2, 4, 3, 2] + out: false + - name: "loop_not_target" + in: + grid: + elemType: "int" + value: + - [4, 3, 4] + - [6, 1, 5] + - [2, 4, 3] + out: false + - name: "three_by_three_valid" + in: + grid: + elemType: "int" + value: + - [2, 4, 3] + - [2, 2, 5] + - [2, 4, 3] + out: false + - name: "three_by_three_invalid" + in: + grid: + elemType: "int" + value: + - [2, 4, 3] + - [6, 1, 5] + - [2, 4, 3] + out: false + - name: "start_points_up" + in: + grid: + elemType: "int" + value: + - [5, 1] + - [2, 4] + out: false + - name: "start_points_left" + in: + grid: + elemType: "int" + value: + - [5, 1] + - [2, 3] + out: false + - name: "target_points_right" + in: + grid: + elemType: "int" + value: + - [4, 3] + - [1, 1] + out: false + - name: "target_points_down" + in: + grid: + elemType: "int" + value: + - [2, 4] + - [2, 5] + out: false + - name: "mixed_four_by_four" + in: + grid: + elemType: "int" + value: + - [2, 4, 3, 4] + - [2, 2, 5, 5] + - [2, 4, 3, 4] + - [2, 2, 5, 5] + out: false + - name: "isolated_start" + in: + grid: + elemType: "int" + value: + - [1, 5] + - [2, 4] + out: false + - name: "isolated_target" + in: + grid: + elemType: "int" + value: + - [4, 3] + - [1, 2] + out: true + - name: "all_type_three" + in: + grid: + elemType: "int" + value: + - [3, 3, 3] + - [3, 3, 3] + out: false + - name: "all_type_four" + in: + grid: + elemType: "int" + value: + - [4, 4] + - [4, 4] + out: false + - name: "all_type_five" + in: + grid: + elemType: "int" + value: + - [5, 5] + - [5, 5] + out: false + - name: "all_type_six" + in: + grid: + elemType: "int" + value: + - [6, 6] + - [6, 6] + out: false + - name: "wide_valid_corridor" + in: + grid: + elemType: "int" + value: + - [1, 1, 1, 1, 1, 1, 1, 1] + out: true + - name: "wide_broken_corridor" + in: + grid: + elemType: "int" + value: + - [1, 1, 1, 2, 1, 1, 1, 1] + out: false + - name: "tall_valid_corridor" + in: + grid: + elemType: "int" + value: + - [2] + - [2] + - [2] + - [2] + - [2] + - [2] + out: true + - name: "generated_small" + seed: 139101 + in: + grid: + gen: "array" + len: + gen: "int" + min: 1 + max: 5 + of: + gen: "array" + len: + gen: "int" + min: 1 + max: 5 + of: + gen: "int" + min: 1 + max: 6 + - name: "generated_medium" + seed: 139102 + in: + grid: + gen: "array" + len: 8 + of: + gen: "array" + len: 9 + of: + gen: "int" + min: 1 + max: 6 + - name: "generated_rectangular" + seed: 139103 + in: + grid: + gen: "array" + len: 12 + of: + gen: "array" + len: 4 + of: + gen: "int" + min: 1 + max: 6 + - name: "generated_large_square" + seed: 139104 + in: + grid: + gen: "array" + len: 40 + of: + gen: "array" + len: 40 + of: + gen: "int" + min: 1 + max: 6 + - name: "generated_large_rectangle" + seed: 139105 + in: + grid: + gen: "array" + len: 60 + of: + gen: "array" + len: 30 + of: + gen: "int" + min: 1 + max: 6 diff --git a/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.cpp b/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.cpp new file mode 100644 index 00000000..a0170fa5 --- /dev/null +++ b/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.cpp @@ -0,0 +1,47 @@ +class Solution { +public: + bool hasValidPath(vector>& grid) { + int m = grid.size(); + int n = grid[0].size(); + + unordered_map>> dir; + dir[1] = {{0, -1}, {0, 1}}; + dir[2] = {{-1, 0}, {1, 0}}; + dir[3] = {{0, -1}, {1, 0}}; + dir[4] = {{0, 1}, {1, 0}}; + dir[5] = {{0, -1}, {-1, 0}}; + dir[6] = {{0, 1}, {-1, 0}}; + + vector> vis(m, vector(n, false)); + queue> q; + q.push({0, 0}); + vis[0][0] = true; + + while (!q.empty()) { + auto [r, c] = q.front(); + q.pop(); + + if (r == m - 1 && c == n - 1) { + return true; + } + + for (auto& [dr, dc] : dir[grid[r][c]]) { + int nr = r + dr; + int nc = c + dc; + + if (nr < 0 || nc < 0 || nr >= m || nc >= n || vis[nr][nc]) { + continue; + } + + for (auto& [bdr, bdc] : dir[grid[nr][nc]]) { + if (nr + bdr == r && nc + bdc == c) { + vis[nr][nc] = true; + q.push({nr, nc}); + } + } + } + } + + return false; + } +}; diff --git a/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.cs b/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.cs new file mode 100644 index 00000000..bdfabf38 --- /dev/null +++ b/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.cs @@ -0,0 +1,50 @@ +public class Solution { + public bool HasValidPath(int[][] grid) { + int m = grid.Length; + int n = grid[0].Length; + + Dictionary dir = new Dictionary() { + {1, new int[][] { new int[] {0, -1}, new int[] {0, 1} }}, + {2, new int[][] { new int[] {-1, 0}, new int[] {1, 0} }}, + {3, new int[][] { new int[] {0, -1}, new int[] {1, 0} }}, + {4, new int[][] { new int[] {0, 1}, new int[] {1, 0} }}, + {5, new int[][] { new int[] {0, -1}, new int[] {-1, 0} }}, + {6, new int[][] { new int[] {0, 1}, new int[] {-1, 0} }} + }; + + bool[][] vis = new bool[m][]; + for (int i = 0; i < m; i++) { + vis[i] = new bool[n]; + } + + Queue<(int, int)> q = new Queue<(int, int)>(); + q.Enqueue((0, 0)); + vis[0][0] = true; + + while (q.Count > 0) { + var (r, c) = q.Dequeue(); + + if (r == m - 1 && c == n - 1) { + return true; + } + + foreach (var d in dir[grid[r][c]]) { + int nr = r + d[0]; + int nc = c + d[1]; + + if (nr < 0 || nc < 0 || nr >= m || nc >= n || vis[nr][nc]) { + continue; + } + + foreach (var bd in dir[grid[nr][nc]]) { + if (nr + bd[0] == r && nc + bd[1] == c) { + vis[nr][nc] = true; + q.Enqueue((nr, nc)); + } + } + } + } + + return false; + } +} diff --git a/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.dart b/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.dart new file mode 100644 index 00000000..f26f68dc --- /dev/null +++ b/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.dart @@ -0,0 +1,47 @@ +class Solution { + bool hasValidPath(List> grid) { + int m = grid.length; + int n = grid[0].length; + + Map>> dir = { + 1: [[0, -1], [0, 1]], + 2: [[-1, 0], [1, 0]], + 3: [[0, -1], [1, 0]], + 4: [[0, 1], [1, 0]], + 5: [[0, -1], [-1, 0]], + 6: [[0, 1], [-1, 0]] + }; + + List> vis = List.generate(m, (_) => List.filled(n, false)); + List> q = [[0, 0]]; + vis[0][0] = true; + + while (q.isNotEmpty) { + int r = q[0][0]; + int c = q[0][1]; + q.removeAt(0); + + if (r == m - 1 && c == n - 1) { + return true; + } + + for (var d in dir[grid[r][c]]!) { + int nr = r + d[0]; + int nc = c + d[1]; + + if (nr < 0 || nc < 0 || nr >= m || nc >= n || vis[nr][nc]) { + continue; + } + + for (var bd in dir[grid[nr][nc]]!) { + if (nr + bd[0] == r && nc + bd[1] == c) { + vis[nr][nc] = true; + q.add([nr, nc]); + } + } + } + } + + return false; + } +} diff --git a/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.go b/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.go new file mode 100644 index 00000000..30cf9053 --- /dev/null +++ b/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.go @@ -0,0 +1,47 @@ +func hasValidPath(grid [][]int) bool { + m := len(grid) + n := len(grid[0]) + + dir := map[int][][]int{ + 1: {{0, -1}, {0, 1}}, + 2: {{-1, 0}, {1, 0}}, + 3: {{0, -1}, {1, 0}}, + 4: {{0, 1}, {1, 0}}, + 5: {{0, -1}, {-1, 0}}, + 6: {{0, 1}, {-1, 0}}, + } + + vis := make([][]bool, m) + for i := range vis { + vis[i] = make([]bool, n) + } + + q := [][]int{{0, 0}} + vis[0][0] = true + + for len(q) > 0 { + r, c := q[0][0], q[0][1] + q = q[1:] + + if r == m-1 && c == n-1 { + return true + } + + for _, d := range dir[grid[r][c]] { + nr, nc := r+d[0], c+d[1] + + if nr < 0 || nc < 0 || nr >= m || nc >= n || vis[nr][nc] { + continue + } + + for _, bd := range dir[grid[nr][nc]] { + if nr+bd[0] == r && nc+bd[1] == c { + vis[nr][nc] = true + q = append(q, []int{nr, nc}) + } + } + } + } + + return false +} diff --git a/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.java b/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.java new file mode 100644 index 00000000..e1ac032c --- /dev/null +++ b/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.java @@ -0,0 +1,46 @@ +class Solution { + public boolean hasValidPath(int[][] grid) { + int m = grid.length; + int n = grid[0].length; + + int[][][] dir = new int[7][][]; + dir[1] = new int[][]{{0, -1}, {0, 1}}; + dir[2] = new int[][]{{-1, 0}, {1, 0}}; + dir[3] = new int[][]{{0, -1}, {1, 0}}; + dir[4] = new int[][]{{0, 1}, {1, 0}}; + dir[5] = new int[][]{{0, -1}, {-1, 0}}; + dir[6] = new int[][]{{0, 1}, {-1, 0}}; + + boolean[][] vis = new boolean[m][n]; + Queue q = new LinkedList<>(); + q.offer(new int[]{0, 0}); + vis[0][0] = true; + + while (!q.isEmpty()) { + int[] cur = q.poll(); + int r = cur[0], c = cur[1]; + + if (r == m - 1 && c == n - 1) { + return true; + } + + for (int[] d : dir[grid[r][c]]) { + int nr = r + d[0]; + int nc = c + d[1]; + + if (nr < 0 || nc < 0 || nr >= m || nc >= n || vis[nr][nc]) { + continue; + } + + for (int[] bd : dir[grid[nr][nc]]) { + if (nr + bd[0] == r && nc + bd[1] == c) { + vis[nr][nc] = true; + q.offer(new int[]{nr, nc}); + } + } + } + } + + return false; + } +} diff --git a/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.kt b/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.kt new file mode 100644 index 00000000..96eeac78 --- /dev/null +++ b/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.kt @@ -0,0 +1,48 @@ +class Solution { + fun hasValidPath(grid: Array): Boolean { + val m = grid.size + val n = grid[0].size + + val dir = mapOf( + 1 to arrayOf(intArrayOf(0, -1), intArrayOf(0, 1)), + 2 to arrayOf(intArrayOf(-1, 0), intArrayOf(1, 0)), + 3 to arrayOf(intArrayOf(0, -1), intArrayOf(1, 0)), + 4 to arrayOf(intArrayOf(0, 1), intArrayOf(1, 0)), + 5 to arrayOf(intArrayOf(0, -1), intArrayOf(-1, 0)), + 6 to arrayOf(intArrayOf(0, 1), intArrayOf(-1, 0)) + ) + + val vis = Array(m) { BooleanArray(n) } + val q: java.util.Queue = java.util.LinkedList() + q.offer(intArrayOf(0, 0)) + vis[0][0] = true + + while (q.isNotEmpty()) { + val cur = q.poll() + val r = cur[0] + val c = cur[1] + + if (r == m - 1 && c == n - 1) { + return true + } + + for (d in dir[grid[r][c]]!!) { + val nr = r + d[0] + val nc = c + d[1] + + if (nr < 0 || nc < 0 || nr >= m || nc >= n || vis[nr][nc]) { + continue + } + + for (bd in dir[grid[nr][nc]]!!) { + if (nr + bd[0] == r && nc + bd[1] == c) { + vis[nr][nc] = true + q.offer(intArrayOf(nr, nc)) + } + } + } + } + + return false + } +} diff --git a/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.py b/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.py new file mode 100644 index 00000000..e16bd714 --- /dev/null +++ b/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.py @@ -0,0 +1,35 @@ +class Solution: + def hasValidPath(self, grid: List[List[int]]) -> bool: + m, n = len(grid), len(grid[0]) + + dir = { + 1: [(0, -1), (0, 1)], + 2: [(-1, 0), (1, 0)], + 3: [(0, -1), (1, 0)], + 4: [(0, 1), (1, 0)], + 5: [(0, -1), (-1, 0)], + 6: [(0, 1), (-1, 0)], + } + + vis = [[False] * n for _ in range(m)] + q = deque([(0, 0)]) + vis[0][0] = True + + while q: + r, c = q.popleft() + + if r == m - 1 and c == n - 1: + return True + + for dr, dc in dir[grid[r][c]]: + nr, nc = r + dr, c + dc + + if nr < 0 or nc < 0 or nr >= m or nc >= n or vis[nr][nc]: + continue + + for bdr, bdc in dir[grid[nr][nc]]: + if nr + bdr == r and nc + bdc == c: + vis[nr][nc] = True + q.append((nr, nc)) + + return False diff --git a/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.py2 b/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.py2 new file mode 100644 index 00000000..04755d5f --- /dev/null +++ b/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.py2 @@ -0,0 +1,41 @@ +class Solution(object): + def hasValidPath(self, grid): + """ + :type grid: List[List[int]] + :rtype: bool + """ + from collections import deque + + m, n = len(grid), len(grid[0]) + + dir_map = { + 1: [(0, -1), (0, 1)], + 2: [(-1, 0), (1, 0)], + 3: [(0, -1), (1, 0)], + 4: [(0, 1), (1, 0)], + 5: [(0, -1), (-1, 0)], + 6: [(0, 1), (-1, 0)] + } + + vis = [[False] * n for _ in range(m)] + q = deque([(0, 0)]) + vis[0][0] = True + + while q: + r, c = q.popleft() + + if r == m - 1 and c == n - 1: + return True + + for dr, dc in dir_map[grid[r][c]]: + nr, nc = r + dr, c + dc + + if nr < 0 or nc < 0 or nr >= m or nc >= n or vis[nr][nc]: + continue + + for bdr, bdc in dir_map[grid[nr][nc]]: + if nr + bdr == r and nc + bdc == c: + vis[nr][nc] = True + q.append((nr, nc)) + + return False diff --git a/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.rb b/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.rb new file mode 100644 index 00000000..7d2745f7 --- /dev/null +++ b/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.rb @@ -0,0 +1,41 @@ +# @param {Integer[][]} grid +# @return {Boolean} +def has_valid_path(grid) + m = grid.length + n = grid[0].length + + dir = { + 1 => [[0, -1], [0, 1]], + 2 => [[-1, 0], [1, 0]], + 3 => [[0, -1], [1, 0]], + 4 => [[0, 1], [1, 0]], + 5 => [[0, -1], [-1, 0]], + 6 => [[0, 1], [-1, 0]] + } + + vis = Array.new(m) { Array.new(n, false) } + q = [[0, 0]] + vis[0][0] = true + + while !q.empty? + r, c = q.shift + + return true if r == m - 1 && c == n - 1 + + dir[grid[r][c]].each do |dr, dc| + nr = r + dr + nc = c + dc + + next if nr < 0 || nc < 0 || nr >= m || nc >= n || vis[nr][nc] + + dir[grid[nr][nc]].each do |bdr, bdc| + if nr + bdr == r && nc + bdc == c + vis[nr][nc] = true + q.push([nr, nc]) + end + end + end + end + + false +end diff --git a/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.rs b/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.rs new file mode 100644 index 00000000..fde47355 --- /dev/null +++ b/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.rs @@ -0,0 +1,57 @@ +impl Solution { + pub fn has_valid_path(grid: Vec>) -> bool { + use std::collections::VecDeque; + + let m = grid.len(); + let n = grid[0].len(); + + let dir: std::collections::HashMap> = [ + (1, vec![(0, -1), (0, 1)]), + (2, vec![(-1, 0), (1, 0)]), + (3, vec![(0, -1), (1, 0)]), + (4, vec![(0, 1), (1, 0)]), + (5, vec![(0, -1), (-1, 0)]), + (6, vec![(0, 1), (-1, 0)]), + ].iter().cloned().collect(); + + let mut vis = vec![vec![false; n]; m]; + let mut q = VecDeque::new(); + q.push_back((0, 0)); + vis[0][0] = true; + + while let Some((r, c)) = q.pop_front() { + if r == m - 1 && c == n - 1 { + return true; + } + + if let Some(dirs) = dir.get(&grid[r][c]) { + for &(dr, dc) in dirs { + let nr = r as i32 + dr; + let nc = c as i32 + dc; + + if nr < 0 || nc < 0 || nr >= m as i32 || nc >= n as i32 { + continue; + } + + let nr = nr as usize; + let nc = nc as usize; + + if vis[nr][nc] { + continue; + } + + if let Some(bdirs) = dir.get(&grid[nr][nc]) { + for &(bdr, bdc) in bdirs { + if nr as i32 + bdr == r as i32 && nc as i32 + bdc == c as i32 { + vis[nr][nc] = true; + q.push_back((nr, nc)); + } + } + } + } + } + } + + false + } +} diff --git a/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.swift b/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.swift new file mode 100644 index 00000000..a92add0f --- /dev/null +++ b/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.swift @@ -0,0 +1,45 @@ +class Solution { + func hasValidPath(_ grid: [[Int]]) -> Bool { + let m = grid.count + let n = grid[0].count + + let dir: [Int: [(Int, Int)]] = [ + 1: [(0, -1), (0, 1)], + 2: [(-1, 0), (1, 0)], + 3: [(0, -1), (1, 0)], + 4: [(0, 1), (1, 0)], + 5: [(0, -1), (-1, 0)], + 6: [(0, 1), (-1, 0)] + ] + + var vis = Array(repeating: Array(repeating: false, count: n), count: m) + var q = [(0, 0)] + vis[0][0] = true + + while !q.isEmpty { + let (r, c) = q.removeFirst() + + if r == m - 1 && c == n - 1 { + return true + } + + for (dr, dc) in dir[grid[r][c]]! { + let nr = r + dr + let nc = c + dc + + if nr < 0 || nc < 0 || nr >= m || nc >= n || vis[nr][nc] { + continue + } + + for (bdr, bdc) in dir[grid[nr][nc]]! { + if nr + bdr == r && nc + bdc == c { + vis[nr][nc] = true + q.append((nr, nc)) + } + } + } + } + + return false + } +} diff --git a/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.ts b/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.ts new file mode 100644 index 00000000..c69a0838 --- /dev/null +++ b/tests/1001-1500/1391. check-if-there-is-a-valid-path-in-a-grid/sol.ts @@ -0,0 +1,63 @@ +function hasValidPath(grid: number[][]): boolean { + const m = grid.length; + const n = grid[0].length; + + const dir: { [key: number]: [number, number][] } = { + 1: [ + [0, -1], + [0, 1], + ], + 2: [ + [-1, 0], + [1, 0], + ], + 3: [ + [0, -1], + [1, 0], + ], + 4: [ + [0, 1], + [1, 0], + ], + 5: [ + [0, -1], + [-1, 0], + ], + 6: [ + [0, 1], + [-1, 0], + ], + }; + + const vis: boolean[][] = Array.from({ length: m }, () => + Array(n).fill(false), + ); + const q: [number, number][] = [[0, 0]]; + vis[0][0] = true; + + while (q.length > 0) { + const [r, c] = q.shift()!; + + if (r === m - 1 && c === n - 1) { + return true; + } + + for (const [dr, dc] of dir[grid[r][c]]) { + const nr = r + dr; + const nc = c + dc; + + if (nr < 0 || nc < 0 || nr >= m || nc >= n || vis[nr][nc]) { + continue; + } + + for (const [bdr, bdc] of dir[grid[nr][nc]]) { + if (nr + bdr === r && nc + bdc === c) { + vis[nr][nc] = true; + q.push([nr, nc]); + } + } + } + } + + return false; +} diff --git a/tests/1001-1500/1392. longest-happy-prefix/manifest.yaml b/tests/1001-1500/1392. longest-happy-prefix/manifest.yaml new file mode 100644 index 00000000..a71e8962 --- /dev/null +++ b/tests/1001-1500/1392. longest-happy-prefix/manifest.yaml @@ -0,0 +1,221 @@ +entry: + id: 1392 + title: "longest-happy-prefix" + params: + s: + type: string + call: + cpp: "Solution().longestPrefix({s})" + rust: "Solution::longest_prefix({s})" + python3: "Solution().longestPrefix({s})" + python2: "Solution().longestPrefix({s})" + ruby: "longest_prefix({s})" + java: "new Solution().longestPrefix({s})" + csharp: "new Solution().LongestPrefix({s})" + kotlin: "Solution().longestPrefix({s})" + go: "longestPrefix({s})" + dart: "Solution().longestPrefix({s})" + swift: "Solution().longestPrefix({s})" + typescript: "longestPrefix({s})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().longestPrefix(s, {result})" + checker: | + class Checker: + def longestPrefix(self, s, result): + prefix = [0] * len(s) + matched = 0 + for i in range(1, len(s)): + while matched and s[i] != s[matched]: + matched = prefix[matched - 1] + if s[i] == s[matched]: + matched += 1 + prefix[i] = matched + return result == s[:prefix[-1]] + +seed: 1392 + +tests: + - name: "example-level" + in: + s: "level" + out: "l" + - name: "example-aba-repeat" + in: + s: "ababab" + out: "abab" + - name: "single-character" + in: + s: "a" + out: "" + - name: "two-distinct" + in: + s: "ab" + out: "" + - name: "two-equal" + in: + s: "aa" + out: "a" + - name: "no-border" + in: + s: "abcd" + out: "" + - name: "full-periodic-border" + in: + s: "aaaaaa" + out: "aaaaa" + - name: "alternating" + in: + s: "abababa" + out: "ababa" + - name: "alternating-even" + in: + s: "abababab" + out: "ababab" + - name: "nested-borders" + in: + s: "abcababcab" + out: "abcab" + - name: "border-after-mismatch" + in: + s: "aabaaab" + out: "aab" + - name: "long-border" + in: + s: "aaaaabaaaaa" + out: "aaaaa" + - name: "border-one" + in: + s: "aabcda" + out: "a" + - name: "palindromic-no-border" + in: + s: "abccba" + out: "a" + - name: "palindromic-border" + in: + s: "abcabca" + out: "abca" + - name: "distinct-suffix" + in: + s: "banana" + out: "" + - name: "repeated-word" + in: + s: "barbarbar" + out: "barbar" + - name: "overlapping-pattern" + in: + s: "abcabcabc" + out: "abcabc" + - name: "border-length-two" + in: + s: "xyaxy" + out: "xy" + - name: "border-length-three" + in: + s: "catdogcat" + out: "cat" + - name: "late-border" + in: + s: "zzzyzzzz" + out: "zzz" + - name: "many-mismatches" + in: + s: "abacabadabacaba" + out: "abacaba" + - name: "period-three" + in: + s: "xyzxyzxyzx" + out: "xyzxyzx" + - name: "period-four" + in: + s: "abcdabcdabc" + out: "abcdabc" + - name: "single-border-at-end" + in: + s: "qwertyq" + out: "q" + - name: "two-letter-border" + in: + s: "zzazz" + out: "zz" + - name: "all-vowels" + in: + s: "aeiouaeiou" + out: "aeiou" + - name: "mixed-lowercase" + in: + s: "mississippi" + out: "" + - name: "near-repeat" + in: + s: "abcabxabcab" + out: "abcab" + - name: "nested-repetition" + in: + s: "ababacaababaca" + out: "ababaca" + - name: "long-single-border" + in: + s: "abcdefghijklmnopqrstuvwxyza" + out: "a" + - name: "suffix-prefix-chain" + in: + s: "aaaaabaaaaab" + out: "aaaaab" + - name: "large-generated-unary" + seed: 139201 + in: + s: + gen: "str" + len: 100000 + alphabet: "a" + - name: "large-generated-alphabet" + seed: 139202 + in: + s: + gen: "str" + len: 100000 + alphabet: "abcdef" + - name: "repeated-prefix-with-tail" + in: + s: "abcdabcxabcdabc" + out: "abcdabc" + - name: "large-generated-binary" + seed: 139203 + in: + s: + gen: "str" + len: 99999 + alphabet: "ab" + - name: "large-generated-triad" + seed: 139204 + in: + s: + gen: "str" + len: 85000 + alphabet: "abc" + - name: "large-generated-lowercase" + seed: 139205 + in: + s: + gen: "str" + len: 75000 + alphabet: "abcdefghijklmnopqrstuvwxyz" + - name: "repeated-composite" + in: + s: "abcabcaabcabca" + out: "abcabca" + - name: "repeated-with-separators" + in: + s: "zzabzzabzz" + out: "zzabzz" diff --git a/tests/1001-1500/1392. longest-happy-prefix/sol.cpp b/tests/1001-1500/1392. longest-happy-prefix/sol.cpp new file mode 100644 index 00000000..fc59202a --- /dev/null +++ b/tests/1001-1500/1392. longest-happy-prefix/sol.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + string longestPrefix(string s) { + int n = s.size(); + vector prefix(n, 0); + int matched = 0; + for (int i = 1; i < n; i++) { + while (matched > 0 && s[i] != s[matched]) { + matched = prefix[matched - 1]; + } + if (s[i] == s[matched]) { + matched++; + } + prefix[i] = matched; + } + return s.substr(0, prefix[n - 1]); + } +}; diff --git a/tests/1001-1500/1392. longest-happy-prefix/sol.cs b/tests/1001-1500/1392. longest-happy-prefix/sol.cs new file mode 100644 index 00000000..084fc1c2 --- /dev/null +++ b/tests/1001-1500/1392. longest-happy-prefix/sol.cs @@ -0,0 +1,17 @@ +public class Solution { + public string LongestPrefix(string s) { + int n = s.Length; + int[] prefix = new int[n]; + int matched = 0; + for (int i = 1; i < n; i++) { + while (matched > 0 && s[i] != s[matched]) { + matched = prefix[matched - 1]; + } + if (s[i] == s[matched]) { + matched++; + } + prefix[i] = matched; + } + return s.Substring(0, prefix[n - 1]); + } +} diff --git a/tests/1001-1500/1392. longest-happy-prefix/sol.dart b/tests/1001-1500/1392. longest-happy-prefix/sol.dart new file mode 100644 index 00000000..a15be34a --- /dev/null +++ b/tests/1001-1500/1392. longest-happy-prefix/sol.dart @@ -0,0 +1,17 @@ +class Solution { + String longestPrefix(String s) { + int n = s.length; + List prefix = List.filled(n, 0); + int matched = 0; + for (int i = 1; i < n; i++) { + while (matched > 0 && s[i] != s[matched]) { + matched = prefix[matched - 1]; + } + if (s[i] == s[matched]) { + matched++; + } + prefix[i] = matched; + } + return s.substring(0, prefix[n - 1]); + } +} diff --git a/tests/1001-1500/1392. longest-happy-prefix/sol.go b/tests/1001-1500/1392. longest-happy-prefix/sol.go new file mode 100644 index 00000000..783d68f8 --- /dev/null +++ b/tests/1001-1500/1392. longest-happy-prefix/sol.go @@ -0,0 +1,15 @@ +func longestPrefix(s string) string { + n := len(s) + prefix := make([]int, n) + matched := 0 + for i := 1; i < n; i++ { + for matched > 0 && s[i] != s[matched] { + matched = prefix[matched-1] + } + if s[i] == s[matched] { + matched++ + } + prefix[i] = matched + } + return s[:prefix[n-1]] +} diff --git a/tests/1001-1500/1392. longest-happy-prefix/sol.java b/tests/1001-1500/1392. longest-happy-prefix/sol.java new file mode 100644 index 00000000..beb3ce99 --- /dev/null +++ b/tests/1001-1500/1392. longest-happy-prefix/sol.java @@ -0,0 +1,17 @@ +class Solution { + public String longestPrefix(String s) { + int n = s.length(); + int[] prefix = new int[n]; + int matched = 0; + for (int i = 1; i < n; i++) { + while (matched > 0 && s.charAt(i) != s.charAt(matched)) { + matched = prefix[matched - 1]; + } + if (s.charAt(i) == s.charAt(matched)) { + matched++; + } + prefix[i] = matched; + } + return s.substring(0, prefix[n - 1]); + } +} diff --git a/tests/1001-1500/1392. longest-happy-prefix/sol.kt b/tests/1001-1500/1392. longest-happy-prefix/sol.kt new file mode 100644 index 00000000..0452cd08 --- /dev/null +++ b/tests/1001-1500/1392. longest-happy-prefix/sol.kt @@ -0,0 +1,17 @@ +class Solution { + fun longestPrefix(s: String): String { + val n = s.length + val prefix = IntArray(n) + var matched = 0 + for (i in 1 until n) { + while (matched > 0 && s[i] != s[matched]) { + matched = prefix[matched - 1] + } + if (s[i] == s[matched]) { + matched++ + } + prefix[i] = matched + } + return s.substring(0, prefix[n - 1]) + } +} diff --git a/tests/1001-1500/1392. longest-happy-prefix/sol.py b/tests/1001-1500/1392. longest-happy-prefix/sol.py new file mode 100644 index 00000000..2d5f087e --- /dev/null +++ b/tests/1001-1500/1392. longest-happy-prefix/sol.py @@ -0,0 +1,11 @@ +class Solution: + def longestPrefix(self, s: str) -> str: + prefix = [0] * len(s) + matched = 0 + for i in range(1, len(s)): + while matched and s[i] != s[matched]: + matched = prefix[matched - 1] + if s[i] == s[matched]: + matched += 1 + prefix[i] = matched + return s[: prefix[-1]] diff --git a/tests/1001-1500/1392. longest-happy-prefix/sol.py2 b/tests/1001-1500/1392. longest-happy-prefix/sol.py2 new file mode 100644 index 00000000..09601e3a --- /dev/null +++ b/tests/1001-1500/1392. longest-happy-prefix/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def longestPrefix(self, s): + """ + :type s: str + :rtype: str + """ + n = len(s) + prefix = [0] * n + matched = 0 + for i in range(1, n): + while matched and s[i] != s[matched]: + matched = prefix[matched - 1] + if s[i] == s[matched]: + matched += 1 + prefix[i] = matched + return s[:prefix[-1]] diff --git a/tests/1001-1500/1392. longest-happy-prefix/sol.rb b/tests/1001-1500/1392. longest-happy-prefix/sol.rb new file mode 100644 index 00000000..1261c108 --- /dev/null +++ b/tests/1001-1500/1392. longest-happy-prefix/sol.rb @@ -0,0 +1,17 @@ +# @param {String} s +# @return {String} +def longest_prefix(s) + n = s.length + prefix = Array.new(n, 0) + matched = 0 + (1...n).each do |i| + while matched > 0 && s[i] != s[matched] + matched = prefix[matched - 1] + end + if s[i] == s[matched] + matched += 1 + end + prefix[i] = matched + end + s[0...prefix[-1]] +end diff --git a/tests/1001-1500/1392. longest-happy-prefix/sol.rs b/tests/1001-1500/1392. longest-happy-prefix/sol.rs new file mode 100644 index 00000000..b7482637 --- /dev/null +++ b/tests/1001-1500/1392. longest-happy-prefix/sol.rs @@ -0,0 +1,18 @@ +impl Solution { + pub fn longest_prefix(s: String) -> String { + let n = s.len(); + let chars: Vec = s.chars().collect(); + let mut prefix = vec![0; n]; + let mut matched = 0; + for i in 1..n { + while matched > 0 && chars[i] != chars[matched] { + matched = prefix[matched - 1]; + } + if chars[i] == chars[matched] { + matched += 1; + } + prefix[i] = matched; + } + chars[0..prefix[n - 1]].iter().collect() + } +} diff --git a/tests/1001-1500/1392. longest-happy-prefix/sol.swift b/tests/1001-1500/1392. longest-happy-prefix/sol.swift new file mode 100644 index 00000000..e4a4d998 --- /dev/null +++ b/tests/1001-1500/1392. longest-happy-prefix/sol.swift @@ -0,0 +1,18 @@ +class Solution { + func longestPrefix(_ s: String) -> String { + let n = s.count + let chars = Array(s) + var prefix = [Int](repeating: 0, count: n) + var matched = 0 + for i in 1.. 0 && chars[i] != chars[matched] { + matched = prefix[matched - 1] + } + if chars[i] == chars[matched] { + matched += 1 + } + prefix[i] = matched + } + return String(chars[0.. 0 && s[i] !== s[matched]) { + matched = prefix[matched - 1]; + } + if (s[i] === s[matched]) { + matched++; + } + prefix[i] = matched; + } + return s.substring(0, prefix[n - 1]); +} diff --git a/tests/1001-1500/1394. find-lucky-integer-in-an-array/manifest.yaml b/tests/1001-1500/1394. find-lucky-integer-in-an-array/manifest.yaml new file mode 100644 index 00000000..4d228671 --- /dev/null +++ b/tests/1001-1500/1394. find-lucky-integer-in-an-array/manifest.yaml @@ -0,0 +1,245 @@ +entry: + id: 1394 + title: "find-lucky-integer-in-an-array" + params: + arr: + type: array + items: + type: int + call: + cpp: "Solution().findLucky({arr})" + rust: "Solution::find_lucky({arr})" + python3: "Solution().findLucky({arr})" + python2: "Solution().findLucky({arr})" + ruby: "find_lucky({arr})" + java: "new Solution().findLucky({arr})" + csharp: "new Solution().FindLucky({arr})" + kotlin: "Solution().findLucky({arr})" + go: "findLucky({arr})" + dart: "Solution().findLucky({arr})" + swift: "Solution().findLucky({arr})" + typescript: "findLucky({arr})" +judge: + type: exact +limits: + time_ms: 300 + memory_mb: 300 +oracle: + python3: + call: "Checker().findLucky(arr, {result})" + checker: | + from collections import Counter + class Checker: + def findLucky(self, arr, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + frequencies = Counter(arr) + lucky = [value for value, count in frequencies.items() if value == count] + return result == (max(lucky) if lucky else -1) +seed: 1394 +tests: + - name: ex1 + in: + arr: [2, 2, 3, 4] + out: 2 + - name: ex2 + in: + arr: [1, 2, 2, 3, 3, 3] + out: 3 + - name: ex3 + in: + arr: [2, 2, 2, 3, 3] + out: -1 + - name: single_one + in: + arr: [1] + out: 1 + - name: single_maximum_value + in: + arr: [500] + out: -1 + - name: ones_not_lucky_when_repeated + in: + arr: [1, 1, 1] + out: -1 + - name: repeated_two + in: + arr: [2, 2] + out: 2 + - name: repeated_three + in: + arr: [3, 3, 3] + out: 3 + - name: all_small_values_lucky + in: + arr: [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] + out: 4 + - name: largest_lucky_wins + in: + arr: [1, 2, 2, 4, 4, 4, 4] + out: 4 + - name: no_lucky_integer + in: + arr: [5, 5, 5, 5] + out: -1 + - name: scattered_nonmatching_counts + in: + arr: [1, 1, 2, 3, 4, 4, 4, 5, 5] + out: -1 + - name: ten_occurs_ten_times + in: + arr: [10, 10, 10, 10, 10, 10, 10, 10, 10, 10] + out: 10 + - name: all_values_unique + in: + arr: [1, 2, 3, 4, 5] + out: 1 + - name: lucky_pair_with_noise + in: + arr: [2, 2, 7] + out: 2 + - name: lucky_triple_with_noise + in: + arr: [3, 3, 3, 8] + out: 3 + - name: lucky_four_with_noise + in: + arr: [4, 4, 4, 4, 9] + out: 4 + - name: lucky_five_with_noise + in: + arr: [5, 5, 5, 5, 5, 1] + out: 5 + - name: lucky_six_with_noise + in: + arr: [6, 6, 6, 6, 6, 6, 2] + out: 6 + - name: lucky_seven_with_noise + in: + arr: [7, 7, 7, 7, 7, 7, 7, 1] + out: 7 + - name: lucky_eight_with_noise + in: + arr: [8, 8, 8, 8, 8, 8, 8, 8, 2] + out: 8 + - name: lucky_nine_with_noise + in: + arr: [9, 9, 9, 9, 9, 9, 9, 9, 9, 3] + out: 9 + - name: lucky_ten_with_noise + in: + arr: [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 2] + out: 10 + - name: competing_lucky_values + in: + arr: [1, 2, 2, 3, 3, 3, 6, 6, 6, 6, 6, 6] + out: 6 + - name: near_lucky_values + in: + arr: [4, 4, 4, 2, 2, 2, 2] + out: -1 + - name: large_value_frequency_ten + in: + arr: [100, 100, 100, 100, 100, 100, 100, 100, 100, 100] + out: -1 + - name: maximum_value_below_required_frequency + in: + arr: [500, 500, 500, 500, 500] + out: -1 + - name: mixed_lucky_values + in: + arr: [1, 2, 2, 4, 4, 4, 8, 8, 8, 8] + out: 2 + - name: mixed_values_no_match + in: + arr: [2, 3, 3, 5, 5, 5, 7, 7, 7, 7] + out: -1 + - name: ascending_lucky_counts + in: + arr: [1, 1, 3, 3, 3, 4, 4, 4, 4] + out: 4 + - name: mixed_nonmatching_counts + in: + arr: [2, 2, 2, 5, 5, 5, 5, 9, 9] + out: -1 + - name: mixed_noise_counts + in: + arr: [6, 6, 1, 1, 1, 10, 10, 10, 10] + out: -1 + - name: complete_lucky_sequence + in: + arr: [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5] + out: 5 + - name: eleven_occurs_eleven_times + in: + arr: [11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 1] + out: 11 + - name: twelve_occurs_twelve_times + in: + arr: [12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 2] + out: 12 + - name: generated_maximum_mixed_values + seed: 1401 + in: + arr: + gen: "array" + len: 500 + of: + gen: "int" + min: 1 + max: 500 + distinct: false + sorted: false + elemType: "int" + - name: generated_maximum_low_values + seed: 1402 + in: + arr: + gen: "array" + len: 500 + of: + gen: "int" + min: 1 + max: 20 + distinct: false + sorted: false + elemType: "int" + - name: generated_large_single_value + seed: 1403 + in: + arr: + gen: "array" + len: 499 + of: + gen: "int" + min: 250 + max: 500 + distinct: false + sorted: false + elemType: "int" + - name: generated_large_small_values + seed: 1404 + in: + arr: + gen: "array" + len: 450 + of: + gen: "int" + min: 1 + max: 10 + distinct: false + sorted: false + elemType: "int" + - name: generated_maximum_broad_values + seed: 1405 + in: + arr: + gen: "array" + len: 500 + of: + gen: "int" + min: 1 + max: 500 + distinct: false + sorted: false + elemType: "int" diff --git a/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.cpp b/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.cpp new file mode 100644 index 00000000..3d5dd006 --- /dev/null +++ b/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int findLucky(vector& arr) { + unordered_map freq; + for (int num : arr) { + freq[num]++; + } + + int lucky = -1; + for (auto& [num, count] : freq) { + if (num == count) { + lucky = max(lucky, num); + } + } + + return lucky; + } +}; diff --git a/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.cs b/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.cs new file mode 100644 index 00000000..5477eab6 --- /dev/null +++ b/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.cs @@ -0,0 +1,23 @@ +public class Solution { + public int FindLucky(int[] arr) { + Dictionary freq = new Dictionary(); + foreach (int num in arr) { + if (freq.ContainsKey(num)) { + freq[num]++; + } else { + freq[num] = 1; + } + } + + int lucky = -1; + foreach (var kvp in freq) { + int num = kvp.Key; + int count = kvp.Value; + if (num == count) { + lucky = Math.Max(lucky, num); + } + } + + return lucky; + } +} diff --git a/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.dart b/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.dart new file mode 100644 index 00000000..102dac07 --- /dev/null +++ b/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.dart @@ -0,0 +1,19 @@ +class Solution { + int findLucky(List arr) { + final freq = {}; + for (final num in arr) { + freq[num] = (freq[num] ?? 0) + 1; + } + + int lucky = -1; + freq.forEach((num, count) { + if (num == count) { + if (num > lucky) { + lucky = num; + } + } + }); + + return lucky; + } +} diff --git a/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.go b/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.go new file mode 100644 index 00000000..443f07d8 --- /dev/null +++ b/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.go @@ -0,0 +1,17 @@ +func findLucky(arr []int) int { + freq := make(map[int]int) + for _, num := range arr { + freq[num]++ + } + + lucky := -1 + for num, count := range freq { + if num == count { + if num > lucky { + lucky = num + } + } + } + + return lucky +} diff --git a/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.java b/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.java new file mode 100644 index 00000000..0cd66666 --- /dev/null +++ b/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.java @@ -0,0 +1,19 @@ +class Solution { + public int findLucky(int[] arr) { + Map freq = new HashMap<>(); + for (int num : arr) { + freq.put(num, freq.getOrDefault(num, 0) + 1); + } + + int lucky = -1; + for (Map.Entry entry : freq.entrySet()) { + int num = entry.getKey(); + int count = entry.getValue(); + if (num == count) { + lucky = Math.max(lucky, num); + } + } + + return lucky; + } +} diff --git a/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.kt b/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.kt new file mode 100644 index 00000000..333ca9eb --- /dev/null +++ b/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.kt @@ -0,0 +1,17 @@ +class Solution { + fun findLucky(arr: IntArray): Int { + val freq = mutableMapOf() + for (num in arr) { + freq[num] = freq.getOrDefault(num, 0) + 1 + } + + var lucky = -1 + for ((num, count) in freq) { + if (num == count) { + lucky = maxOf(lucky, num) + } + } + + return lucky + } +} diff --git a/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.py b/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.py new file mode 100644 index 00000000..93c14410 --- /dev/null +++ b/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.py @@ -0,0 +1,12 @@ +class Solution: + def findLucky(self, arr: list[int]) -> int: + from collections import Counter + + freq = Counter(arr) + lucky = -1 + + for num, count in freq.items(): + if num == count: + lucky = max(lucky, num) + + return lucky diff --git a/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.py2 b/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.py2 new file mode 100644 index 00000000..71f6dbcf --- /dev/null +++ b/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def findLucky(self, arr): + """ + :type arr: List[int] + :rtype: int + """ + freq = {} + for num in arr: + freq[num] = freq.get(num, 0) + 1 + + lucky = -1 + for num, count in freq.items(): + if num == count: + lucky = max(lucky, num) + + return lucky diff --git a/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.rb b/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.rb new file mode 100644 index 00000000..4b8e3699 --- /dev/null +++ b/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.rb @@ -0,0 +1,15 @@ +# @param {Integer[]} arr +# @return {Integer} +def find_lucky(arr) + freq = Hash.new(0) + arr.each { |num| freq[num] += 1 } + + lucky = -1 + freq.each do |num, count| + if num == count + lucky = [lucky, num].max + end + end + + lucky +end diff --git a/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.rs b/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.rs new file mode 100644 index 00000000..31c874b2 --- /dev/null +++ b/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.rs @@ -0,0 +1,19 @@ +impl Solution { + pub fn find_lucky(arr: Vec) -> i32 { + use std::collections::HashMap; + + let mut freq: HashMap = HashMap::new(); + for num in arr { + *freq.entry(num).or_insert(0) += 1; + } + + let mut lucky = -1; + for (&num, &count) in freq.iter() { + if num == count { + lucky = lucky.max(num); + } + } + + lucky + } +} diff --git a/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.swift b/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.swift new file mode 100644 index 00000000..d1c71262 --- /dev/null +++ b/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.swift @@ -0,0 +1,17 @@ +class Solution { + func findLucky(_ arr: [Int]) -> Int { + var freq = [Int: Int]() + for num in arr { + freq[num, default: 0] += 1 + } + + var lucky = -1 + for (num, count) in freq { + if num == count { + lucky = max(lucky, num) + } + } + + return lucky + } +} diff --git a/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.ts b/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.ts new file mode 100644 index 00000000..f09dab1e --- /dev/null +++ b/tests/1001-1500/1394. find-lucky-integer-in-an-array/sol.ts @@ -0,0 +1,15 @@ +function findLucky(arr: number[]): number { + const freq: Map = new Map(); + for (const num of arr) { + freq.set(num, (freq.get(num) || 0) + 1); + } + + let lucky = -1; + freq.forEach((count, num) => { + if (num === count) { + lucky = Math.max(lucky, num); + } + }); + + return lucky; +} diff --git a/tests/1001-1500/1395. count-number-of-teams/manifest.yaml b/tests/1001-1500/1395. count-number-of-teams/manifest.yaml new file mode 100644 index 00000000..706b4624 --- /dev/null +++ b/tests/1001-1500/1395. count-number-of-teams/manifest.yaml @@ -0,0 +1,260 @@ +entry: + id: 1395 + title: "count-number-of-teams" + params: + rating: + type: array + items: + type: int + call: + cpp: "Solution().numTeams({rating})" + rust: "Solution::num_teams({rating})" + python3: "Solution().numTeams({rating})" + python2: "Solution().numTeams({rating})" + ruby: "num_teams({rating})" + java: "new Solution().numTeams({rating})" + csharp: "new Solution().NumTeams({rating})" + kotlin: "Solution().numTeams({rating})" + go: "numTeams({rating})" + dart: "Solution().numTeams({rating})" + swift: "Solution().numTeams({rating})" + typescript: "numTeams({rating})" +judge: + type: "exact" +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().numTeams(rating, {result})" + checker: | + class Checker: + def numTeams(self, rating, result): + if type(result) is not int: + return False + total = 0 + for j in range(1, len(rating) - 1): + left_less = sum(rating[i] < rating[j] for i in range(j)) + left_greater = j - left_less + right_less = sum(rating[k] < rating[j] for k in range(j + 1, len(rating))) + right_greater = len(rating) - 1 - j - right_less + total += left_less * right_greater + left_greater * right_less + return result == total +seed: 1395 +tests: + - name: "ex1_prompt" + in: + rating: [2, 5, 3, 4, 1] + out: 3 + - name: "ex2_prompt" + in: + rating: [2, 1, 3] + out: 0 + - name: "ex3_prompt" + in: + rating: [1, 2, 3, 4] + out: 4 + - name: "decreasing_minimum" + in: + rating: [3, 2, 1] + out: 1 + - name: "three_no_team" + in: + rating: [1, 3, 2] + out: 0 + - name: "increasing_five" + in: + rating: [1, 2, 3, 4, 5] + out: 10 + - name: "decreasing_five" + in: + rating: [5, 4, 3, 2, 1] + out: 10 + - name: "alternating_six" + in: + rating: [1, 4, 2, 5, 3, 6] + out: 10 + - name: "reverse_alternating_six" + in: + rating: [6, 3, 5, 2, 4, 1] + out: 10 + - name: "peak_five" + in: + rating: [1, 3, 5, 4, 2] + out: 3 + - name: "valley_five" + in: + rating: [5, 3, 1, 2, 4] + out: 3 + - name: "zigzag_seven" + in: + rating: [3, 1, 4, 2, 5, 6, 7] + out: 22 + - name: "center_peak_seven" + in: + rating: [1, 3, 5, 7, 6, 4, 2] + out: 13 + - name: "center_valley_seven" + in: + rating: [7, 5, 3, 1, 2, 4, 6] + out: 13 + - name: "permutation_eight" + in: + rating: [4, 1, 7, 3, 8, 2, 6, 5] + out: 11 + - name: "low_high_eight" + in: + rating: [1, 8, 2, 7, 3, 6, 4, 5] + out: 22 + - name: "high_low_eight" + in: + rating: [8, 1, 7, 2, 6, 3, 5, 4] + out: 22 + - name: "balanced_nine" + in: + rating: [5, 1, 9, 2, 8, 3, 7, 4, 6] + out: 22 + - name: "odds_then_evens" + in: + rating: [1, 3, 5, 7, 9, 2, 4, 6, 8] + out: 34 + - name: "evens_then_odds" + in: + rating: [2, 4, 6, 8, 1, 3, 5, 7, 9] + out: 34 + - name: "pattern_ten" + in: + rating: [2, 5, 1, 6, 3, 8, 4, 7, 9, 10] + out: 66 + - name: "sawtooth_ten" + in: + rating: [1, 6, 2, 7, 3, 8, 4, 9, 5, 10] + out: 60 + - name: "paired_blocks_ten" + in: + rating: [1, 2, 6, 7, 3, 4, 8, 9, 5, 10] + out: 70 + - name: "near_sorted_ten" + in: + rating: [1, 2, 3, 5, 4, 6, 7, 9, 8, 10] + out: 104 + - name: "permutation_eleven" + in: + rating: [6, 2, 9, 1, 8, 3, 7, 4, 10, 5, 11] + out: 58 + - name: "descending_runs_twelve" + in: + rating: [4, 3, 2, 1, 8, 7, 6, 5, 12, 11, 10, 9] + out: 76 + - name: "interleave_twelve" + in: + rating: [1, 7, 2, 8, 3, 9, 4, 10, 5, 11, 6, 12] + out: 110 + - name: "reverse_interleave_twelve" + in: + rating: [12, 6, 11, 5, 10, 4, 9, 3, 8, 2, 7, 1] + out: 110 + - name: "permutation_fifteen" + in: + rating: [8, 1, 14, 3, 12, 5, 10, 7, 15, 2, 13, 4, 11, 6, 9] + out: 129 + - name: "permutation_twenty" + in: + rating: + [13, 2, 18, 7, 11, 4, 20, 1, 16, 9, 5, 15, 3, 19, 8, 12, 6, 17, 10, 14] + out: 327 + - name: "near_reverse_fifteen" + in: + rating: [15, 14, 13, 12, 11, 10, 9, 1, 2, 3, 4, 5, 6, 7, 8] + out: 259 + - name: "low_middle_high_fifteen" + in: + rating: [1, 2, 3, 4, 5, 11, 12, 13, 14, 15, 6, 7, 8, 9, 10] + out: 230 + - name: "extreme_rating_values" + in: + rating: [100000, 1, 50000, 99999, 2, 75000, 3, 25000, 4] + out: 29 + - name: "large_spread_values" + in: + rating: + [99991, 17, 65000, 3, 88888, 42, 12000, 77777, 8, 54321, 99, 30000] + out: 69 + - name: "generated_stress_950" + seed: 9501395 + in: + rating: + gen: "array" + len: 950 + of: + gen: "int" + min: 1 + max: 100000 + distinct: true + sorted: false + elemType: "int" + - name: "generated_stress_975" + seed: 9751395 + in: + rating: + gen: "array" + len: 975 + of: + gen: "int" + min: 1 + max: 100000 + distinct: true + sorted: false + elemType: "int" + - name: "generated_stress_990" + seed: 9901395 + in: + rating: + gen: "array" + len: 990 + of: + gen: "int" + min: 1 + max: 100000 + distinct: true + sorted: false + elemType: "int" + - name: "generated_stress_997" + seed: 9971395 + in: + rating: + gen: "array" + len: 997 + of: + gen: "int" + min: 1 + max: 100000 + distinct: true + sorted: false + elemType: "int" + - name: "generated_stress_999" + seed: 9991395 + in: + rating: + gen: "array" + len: 999 + of: + gen: "int" + min: 1 + max: 100000 + distinct: true + sorted: false + elemType: "int" + - name: "generated_stress_1000" + seed: 10001395 + in: + rating: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: true + sorted: false + elemType: "int" diff --git a/tests/1001-1500/1395. count-number-of-teams/sol.cpp b/tests/1001-1500/1395. count-number-of-teams/sol.cpp new file mode 100644 index 00000000..7f7b5d46 --- /dev/null +++ b/tests/1001-1500/1395. count-number-of-teams/sol.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + int numTeams(vector& rating) { + int total = 0; + int n = rating.size(); + for (int j = 1; j < n - 1; j++) { + int leftLess = 0; + int leftGreater = 0; + for (int i = 0; i < j; i++) { + if (rating[i] < rating[j]) { + leftLess++; + } else if (rating[i] > rating[j]) { + leftGreater++; + } + } + + int rightLess = 0; + int rightGreater = 0; + for (int k = j + 1; k < n; k++) { + if (rating[k] < rating[j]) { + rightLess++; + } else if (rating[k] > rating[j]) { + rightGreater++; + } + } + + total += leftLess * rightGreater + leftGreater * rightLess; + } + return total; + } +}; diff --git a/tests/1001-1500/1395. count-number-of-teams/sol.cs b/tests/1001-1500/1395. count-number-of-teams/sol.cs new file mode 100644 index 00000000..b0caaeb3 --- /dev/null +++ b/tests/1001-1500/1395. count-number-of-teams/sol.cs @@ -0,0 +1,30 @@ +public class Solution { + public int NumTeams(int[] rating) { + int total = 0; + int n = rating.Length; + for (int j = 1; j < n - 1; j++) { + int leftLess = 0; + int leftGreater = 0; + for (int i = 0; i < j; i++) { + if (rating[i] < rating[j]) { + leftLess++; + } else if (rating[i] > rating[j]) { + leftGreater++; + } + } + + int rightLess = 0; + int rightGreater = 0; + for (int k = j + 1; k < n; k++) { + if (rating[k] < rating[j]) { + rightLess++; + } else if (rating[k] > rating[j]) { + rightGreater++; + } + } + + total += leftLess * rightGreater + leftGreater * rightLess; + } + return total; + } +} diff --git a/tests/1001-1500/1395. count-number-of-teams/sol.dart b/tests/1001-1500/1395. count-number-of-teams/sol.dart new file mode 100644 index 00000000..4db7bc2f --- /dev/null +++ b/tests/1001-1500/1395. count-number-of-teams/sol.dart @@ -0,0 +1,30 @@ +class Solution { + int numTeams(List rating) { + int total = 0; + int n = rating.length; + for (int j = 1; j < n - 1; j++) { + int leftLess = 0; + int leftGreater = 0; + for (int i = 0; i < j; i++) { + if (rating[i] < rating[j]) { + leftLess++; + } else if (rating[i] > rating[j]) { + leftGreater++; + } + } + + int rightLess = 0; + int rightGreater = 0; + for (int k = j + 1; k < n; k++) { + if (rating[k] < rating[j]) { + rightLess++; + } else if (rating[k] > rating[j]) { + rightGreater++; + } + } + + total += leftLess * rightGreater + leftGreater * rightLess; + } + return total; + } +} diff --git a/tests/1001-1500/1395. count-number-of-teams/sol.go b/tests/1001-1500/1395. count-number-of-teams/sol.go new file mode 100644 index 00000000..f270950d --- /dev/null +++ b/tests/1001-1500/1395. count-number-of-teams/sol.go @@ -0,0 +1,28 @@ +func numTeams(rating []int) int { + total := 0 + n := len(rating) + for j := 1; j < n - 1; j++ { + leftLess := 0 + leftGreater := 0 + for i := 0; i < j; i++ { + if rating[i] < rating[j] { + leftLess++ + } else if rating[i] > rating[j] { + leftGreater++ + } + } + + rightLess := 0 + rightGreater := 0 + for k := j + 1; k < n; k++ { + if rating[k] < rating[j] { + rightLess++ + } else if rating[k] > rating[j] { + rightGreater++ + } + } + + total += leftLess * rightGreater + leftGreater * rightLess + } + return total +} diff --git a/tests/1001-1500/1395. count-number-of-teams/sol.java b/tests/1001-1500/1395. count-number-of-teams/sol.java new file mode 100644 index 00000000..c394efec --- /dev/null +++ b/tests/1001-1500/1395. count-number-of-teams/sol.java @@ -0,0 +1,30 @@ +class Solution { + public int numTeams(int[] rating) { + int total = 0; + int n = rating.length; + for (int j = 1; j < n - 1; j++) { + int leftLess = 0; + int leftGreater = 0; + for (int i = 0; i < j; i++) { + if (rating[i] < rating[j]) { + leftLess++; + } else if (rating[i] > rating[j]) { + leftGreater++; + } + } + + int rightLess = 0; + int rightGreater = 0; + for (int k = j + 1; k < n; k++) { + if (rating[k] < rating[j]) { + rightLess++; + } else if (rating[k] > rating[j]) { + rightGreater++; + } + } + + total += leftLess * rightGreater + leftGreater * rightLess; + } + return total; + } +} diff --git a/tests/1001-1500/1395. count-number-of-teams/sol.kt b/tests/1001-1500/1395. count-number-of-teams/sol.kt new file mode 100644 index 00000000..2b479b3b --- /dev/null +++ b/tests/1001-1500/1395. count-number-of-teams/sol.kt @@ -0,0 +1,30 @@ +class Solution { + fun numTeams(rating: IntArray): Int { + var total = 0 + val n = rating.size + for (j in 1 until n - 1) { + var leftLess = 0 + var leftGreater = 0 + for (i in 0 until j) { + if (rating[i] < rating[j]) { + leftLess++ + } else if (rating[i] > rating[j]) { + leftGreater++ + } + } + + var rightLess = 0 + var rightGreater = 0 + for (k in j + 1 until n) { + if (rating[k] < rating[j]) { + rightLess++ + } else if (rating[k] > rating[j]) { + rightGreater++ + } + } + + total += leftLess * rightGreater + leftGreater * rightLess + } + return total + } +} diff --git a/tests/1001-1500/1395. count-number-of-teams/sol.py b/tests/1001-1500/1395. count-number-of-teams/sol.py new file mode 100644 index 00000000..e1bc9501 --- /dev/null +++ b/tests/1001-1500/1395. count-number-of-teams/sol.py @@ -0,0 +1,108 @@ +from bisect import bisect_left, bisect_right +import math +from typing import List + + +class MultiGridCounter: + def __init__(self, data: list[int]): + self.data = data + self.n = len(data) + + # 1. Establish Optimal Grid Geometry + self.block_size = int(math.isqrt(self.n)) + 1 + self.num_blocks = (self.n + self.block_size - 1) // self.block_size + + # 2. Build the Coarse Grid Layer (Maintain each block in sorted order) + self.sorted_blocks = [] + for b in range(self.num_blocks): + start = b * self.block_size + end = min(start + self.block_size, self.n) + # Store a sorted copy of the slice for fast localized querying + self.sorted_blocks.append(sorted(self.data[start:end])) + + def count_less_than_in_range( + self, query_start: int, query_end: int, val: int + ) -> int: + """Counts how many elements in data[query_start:query_end] are strictly less than val.""" + if query_start >= query_end: + return 0 + + count = 0 + + # Determine which blocks contain the start and end boundaries + start_block = query_start // self.block_size + end_block = (query_end - 1) // self.block_size + + # Case A: The query range is contained entirely within a single block + if start_block == end_block: + for idx in range(query_start, query_end): + if self.data[idx] < val: + count += 1 + return count + + # Case B: Multi-block crossing. + # 1. Process the partial left fractional block + left_block_end = (start_block + 1) * self.block_size + for idx in range(query_start, left_block_end): + if self.data[idx] < val: + count += 1 + + # 2. Process all fully covered middle blocks using the Coarse Grid + for b in range(start_block + 1, end_block): + # O(log √N) fast binary lookahead step + count += bisect_left(self.sorted_blocks[b], val) + + # 3. Process the partial right fractional block + right_block_start = end_block * self.block_size + for idx in range(right_block_start, query_end): + if self.data[idx] < val: + count += 1 + + return count + + +class Solution: + def numTeams(self, rating: List[int]) -> int: + total = 0 + for j in range(1, len(rating) - 1): + left_less = sum(rating[i] < rating[j] for i in range(j)) + left_greater = sum(rating[i] > rating[j] for i in range(j)) + right_less = sum(rating[k] < rating[j] for k in range(j + 1, len(rating))) + right_greater = sum( + rating[k] > rating[j] for k in range(j + 1, len(rating)) + ) + total += left_less * right_greater + left_greater * right_less + return total + + # The original block index implementation is retained below for reference. + n = len(rating) + if n < 3: + return 0 + + # Initialize our structural multi-grid spatial index + grid = MultiGridCounter(rating) + total_teams = 0 + + # Treat every soldier j as the middle structural axis of the team + for j in range(1, n - 1): + mid_val = rating[j] + + # --- 1. Calculations to the Left of index j [0 : j] --- + # Total elements to the left is exactly j + left_smaller = grid.count_less_than_in_range(0, j, mid_val) + left_greater = j - left_smaller + + # --- 2. Calculations to the Right of index j [j+1 : n] --- + # Total elements to the right is exactly (n - 1 - j) + right_elements = n - 1 - j + right_smaller = grid.count_less_than_in_range(j + 1, n, mid_val) + right_greater = right_elements - right_smaller + + # --- 3. Combinatorial Energy Update --- + # Monotonically Increasing: rating[i] < rating[j] < rating[k] + # Monotonically Decreasing: rating[i] > rating[j] > rating[k] + total_teams += (left_smaller * right_greater) + ( + left_greater * right_smaller + ) + + return total_teams diff --git a/tests/1001-1500/1395. count-number-of-teams/sol.py2 b/tests/1001-1500/1395. count-number-of-teams/sol.py2 new file mode 100644 index 00000000..76bfb91c --- /dev/null +++ b/tests/1001-1500/1395. count-number-of-teams/sol.py2 @@ -0,0 +1,15 @@ +class Solution(object): + def numTeams(self, rating): + """ + :type rating: List[int] + :rtype: int + """ + total = 0 + n = len(rating) + for j in range(1, n - 1): + left_less = sum(1 for i in range(j) if rating[i] < rating[j]) + left_greater = sum(1 for i in range(j) if rating[i] > rating[j]) + right_less = sum(1 for k in range(j + 1, n) if rating[k] < rating[j]) + right_greater = sum(1 for k in range(j + 1, n) if rating[k] > rating[j]) + total += left_less * right_greater + left_greater * right_less + return total diff --git a/tests/1001-1500/1395. count-number-of-teams/sol.rb b/tests/1001-1500/1395. count-number-of-teams/sol.rb new file mode 100644 index 00000000..8a11b1de --- /dev/null +++ b/tests/1001-1500/1395. count-number-of-teams/sol.rb @@ -0,0 +1,30 @@ +# @param {Integer[]} rating +# @return {Integer} +def num_teams(rating) + total = 0 + n = rating.length + (1...n - 1).each do |j| + left_less = 0 + left_greater = 0 + (0...j).each do |i| + if rating[i] < rating[j] + left_less += 1 + elsif rating[i] > rating[j] + left_greater += 1 + end + end + + right_less = 0 + right_greater = 0 + (j + 1...n).each do |k| + if rating[k] < rating[j] + right_less += 1 + elsif rating[k] > rating[j] + right_greater += 1 + end + end + + total += left_less * right_greater + left_greater * right_less + end + total +end diff --git a/tests/1001-1500/1395. count-number-of-teams/sol.rs b/tests/1001-1500/1395. count-number-of-teams/sol.rs new file mode 100644 index 00000000..3518d98b --- /dev/null +++ b/tests/1001-1500/1395. count-number-of-teams/sol.rs @@ -0,0 +1,30 @@ +impl Solution { + pub fn num_teams(rating: Vec) -> i32 { + let mut total = 0; + let n = rating.len(); + for j in 1..n - 1 { + let mut left_less = 0; + let mut left_greater = 0; + for i in 0..j { + if rating[i] < rating[j] { + left_less += 1; + } else if rating[i] > rating[j] { + left_greater += 1; + } + } + + let mut right_less = 0; + let mut right_greater = 0; + for k in j + 1..n { + if rating[k] < rating[j] { + right_less += 1; + } else if rating[k] > rating[j] { + right_greater += 1; + } + } + + total += left_less * right_greater + left_greater * right_less; + } + total + } +} diff --git a/tests/1001-1500/1395. count-number-of-teams/sol.swift b/tests/1001-1500/1395. count-number-of-teams/sol.swift new file mode 100644 index 00000000..98042124 --- /dev/null +++ b/tests/1001-1500/1395. count-number-of-teams/sol.swift @@ -0,0 +1,30 @@ +class Solution { + func numTeams(_ rating: [Int]) -> Int { + var total = 0 + let n = rating.count + for j in 1.. rating[j] { + leftGreater += 1 + } + } + + var rightLess = 0 + var rightGreater = 0 + for k in j + 1.. rating[j] { + rightGreater += 1 + } + } + + total += leftLess * rightGreater + leftGreater * rightLess + } + return total + } +} diff --git a/tests/1001-1500/1395. count-number-of-teams/sol.ts b/tests/1001-1500/1395. count-number-of-teams/sol.ts new file mode 100644 index 00000000..506253c8 --- /dev/null +++ b/tests/1001-1500/1395. count-number-of-teams/sol.ts @@ -0,0 +1,28 @@ +function numTeams(rating: number[]): number { + let total = 0; + const n = rating.length; + for (let j = 1; j < n - 1; j++) { + let leftLess = 0; + let leftGreater = 0; + for (let i = 0; i < j; i++) { + if (rating[i] < rating[j]) { + leftLess++; + } else if (rating[i] > rating[j]) { + leftGreater++; + } + } + + let rightLess = 0; + let rightGreater = 0; + for (let k = j + 1; k < n; k++) { + if (rating[k] < rating[j]) { + rightLess++; + } else if (rating[k] > rating[j]) { + rightGreater++; + } + } + + total += leftLess * rightGreater + leftGreater * rightLess; + } + return total; +} diff --git a/tests/1001-1500/1397. find-all-good-strings/manifest.yaml b/tests/1001-1500/1397. find-all-good-strings/manifest.yaml new file mode 100644 index 00000000..57db47b6 --- /dev/null +++ b/tests/1001-1500/1397. find-all-good-strings/manifest.yaml @@ -0,0 +1,352 @@ +entry: + id: 1397 + title: find-all-good-strings + params: + n: + type: int + s1: + type: string + s2: + type: string + evil: + type: string + call: + cpp: "Solution().findGoodStrings({n}, {s1}, {s2}, {evil})" + rust: "Solution::find_good_strings({n}, {s1}, {s2}, {evil})" + python3: "Solution().findGoodStrings({n}, {s1}, {s2}, {evil})" + python2: "Solution().findGoodStrings({n}, {s1}, {s2}, {evil})" + ruby: "find_good_strings({n}, {s1}, {s2}, {evil})" + java: "new Solution().findGoodStrings({n}, {s1}, {s2}, {evil})" + csharp: "new Solution().FindGoodStrings({n}, {s1}, {s2}, {evil})" + kotlin: "Solution().findGoodStrings({n}, {s1}, {s2}, {evil})" + go: "findGoodStrings({n}, {s1}, {s2}, {evil})" + dart: "Solution().findGoodStrings({n}, {s1}, {s2}, {evil})" + swift: "Solution().findGoodStrings({n}, {s1}, {s2}, {evil})" + typescript: "findGoodStrings({n}, {s1}, {s2}, {evil})" +judge: + type: exact +limits: + time_ms: 1500 + memory_mb: 256 +oracle: + python3: + call: "Checker().findGoodStrings(n, s1, s2, evil, {result})" + checker: | + class Checker: + def findGoodStrings(self, n, s1, s2, evil, result): + if not isinstance(n, int) or not 1 <= n <= 500: + return False + if not all(isinstance(value, str) and len(value) == n for value in (s1, s2)): + return False + if not isinstance(evil, str) or not 1 <= len(evil) <= n: + return False + if not all(all('a' <= char <= 'z' for char in value) for value in (s1, s2, evil)) or s1 > s2: + return False + if not isinstance(result, int) or isinstance(result, bool): + return False + mod = 1000000007 + m = len(evil) + lps = [0] * m + for i in range(1, m): + j = lps[i - 1] + while j and evil[i] != evil[j]: + j = lps[j - 1] + if evil[i] == evil[j]: + j += 1 + lps[i] = j + + transitions = [[0] * 26 for _ in range(m)] + for state in range(m): + for code in range(26): + char = chr(ord('a') + code) + j = state + while j and char != evil[j]: + j = lps[j - 1] + if char == evil[j]: + j += 1 + transitions[state][code] = j + + def count_at_most(bound): + less = [0] * m + equal = [1] + [0] * (m - 1) + for pos, limit_char in enumerate(bound): + limit = ord(limit_char) - ord('a') + next_less = [0] * m + next_equal = [0] * m + for state, ways in enumerate(less): + if not ways: + continue + for code in range(26): + next_state = transitions[state][code] + if next_state < m: + next_less[next_state] = (next_less[next_state] + ways) % mod + for state, ways in enumerate(equal): + if not ways: + continue + for code in range(limit): + next_state = transitions[state][code] + if next_state < m: + next_less[next_state] = (next_less[next_state] + ways) % mod + next_state = transitions[state][limit] + if next_state < m: + next_equal[next_state] = (next_equal[next_state] + ways) % mod + less, equal = next_less, next_equal + return (sum(less) + sum(equal)) % mod + + def predecessor(value): + chars = list(value) + index = len(chars) - 1 + while chars[index] == 'a': + chars[index] = 'z' + index -= 1 + if index < 0: + return None + chars[index] = chr(ord(chars[index]) - 1) + return ''.join(chars) + + lower = predecessor(s1) + below_lower = 0 if lower is None else count_at_most(lower) + expected = (count_at_most(s2) - below_lower) % mod + return result == expected +seed: 1397 +tests: + - name: one_letter_no_match + in: + n: 1 + s1: a + s2: z + evil: b + - name: one_letter_exact_evil + in: + n: 1 + s1: a + s2: a + evil: a + - name: exact_single_range + in: + n: 2 + s1: aa + s2: aa + evil: b + - name: exact_evil_range + in: + n: 2 + s1: ab + s2: ab + evil: ab + - name: example_like + in: + n: 2 + s1: aa + s2: zz + evil: b + - name: evil_at_prefix + in: + n: 3 + s1: aaa + s2: abc + evil: aa + - name: evil_at_suffix + in: + n: 3 + s1: aba + s2: abz + evil: ba + - name: no_possible_evil + in: + n: 3 + s1: aaa + s2: aaa + evil: zzz + - name: full_alphabet_three + in: + n: 3 + s1: aaa + s2: zzz + evil: abc + - name: tight_lower + in: + n: 3 + s1: abc + s2: abd + evil: c + - name: tight_upper + in: + n: 3 + s1: xya + s2: xyz + evil: "y" + - name: repeated_evil + in: + n: 4 + s1: aaaa + s2: aazz + evil: aa + - name: overlapping_evil + in: + n: 4 + s1: abaa + s2: abzz + evil: aba + - name: evil_length_n + in: + n: 4 + s1: abcd + s2: abcd + evil: abcd + - name: evil_length_long + in: + n: 4 + s1: aaaa + s2: zzzz + evil: zzzz + - name: narrow_range + in: + n: 4 + s1: bcde + s2: bcdf + evil: cd + - name: repeated_a + in: + n: 5 + s1: aaaaa + s2: aaaaa + evil: aaa + - name: repeated_b + in: + n: 5 + s1: bbbbb + s2: bbbbb + evil: bb + - name: evil_middle + in: + n: 5 + s1: aaaaa + s2: abcde + evil: bc + - name: evil_impossible_alphabet + in: + n: 5 + s1: aaaaa + s2: ccccc + evil: z + - name: reversed_not_allowed_boundary + in: + n: 3 + s1: aaa + s2: aaz + evil: az + - name: distinct_evil + in: + n: 5 + s1: abcde + s2: abcde + evil: abcde + - name: lexicographic_small + in: + n: 5 + s1: aaaaa + s2: aaazz + evil: az + - name: lexicographic_large + in: + n: 5 + s1: xxxxx + s2: zzzzz + evil: xy + - name: evil_single_c + in: + n: 5 + s1: aaaaa + s2: eeeee + evil: c + - name: evil_single_a + in: + n: 4 + s1: aaaa + s2: dddd + evil: a + - name: two_evil_patterns + in: + n: 6 + s1: aaaaaa + s2: abzzzz + evil: ab + - name: six_repeated + in: + n: 6 + s1: abcabc + s2: abcabc + evil: cab + - name: seven_narrow + in: + n: 7 + s1: aaaaaaa + s2: aaazzzz + evil: aaa + - name: eight_pattern + in: + n: 8 + s1: abababab + s2: abababab + evil: bab + - name: nine_full_range + in: + n: 9 + s1: aaaaaaaaa + s2: zzzzzzzzz + evil: xyz + - name: ten_long_evil + in: + n: 10 + s1: aaaaaaaaaa + s2: aazzzzzzzz + evil: aaz + - name: ten_exact_upper + in: + n: 10 + s1: abcdefghij + s2: abcdefghij + evil: fgh + - name: repeated_prefix_evil + in: + n: 6 + s1: aaaaaa + s2: zzzzzz + evil: aaaa + - name: final_mixed + in: + n: 8 + s1: abcdefgh + s2: abcdefgz + evil: def + - name: example_one + in: + n: 2 + s1: aa + s2: da + evil: b + - name: example_two_zero + in: + n: 8 + s1: leetcode + s2: leetgoes + evil: leet + - name: example_three + in: + n: 2 + s1: gx + s2: gz + evil: x + - name: evil_after_partial_overlap + in: + n: 7 + s1: aababaa + s2: aabzzzz + evil: abab + - name: full_range_longer_pattern + in: + n: 12 + s1: aaaaaaaaaaaa + s2: zzzzzzzzzzzz + evil: abcdef diff --git a/tests/1001-1500/1397. find-all-good-strings/sol.cpp b/tests/1001-1500/1397. find-all-good-strings/sol.cpp new file mode 100644 index 00000000..c0e85525 --- /dev/null +++ b/tests/1001-1500/1397. find-all-good-strings/sol.cpp @@ -0,0 +1,62 @@ +class Solution { +public: + const int MOD = 1000000007; + + int findGoodStrings(int n, string s1, string s2, string evil) { + int m = evil.length(); + + vector lps(m, 0); + for (int i = 1; i < m; i++) { + int j = lps[i - 1]; + while (j > 0 && evil[i] != evil[j]) { + j = lps[j - 1]; + } + if (evil[i] == evil[j]) { + lps[i] = j + 1; + } + } + + auto getNextState = [&](int currMatch, char c) -> int { + while (currMatch > 0 && c != evil[currMatch]) { + currMatch = lps[currMatch - 1]; + } + if (c == evil[currMatch]) { + currMatch++; + } + return currMatch; + }; + + vector>>> memo( + n + 1, vector>>( + m + 1, vector>( + 2, vector(2, -1) + ) + ) + ); + + function dp = [&](int idx, int eIdx, int tightLo, int tightHi) -> int { + if (eIdx == m) return 0; + if (idx == n) return 1; + + if (memo[idx][eIdx][tightLo][tightHi] != -1) { + return memo[idx][eIdx][tightLo][tightHi]; + } + + int res = 0; + char lower = tightLo ? s1[idx] : 'a'; + char upper = tightHi ? s2[idx] : 'z'; + + for (char c = lower; c <= upper; c++) { + int nextEIdx = getNextState(eIdx, c); + int nextTightLo = (tightLo && c == lower) ? 1 : 0; + int nextTightHi = (tightHi && c == upper) ? 1 : 0; + + res = (res + dp(idx + 1, nextEIdx, nextTightLo, nextTightHi)) % MOD; + } + + return memo[idx][eIdx][tightLo][tightHi] = res; + }; + + return dp(0, 0, 1, 1); + } +}; diff --git a/tests/1001-1500/1397. find-all-good-strings/sol.cs b/tests/1001-1500/1397. find-all-good-strings/sol.cs new file mode 100644 index 00000000..0a82ee4f --- /dev/null +++ b/tests/1001-1500/1397. find-all-good-strings/sol.cs @@ -0,0 +1,73 @@ +public class Solution { + private const int MOD = 1000000007; + private int n; + private string s1, s2, evil; + private int[] lps; + private int[][][][] memo; + + public int FindGoodStrings(int n, string s1, string s2, string evil) { + this.n = n; + this.s1 = s1; + this.s2 = s2; + this.evil = evil; + int m = evil.Length; + + lps = new int[m]; + for (int i = 1; i < m; i++) { + int j = lps[i - 1]; + while (j > 0 && evil[i] != evil[j]) { + j = lps[j - 1]; + } + if (evil[i] == evil[j]) { + lps[i] = j + 1; + } + } + + memo = new int[n + 1][][][]; + for (int i = 0; i <= n; i++) { + memo[i] = new int[m + 1][][]; + for (int j = 0; j <= m; j++) { + memo[i][j] = new int[2][]; + for (int k = 0; k < 2; k++) { + memo[i][j][k] = new int[2] { -1, -1 }; + } + } + } + + return Dp(0, 0, 1, 1); + } + + private int GetNextState(int currMatch, char c) { + while (currMatch > 0 && c != evil[currMatch]) { + currMatch = lps[currMatch - 1]; + } + if (c == evil[currMatch]) { + currMatch++; + } + return currMatch; + } + + private int Dp(int idx, int eIdx, int tightLo, int tightHi) { + if (eIdx == evil.Length) return 0; + if (idx == n) return 1; + + if (memo[idx][eIdx][tightLo][tightHi] != -1) { + return memo[idx][eIdx][tightLo][tightHi]; + } + + int res = 0; + char lower = tightLo == 1 ? s1[idx] : 'a'; + char upper = tightHi == 1 ? s2[idx] : 'z'; + + for (char c = lower; c <= upper; c++) { + int nextEIdx = GetNextState(eIdx, c); + int nextTightLo = (tightLo == 1 && c == lower) ? 1 : 0; + int nextTightHi = (tightHi == 1 && c == upper) ? 1 : 0; + + res = (res + Dp(idx + 1, nextEIdx, nextTightLo, nextTightHi)) % MOD; + } + + memo[idx][eIdx][tightLo][tightHi] = res; + return res; + } +} diff --git a/tests/1001-1500/1397. find-all-good-strings/sol.dart b/tests/1001-1500/1397. find-all-good-strings/sol.dart new file mode 100644 index 00000000..d097cae1 --- /dev/null +++ b/tests/1001-1500/1397. find-all-good-strings/sol.dart @@ -0,0 +1,67 @@ +class Solution { + static const int MOD = 1000000007; + + int findGoodStrings(int n, String s1, String s2, String evil) { + int m = evil.length; + + List lps = List.filled(m, 0); + for (int i = 1; i < m; i++) { + int j = lps[i - 1]; + while (j > 0 && evil[i] != evil[j]) { + j = lps[j - 1]; + } + if (evil[i] == evil[j]) { + lps[i] = j + 1; + } + } + + int getNextState(int currMatch, String c) { + while (currMatch > 0 && c != evil[currMatch]) { + currMatch = lps[currMatch - 1]; + } + if (c == evil[currMatch]) { + currMatch++; + } + return currMatch; + } + + List>>> memo = List.generate( + n + 1, + (_) => List.generate( + m + 1, + (_) => List.generate( + 2, + (_) => List.filled(2, -1), + ), + ), + ); + + int dp(int idx, int eIdx, int tightLo, int tightHi) { + if (eIdx == m) return 0; + if (idx == n) return 1; + + if (memo[idx][eIdx][tightLo][tightHi] != -1) { + return memo[idx][eIdx][tightLo][tightHi]; + } + + int res = 0; + String lower = tightLo == 1 ? s1[idx] : 'a'; + String upper = tightHi == 1 ? s2[idx] : 'z'; + + for (int charCode = lower.codeUnitAt(0); charCode <= upper.codeUnitAt(0); charCode++) { + String c = String.fromCharCode(charCode); + + int nextEIdx = getNextState(eIdx, c); + int nextTightLo = (tightLo == 1 && c == lower) ? 1 : 0; + int nextTightHi = (tightHi == 1 && c == upper) ? 1 : 0; + + res = (res + dp(idx + 1, nextEIdx, nextTightLo, nextTightHi)) % MOD; + } + + memo[idx][eIdx][tightLo][tightHi] = res; + return res; + } + + return dp(0, 0, 1, 1); + } +} diff --git a/tests/1001-1500/1397. find-all-good-strings/sol.go b/tests/1001-1500/1397. find-all-good-strings/sol.go new file mode 100644 index 00000000..7f25c205 --- /dev/null +++ b/tests/1001-1500/1397. find-all-good-strings/sol.go @@ -0,0 +1,82 @@ +func findGoodStrings(n int, s1 string, s2 string, evil string) int { + const MOD = 1000000007 + m := len(evil) + + lps := make([]int, m) + for i := 1; i < m; i++ { + j := lps[i - 1] + for j > 0 && evil[i] != evil[j] { + j = lps[j - 1] + } + if evil[i] == evil[j] { + lps[i] = j + 1 + } + } + + getNextState := func(currMatch int, c byte) int { + for currMatch > 0 && c != evil[currMatch] { + currMatch = lps[currMatch - 1] + } + if c == evil[currMatch] { + currMatch++ + } + return currMatch + } + + memo := make([][][][]int, n + 1) + for i := range memo { + memo[i] = make([][][]int, m + 1) + for j := range memo[i] { + memo[i][j] = make([][]int, 2) + for k := range memo[i][j] { + memo[i][j][k] = make([]int, 2) + for l := range memo[i][j][k] { + memo[i][j][k][l] = -1 + } + } + } + } + + var dp func(idx, eIdx, tightLo, tightHi int) int + dp = func(idx, eIdx, tightLo, tightHi int) int { + if eIdx == m { + return 0 + } + if idx == n { + return 1 + } + + if memo[idx][eIdx][tightLo][tightHi] != -1 { + return memo[idx][eIdx][tightLo][tightHi] + } + + res := 0 + lower := byte('a') + if tightLo == 1 { + lower = s1[idx] + } + upper := byte('z') + if tightHi == 1 { + upper = s2[idx] + } + + for c := lower; c <= upper; c++ { + nextEIdx := getNextState(eIdx, c) + nextTightLo := 0 + if tightLo == 1 && c == lower { + nextTightLo = 1 + } + nextTightHi := 0 + if tightHi == 1 && c == upper { + nextTightHi = 1 + } + + res = (res + dp(idx + 1, nextEIdx, nextTightLo, nextTightHi)) % MOD + } + + memo[idx][eIdx][tightLo][tightHi] = res + return res + } + + return dp(0, 0, 1, 1) +} diff --git a/tests/1001-1500/1397. find-all-good-strings/sol.java b/tests/1001-1500/1397. find-all-good-strings/sol.java new file mode 100644 index 00000000..70da6df5 --- /dev/null +++ b/tests/1001-1500/1397. find-all-good-strings/sol.java @@ -0,0 +1,63 @@ +class Solution { + private static final int MOD = 1000000007; + private int n; + private String s1, s2, evil; + private int[] lps; + private Integer[][][][] memo; + + public int findGoodStrings(int n, String s1, String s2, String evil) { + this.n = n; + this.s1 = s1; + this.s2 = s2; + this.evil = evil; + int m = evil.length(); + + lps = new int[m]; + for (int i = 1; i < m; i++) { + int j = lps[i - 1]; + while (j > 0 && evil.charAt(i) != evil.charAt(j)) { + j = lps[j - 1]; + } + if (evil.charAt(i) == evil.charAt(j)) { + lps[i] = j + 1; + } + } + + memo = new Integer[n + 1][m + 1][2][2]; + return dp(0, 0, 1, 1); + } + + private int getNextState(int currMatch, char c) { + while (currMatch > 0 && c != evil.charAt(currMatch)) { + currMatch = lps[currMatch - 1]; + } + if (c == evil.charAt(currMatch)) { + currMatch++; + } + return currMatch; + } + + private int dp(int idx, int eIdx, int tightLo, int tightHi) { + if (eIdx == evil.length()) return 0; + if (idx == n) return 1; + + if (memo[idx][eIdx][tightLo][tightHi] != null) { + return memo[idx][eIdx][tightLo][tightHi]; + } + + int res = 0; + char lower = tightLo == 1 ? s1.charAt(idx) : 'a'; + char upper = tightHi == 1 ? s2.charAt(idx) : 'z'; + + for (char c = lower; c <= upper; c++) { + int nextEIdx = getNextState(eIdx, c); + int nextTightLo = (tightLo == 1 && c == lower) ? 1 : 0; + int nextTightHi = (tightHi == 1 && c == upper) ? 1 : 0; + + res = (res + dp(idx + 1, nextEIdx, nextTightLo, nextTightHi)) % MOD; + } + + memo[idx][eIdx][tightLo][tightHi] = res; + return res; + } +} diff --git a/tests/1001-1500/1397. find-all-good-strings/sol.kt b/tests/1001-1500/1397. find-all-good-strings/sol.kt new file mode 100644 index 00000000..4bb2093a --- /dev/null +++ b/tests/1001-1500/1397. find-all-good-strings/sol.kt @@ -0,0 +1,42 @@ +class Solution { + private val mod = 1_000_000_007 + private var length = 0 + private lateinit var lower: String + private lateinit var upper: String + private lateinit var evil: String + private lateinit var lps: IntArray + private lateinit var memo: Array>> + + fun findGoodStrings(n: Int, s1: String, s2: String, evil: String): Int { + length = n + lower = s1 + upper = s2 + this.evil = evil + lps = IntArray(evil.length) + for (i in 1 until evil.length) { + var j = lps[i - 1] + while (j > 0 && evil[i] != evil[j]) j = lps[j - 1] + if (evil[i] == evil[j]) lps[i] = j + 1 + } + memo = Array(n) { Array(evil.length) { Array(2) { IntArray(2) { -1 } } } } + return dp(0, 0, 1, 1) + } + + private fun dp(index: Int, matched: Int, lowerTight: Int, upperTight: Int): Int { + if (matched == evil.length) return 0 + if (index == length) return 1 + val cached = memo[index][matched][lowerTight][upperTight] + if (cached != -1) return cached + val low = if (lowerTight == 1) lower[index] else 'a' + val high = if (upperTight == 1) upper[index] else 'z' + var answer = 0 + for (char in low..high) { + var next = matched + while (next > 0 && char != evil[next]) next = lps[next - 1] + if (char == evil[next]) next++ + answer = ((answer.toLong() + dp(index + 1, next, if (lowerTight == 1 && char == low) 1 else 0, if (upperTight == 1 && char == high) 1 else 0)) % mod).toInt() + } + memo[index][matched][lowerTight][upperTight] = answer + return answer + } +} diff --git a/tests/1001-1500/1397. find-all-good-strings/sol.py b/tests/1001-1500/1397. find-all-good-strings/sol.py new file mode 100644 index 00000000..562b8815 --- /dev/null +++ b/tests/1001-1500/1397. find-all-good-strings/sol.py @@ -0,0 +1,55 @@ +from functools import lru_cache + + +class Solution: + def findGoodStrings(self, n: int, s1: str, s2: str, evil: str) -> int: + MOD = 10**9 + 7 + m = len(evil) + + # Precompute KMP failure function for fast transitions + lps = [0] * m + for i in range(1, m): + j = lps[i - 1] + while j > 0 and evil[i] != evil[j]: + j = lps[j - 1] + if evil[i] == evil[j]: + lps[i] = j + 1 + + @lru_cache(None) + def get_next_state(curr_match, char): + """Determines the next 'evil' match length using KMP logic.""" + while curr_match > 0 and char != evil[curr_match]: + curr_match = lps[curr_match - 1] + if char == evil[curr_match]: + curr_match += 1 + return curr_match + + @lru_cache(None) + def dp(idx, e_idx, tight_lo, tight_hi): + # If we matched the whole 'evil' string, this path is 'bad' + if e_idx == m: + return 0 + # If we reached the end, we've found 1 'good' string + if idx == n: + return 1 + + res = 0 + # Determine the range of characters allowed by s1 and s2 + lower = s1[idx] if tight_lo else "a" + upper = s2[idx] if tight_hi else "z" + + for char_code in range(ord(lower), ord(upper) + 1): + c = chr(char_code) + + # Calculate next state parameters + next_e_idx = get_next_state(e_idx, c) + next_tight_lo = tight_lo and (c == lower) + next_tight_hi = tight_hi and (c == upper) + + res = ( + res + dp(idx + 1, next_e_idx, next_tight_lo, next_tight_hi) + ) % MOD + + return res + + return dp(0, 0, True, True) diff --git a/tests/1001-1500/1397. find-all-good-strings/sol.py2 b/tests/1001-1500/1397. find-all-good-strings/sol.py2 new file mode 100644 index 00000000..be9312b1 --- /dev/null +++ b/tests/1001-1500/1397. find-all-good-strings/sol.py2 @@ -0,0 +1,34 @@ +class Solution(object): + def findGoodStrings(self, n, s1, s2, evil): + mod = 1000000007 + m = len(evil) + lps = [0] * m + for i in range(1, m): + j = lps[i - 1] + while j and evil[i] != evil[j]: + j = lps[j - 1] + if evil[i] == evil[j]: + lps[i] = j + 1 + memo = {} + def dp(index, matched, lower_tight, upper_tight): + if matched == m: + return 0 + if index == n: + return 1 + key = (index, matched, lower_tight, upper_tight) + if key in memo: + return memo[key] + low = ord(s1[index]) if lower_tight else ord('a') + high = ord(s2[index]) if upper_tight else ord('z') + answer = 0 + for code in range(low, high + 1): + char = chr(code) + next_matched = matched + while next_matched and char != evil[next_matched]: + next_matched = lps[next_matched - 1] + if char == evil[next_matched]: + next_matched += 1 + answer = (answer + dp(index + 1, next_matched, lower_tight and code == low, upper_tight and code == high)) % mod + memo[key] = answer + return answer + return dp(0, 0, True, True) diff --git a/tests/1001-1500/1397. find-all-good-strings/sol.rb b/tests/1001-1500/1397. find-all-good-strings/sol.rb new file mode 100644 index 00000000..d0185d4b --- /dev/null +++ b/tests/1001-1500/1397. find-all-good-strings/sol.rb @@ -0,0 +1,65 @@ +# @param {Integer} n +# @param {String} s1 +# @param {String} s2 +# @param {String} evil +# @return {Integer} +def find_good_strings(n, s1, s2, evil) + mod = 10**9 + 7 + m = evil.length + + lps = [0] * m + (1...m).each do |i| + j = lps[i - 1] + while j > 0 && evil[i] != evil[j] + j = lps[j - 1] + end + if evil[i] == evil[j] + lps[i] = j + 1 + end + end + + memo = {} + + get_next_state = lambda do |curr_match, char| + while curr_match > 0 && char != evil[curr_match] + curr_match = lps[curr_match - 1] + end + if char == evil[curr_match] + curr_match += 1 + end + curr_match + end + + dp = lambda do |idx, e_idx, tight_lo, tight_hi| + key = [idx, e_idx, tight_lo, tight_hi] + return memo[key] if memo.key?(key) + + if e_idx == m + memo[key] = 0 + return 0 + end + if idx == n + memo[key] = 1 + return 1 + end + + res = 0 + lower = tight_lo ? s1[idx] : 'a' + upper = tight_hi ? s2[idx] : 'z' + + (lower.ord..upper.ord).each do |char_code| + c = char_code.chr + + next_e_idx = get_next_state.call(e_idx, c) + next_tight_lo = tight_lo && (c == lower) + next_tight_hi = tight_hi && (c == upper) + + res = (res + dp.call(idx + 1, next_e_idx, next_tight_lo, next_tight_hi)) % mod + end + + memo[key] = res + res + end + + dp.call(0, 0, true, true) +end diff --git a/tests/1001-1500/1397. find-all-good-strings/sol.rs b/tests/1001-1500/1397. find-all-good-strings/sol.rs new file mode 100644 index 00000000..5d18913f --- /dev/null +++ b/tests/1001-1500/1397. find-all-good-strings/sol.rs @@ -0,0 +1,93 @@ +impl Solution { + pub fn find_good_strings(n: i32, s1: String, s2: String, evil: String) -> i32 { + const MOD: i32 = 1_000_000_007; + let n = n as usize; + let m = evil.len(); + let s1: Vec = s1.chars().collect(); + let s2: Vec = s2.chars().collect(); + let evil: Vec = evil.chars().collect(); + + let mut lps = vec![0; m]; + for i in 1..m { + let mut j = lps[i - 1]; + while j > 0 && evil[i] != evil[j] { + j = lps[j - 1]; + } + if evil[i] == evil[j] { + lps[i] = j + 1; + } + } + + let get_next_state = |curr_match: usize, c: char| -> usize { + let mut curr = curr_match; + while curr > 0 && c != evil[curr] { + curr = lps[curr - 1]; + } + if c == evil[curr] { + curr += 1; + } + curr + }; + + let mut memo = vec![vec![vec![vec![-1i32; 2]; 2]; m + 1]; n + 1]; + + fn dp( + idx: usize, + e_idx: usize, + tight_lo: usize, + tight_hi: usize, + n: usize, + m: usize, + s1: &[char], + s2: &[char], + evil: &[char], + lps: &[usize], + get_next_state: &impl Fn(usize, char) -> usize, + memo: &mut Vec>>>, + ) -> i32 { + if e_idx == m { + return 0; + } + if idx == n { + return 1; + } + + if memo[idx][e_idx][tight_lo][tight_hi] != -1 { + return memo[idx][e_idx][tight_lo][tight_hi]; + } + + let mut res = 0; + let lower = if tight_lo == 1 { s1[idx] } else { 'a' }; + let upper = if tight_hi == 1 { s2[idx] } else { 'z' }; + + let mut c = lower; + while c as u8 <= upper as u8 { + let next_e_idx = get_next_state(e_idx, c); + let next_tight_lo = if tight_lo == 1 && c == lower { 1 } else { 0 }; + let next_tight_hi = if tight_hi == 1 && c == upper { 1 } else { 0 }; + + res = (res + dp( + idx + 1, + next_e_idx, + next_tight_lo, + next_tight_hi, + n, + m, + s1, + s2, + evil, + lps, + get_next_state, + memo, + )) % MOD; + + c = ((c as u8) + 1) as char; + } + + memo[idx][e_idx][tight_lo][tight_hi] = res; + res + } + + dp(0, 0, 1, 1, n, m, &s1, &s2, &evil, &lps, &get_next_state, &mut memo) + } +} diff --git a/tests/1001-1500/1397. find-all-good-strings/sol.swift b/tests/1001-1500/1397. find-all-good-strings/sol.swift new file mode 100644 index 00000000..0f1bf887 --- /dev/null +++ b/tests/1001-1500/1397. find-all-good-strings/sol.swift @@ -0,0 +1,63 @@ +class Solution { + private let MOD = 1000000007 + + func findGoodStrings(_ n: Int, _ s1: String, _ s2: String, _ evil: String) -> Int { + let m = evil.count + let s1Arr = Array(s1) + let s2Arr = Array(s2) + let evilArr = Array(evil) + + var lps = [Int](repeating: 0, count: m) + for i in 1.. 0 && evilArr[i] != evilArr[j] { + j = lps[j - 1] + } + if evilArr[i] == evilArr[j] { + lps[i] = j + 1 + } + } + + func getNextState(_ currMatch: Int, _ c: Character) -> Int { + var curr = currMatch + while curr > 0 && c != evilArr[curr] { + curr = lps[curr - 1] + } + if c == evilArr[curr] { + curr += 1 + } + return curr + } + + var memo = Array(repeating: Array(repeating: Array(repeating: Array(repeating: -1, count: 2), count: 2), count: m + 1), count: n + 1) + + func dp(_ idx: Int, _ eIdx: Int, _ tightLo: Int, _ tightHi: Int) -> Int { + if eIdx == m { return 0 } + if idx == n { return 1 } + + if memo[idx][eIdx][tightLo][tightHi] != -1 { + return memo[idx][eIdx][tightLo][tightHi] + } + + var res = 0 + let lower = tightLo == 1 ? s1Arr[idx] : Character("a") + let upper = tightHi == 1 ? s2Arr[idx] : Character("z") + + var c = lower + while c <= upper { + let nextEIdx = getNextState(eIdx, c) + let nextTightLo = (tightLo == 1 && c == lower) ? 1 : 0 + let nextTightHi = (tightHi == 1 && c == upper) ? 1 : 0 + + res = (res + dp(idx + 1, nextEIdx, nextTightLo, nextTightHi)) % MOD + + c = Character(UnicodeScalar(c.asciiValue! + 1)) + } + + memo[idx][eIdx][tightLo][tightHi] = res + return res + } + + return dp(0, 0, 1, 1) + } +} diff --git a/tests/1001-1500/1397. find-all-good-strings/sol.ts b/tests/1001-1500/1397. find-all-good-strings/sol.ts new file mode 100644 index 00000000..422ccbca --- /dev/null +++ b/tests/1001-1500/1397. find-all-good-strings/sol.ts @@ -0,0 +1,73 @@ +function findGoodStrings( + n: number, + s1: string, + s2: string, + evil: string, +): number { + const MOD = 1000000007; + const m = evil.length; + + const lps: number[] = new Array(m).fill(0); + for (let i = 1; i < m; i++) { + let j = lps[i - 1]; + while (j > 0 && evil[i] !== evil[j]) { + j = lps[j - 1]; + } + if (evil[i] === evil[j]) { + lps[i] = j + 1; + } + } + + function getNextState(currMatch: number, c: string): number { + while (currMatch > 0 && c !== evil[currMatch]) { + currMatch = lps[currMatch - 1]; + } + if (c === evil[currMatch]) { + currMatch++; + } + return currMatch; + } + + const memo: number[][][][] = Array.from({ length: n + 1 }, () => + Array.from({ length: m + 1 }, () => + Array.from({ length: 2 }, () => new Array(2).fill(-1)), + ), + ); + + function dp( + idx: number, + eIdx: number, + tightLo: number, + tightHi: number, + ): number { + if (eIdx === m) return 0; + if (idx === n) return 1; + + if (memo[idx][eIdx][tightLo][tightHi] !== -1) { + return memo[idx][eIdx][tightLo][tightHi]; + } + + let res = 0; + const lower = tightLo === 1 ? s1[idx] : "a"; + const upper = tightHi === 1 ? s2[idx] : "z"; + + for ( + let charCode = lower.charCodeAt(0); + charCode <= upper.charCodeAt(0); + charCode++ + ) { + const c = String.fromCharCode(charCode); + + const nextEIdx = getNextState(eIdx, c); + const nextTightLo = tightLo === 1 && c === lower ? 1 : 0; + const nextTightHi = tightHi === 1 && c === upper ? 1 : 0; + + res = (res + dp(idx + 1, nextEIdx, nextTightLo, nextTightHi)) % MOD; + } + + memo[idx][eIdx][tightLo][tightHi] = res; + return res; + } + + return dp(0, 0, 1, 1); +} diff --git a/tests/1001-1500/1399. count-largest-group/manifest.yaml b/tests/1001-1500/1399. count-largest-group/manifest.yaml new file mode 100644 index 00000000..fd45ac71 --- /dev/null +++ b/tests/1001-1500/1399. count-largest-group/manifest.yaml @@ -0,0 +1,179 @@ +entry: + id: 1399 + title: "count-largest-group" + params: + n: + type: int + call: + cpp: "Solution().countLargestGroup({n})" + rust: "Solution::count_largest_group({n})" + python3: "Solution().countLargestGroup({n})" + python2: "Solution().countLargestGroup({n})" + ruby: "count_largest_group({n})" + java: "new Solution().countLargestGroup({n})" + csharp: "new Solution().CountLargestGroup({n})" + kotlin: "Solution().countLargestGroup({n})" + go: "countLargestGroup({n})" + dart: "Solution().countLargestGroup({n})" + swift: "Solution().countLargestGroup({n})" + typescript: "countLargestGroup({n})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().countLargestGroup(n, {result})" + checker: | + class Checker: + def countLargestGroup(self, n, result): + groups = {} + for value in range(1, n + 1): + digit_sum = sum(int(digit) for digit in str(value)) + groups[digit_sum] = groups.get(digit_sum, 0) + 1 + largest = max(groups.values()) + return result == sum(size == largest for size in groups.values()) + +seed: 1399 + +tests: + - name: "example-thirteen" + in: + n: 13 + - name: "example-two" + in: + n: 2 + - name: "minimum-one" + in: + n: 1 + - name: "nine" + in: + n: 9 + - name: "ten" + in: + n: 10 + - name: "eleven" + in: + n: 11 + - name: "nineteen" + in: + n: 19 + - name: "twenty" + in: + n: 20 + - name: "twenty-nine" + in: + n: 29 + - name: "thirty" + in: + n: 30 + - name: "forty-four" + in: + n: 44 + - name: "fifty-five" + in: + n: 55 + - name: "sixty-nine" + in: + n: 69 + - name: "ninety-nine" + in: + n: 99 + - name: "one-hundred" + in: + n: 100 + - name: "one-oh-one" + in: + n: 101 + - name: "one-twenty-three" + in: + n: 123 + - name: "one-ninety-nine" + in: + n: 199 + - name: "two-hundred" + in: + n: 200 + - name: "two-forty-six" + in: + n: 246 + - name: "three-hundred-thirty-three" + in: + n: 333 + - name: "four-oh-nine" + in: + n: 409 + - name: "five-hundred" + in: + n: 500 + - name: "six-six-six" + in: + n: 666 + - name: "seven-seventy-seven" + in: + n: 777 + - name: "eight-ninety-nine" + in: + n: 899 + - name: "nine-hundred-ninety-nine" + in: + n: 999 + - name: "one-thousand" + in: + n: 1000 + - name: "one-thousand-one" + in: + n: 1001 + - name: "one-two-three-four" + in: + n: 1234 + - name: "two-thousand-five" + in: + n: 2005 + - name: "three-thousand-three-hundred" + in: + n: 3300 + - name: "four-thousand-nine-hundred-ninety-nine" + in: + n: 4999 + - name: "five-thousand-five-hundred-fifty-five" + in: + n: 5555 + - name: "seven-thousand-eight-hundred-ninety" + in: + n: 7890 + - name: "maximum-ten-thousand" + in: + n: 10000 + - name: "generated-small-range" + seed: 139901 + in: + n: + gen: "int" + min: 1 + max: 100 + - name: "generated-four-digit-midrange" + seed: 139902 + in: + n: + gen: "int" + min: 1001 + max: 5000 + - name: "generated-near-maximum" + seed: 139903 + in: + n: + gen: "int" + min: 9500 + max: 10000 + - name: "generated-maximum-window" + seed: 139904 + in: + n: + gen: "int" + min: 9990 + max: 10000 diff --git a/tests/1001-1500/1399. count-largest-group/sol.cpp b/tests/1001-1500/1399. count-largest-group/sol.cpp new file mode 100644 index 00000000..51845c8f --- /dev/null +++ b/tests/1001-1500/1399. count-largest-group/sol.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + int countLargestGroup(int n) { + unordered_map mpp; + int maxi = 0, count = 0; + + for (int i = 1; i <= n; i++) { + int x = digsum(i); + mpp[x]++; + maxi = max(maxi, mpp[x]); + } + + for (auto& [k, v] : mpp) { + if (v == maxi) { + count++; + } + } + return count; + } + +private: + int digsum(int n) { + int s = 0; + while (n > 0) { + s += n % 10; + n /= 10; + } + return s; + } +}; diff --git a/tests/1001-1500/1399. count-largest-group/sol.cs b/tests/1001-1500/1399. count-largest-group/sol.cs new file mode 100644 index 00000000..ee3fbd03 --- /dev/null +++ b/tests/1001-1500/1399. count-largest-group/sol.cs @@ -0,0 +1,32 @@ +public class Solution { + public int CountLargestGroup(int n) { + Dictionary mpp = new Dictionary(); + int maxi = 0, count = 0; + + for (int i = 1; i <= n; i++) { + int x = DigSum(i); + if (mpp.ContainsKey(x)) { + mpp[x]++; + } else { + mpp[x] = 1; + } + maxi = Math.Max(maxi, mpp[x]); + } + + foreach (int v in mpp.Values) { + if (v == maxi) { + count++; + } + } + return count; + } + + private int DigSum(int n) { + int s = 0; + while (n > 0) { + s += n % 10; + n /= 10; + } + return s; + } +} diff --git a/tests/1001-1500/1399. count-largest-group/sol.dart b/tests/1001-1500/1399. count-largest-group/sol.dart new file mode 100644 index 00000000..87490b6e --- /dev/null +++ b/tests/1001-1500/1399. count-largest-group/sol.dart @@ -0,0 +1,31 @@ +class Solution { + int countLargestGroup(int n) { + Map mpp = {}; + int maxi = 0; + int count = 0; + + for (int i = 1; i <= n; i++) { + int x = digsum(i); + mpp[x] = (mpp[x] ?? 0) + 1; + if (mpp[x]! > maxi) { + maxi = mpp[x]!; + } + } + + for (int v in mpp.values) { + if (v == maxi) { + count++; + } + } + return count; + } + + int digsum(int n) { + int s = 0; + while (n > 0) { + s += n % 10; + n ~/= 10; + } + return s; + } +} diff --git a/tests/1001-1500/1399. count-largest-group/sol.go b/tests/1001-1500/1399. count-largest-group/sol.go new file mode 100644 index 00000000..327b9d2a --- /dev/null +++ b/tests/1001-1500/1399. count-largest-group/sol.go @@ -0,0 +1,29 @@ +func countLargestGroup(n int) int { + mpp := make(map[int]int) + maxi := 0 + count := 0 + + for i := 1; i <= n; i++ { + x := digsum(i) + mpp[x]++ + if mpp[x] > maxi { + maxi = mpp[x] + } + } + + for _, v := range mpp { + if v == maxi { + count++ + } + } + return count +} + +func digsum(n int) int { + s := 0 + for n > 0 { + s += n % 10 + n /= 10 + } + return s +} diff --git a/tests/1001-1500/1399. count-largest-group/sol.java b/tests/1001-1500/1399. count-largest-group/sol.java new file mode 100644 index 00000000..7e7d24c9 --- /dev/null +++ b/tests/1001-1500/1399. count-largest-group/sol.java @@ -0,0 +1,28 @@ +class Solution { + public int countLargestGroup(int n) { + Map mpp = new HashMap<>(); + int maxi = 0, count = 0; + + for (int i = 1; i <= n; i++) { + int x = digsum(i); + mpp.put(x, mpp.getOrDefault(x, 0) + 1); + maxi = Math.max(maxi, mpp.get(x)); + } + + for (int v : mpp.values()) { + if (v == maxi) { + count++; + } + } + return count; + } + + private int digsum(int n) { + int s = 0; + while (n > 0) { + s += n % 10; + n /= 10; + } + return s; + } +} diff --git a/tests/1001-1500/1399. count-largest-group/sol.kt b/tests/1001-1500/1399. count-largest-group/sol.kt new file mode 100644 index 00000000..75c25852 --- /dev/null +++ b/tests/1001-1500/1399. count-largest-group/sol.kt @@ -0,0 +1,30 @@ +class Solution { + fun countLargestGroup(n: Int): Int { + val mpp = mutableMapOf() + var maxi = 0 + var count = 0 + + for (i in 1..n) { + val x = digsum(i) + mpp[x] = mpp.getOrDefault(x, 0) + 1 + maxi = maxOf(maxi, mpp[x]!!) + } + + for (v in mpp.values) { + if (v == maxi) { + count++ + } + } + return count + } + + private fun digsum(n: Int): Int { + var num = n + var s = 0 + while (num > 0) { + s += num % 10 + num /= 10 + } + return s + } +} diff --git a/tests/1001-1500/1399. count-largest-group/sol.py b/tests/1001-1500/1399. count-largest-group/sol.py new file mode 100644 index 00000000..f668969c --- /dev/null +++ b/tests/1001-1500/1399. count-largest-group/sol.py @@ -0,0 +1,21 @@ +class Solution(object): + def countLargestGroup(self, n): + mpp = {} + maxi, count = 0, 0 + + for i in range(1, n + 1): + x = self.digsum(i) + mpp[x] = mpp.get(x, 0) + 1 + maxi = max(maxi, mpp[x]) + + for v in mpp.values(): + if v == maxi: + count += 1 + return count + + def digsum(self, n): + s = 0 + while n: + s += n % 10 + n //= 10 + return s diff --git a/tests/1001-1500/1399. count-largest-group/sol.py2 b/tests/1001-1500/1399. count-largest-group/sol.py2 new file mode 100644 index 00000000..f668969c --- /dev/null +++ b/tests/1001-1500/1399. count-largest-group/sol.py2 @@ -0,0 +1,21 @@ +class Solution(object): + def countLargestGroup(self, n): + mpp = {} + maxi, count = 0, 0 + + for i in range(1, n + 1): + x = self.digsum(i) + mpp[x] = mpp.get(x, 0) + 1 + maxi = max(maxi, mpp[x]) + + for v in mpp.values(): + if v == maxi: + count += 1 + return count + + def digsum(self, n): + s = 0 + while n: + s += n % 10 + n //= 10 + return s diff --git a/tests/1001-1500/1399. count-largest-group/sol.rb b/tests/1001-1500/1399. count-largest-group/sol.rb new file mode 100644 index 00000000..45758908 --- /dev/null +++ b/tests/1001-1500/1399. count-largest-group/sol.rb @@ -0,0 +1,27 @@ +# @param {Integer} n +# @return {Integer} +def count_largest_group(n) + mpp = {} + maxi = 0 + count = 0 + + (1..n).each do |i| + x = digsum(i) + mpp[x] = (mpp[x] || 0) + 1 + maxi = [maxi, mpp[x]].max + end + + mpp.values.each do |v| + count += 1 if v == maxi + end + count +end + +def digsum(n) + s = 0 + while n > 0 + s += n % 10 + n /= 10 + end + s +end diff --git a/tests/1001-1500/1399. count-largest-group/sol.rs b/tests/1001-1500/1399. count-largest-group/sol.rs new file mode 100644 index 00000000..18327af8 --- /dev/null +++ b/tests/1001-1500/1399. count-largest-group/sol.rs @@ -0,0 +1,31 @@ +impl Solution { + pub fn count_largest_group(n: i32) -> i32 { + use std::collections::HashMap; + let mut mpp: HashMap = HashMap::new(); + let mut maxi = 0; + let mut count = 0; + + for i in 1..=n { + let x = Self::digsum(i); + let entry = mpp.entry(x).or_insert(0); + *entry += 1; + maxi = maxi.max(*entry); + } + + for &v in mpp.values() { + if v == maxi { + count += 1; + } + } + count + } + + fn digsum(mut n: i32) -> i32 { + let mut s = 0; + while n > 0 { + s += n % 10; + n /= 10; + } + s + } +} diff --git a/tests/1001-1500/1399. count-largest-group/sol.swift b/tests/1001-1500/1399. count-largest-group/sol.swift new file mode 100644 index 00000000..19e58d62 --- /dev/null +++ b/tests/1001-1500/1399. count-largest-group/sol.swift @@ -0,0 +1,30 @@ +class Solution { + func countLargestGroup(_ n: Int) -> Int { + var mpp = [Int: Int]() + var maxi = 0 + var count = 0 + + for i in 1...n { + let x = digsum(i) + mpp[x] = (mpp[x] ?? 0) + 1 + maxi = max(maxi, mpp[x]!) + } + + for v in mpp.values { + if v == maxi { + count += 1 + } + } + return count + } + + private func digsum(_ n: Int) -> Int { + var num = n + var s = 0 + while num > 0 { + s += num % 10 + num /= 10 + } + return s + } +} diff --git a/tests/1001-1500/1399. count-largest-group/sol.ts b/tests/1001-1500/1399. count-largest-group/sol.ts new file mode 100644 index 00000000..915f3df0 --- /dev/null +++ b/tests/1001-1500/1399. count-largest-group/sol.ts @@ -0,0 +1,27 @@ +function countLargestGroup(n: number): number { + const mpp: Map = new Map(); + let maxi = 0; + let count = 0; + + for (let i = 1; i <= n; i++) { + const x = digsum(i); + mpp.set(x, (mpp.get(x) || 0) + 1); + maxi = Math.max(maxi, mpp.get(x)!); + } + + for (const v of mpp.values()) { + if (v === maxi) { + count++; + } + } + return count; +} + +function digsum(n: number): number { + let s = 0; + while (n > 0) { + s += n % 10; + n = Math.floor(n / 10); + } + return s; +} diff --git a/tests/1001-1500/1400. construct-k-palindrome-strings/manifest.yaml b/tests/1001-1500/1400. construct-k-palindrome-strings/manifest.yaml new file mode 100644 index 00000000..1b6be445 --- /dev/null +++ b/tests/1001-1500/1400. construct-k-palindrome-strings/manifest.yaml @@ -0,0 +1,244 @@ +entry: + id: 1400 + title: "construct-k-palindrome-strings" + params: + s: + type: string + k: + type: int + call: + cpp: "Solution().canConstruct({s}, {k})" + rust: "Solution::can_construct({s}, {k})" + python3: "Solution().canConstruct({s}, {k})" + python2: "Solution().canConstruct({s}, {k})" + ruby: "can_construct({s}, {k})" + java: "new Solution().canConstruct({s}, {k})" + csharp: "new Solution().CanConstruct({s}, {k})" + kotlin: "Solution().canConstruct({s}, {k})" + go: "canConstruct({s}, {k})" + dart: "Solution().canConstruct({s}, {k})" + swift: "Solution().canConstruct({s}, {k})" + typescript: "canConstruct({s}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 300 + memory_mb: 300 + +oracle: + python3: + call: "Checker().canConstruct(s, k, {result})" + checker: | + class Checker: + def canConstruct(self, s, k, result): + if not isinstance(result, bool): + return False + counts = {} + for ch in s: + counts[ch] = counts.get(ch, 0) + 1 + minimum = sum(value % 2 for value in counts.values()) + maximum = len(s) + expected = minimum <= k <= maximum + return result == expected + +seed: 1400001 + +tests: + - name: "example_annabelle" + in: + s: "annabelle" + k: 2 + - name: "example_leetcode" + in: + s: "leetcode" + k: 3 + - name: "example_true" + in: + s: "true" + k: 4 + - name: "single_character_one" + in: + s: "a" + k: 1 + - name: "single_character_too_many" + in: + s: "a" + k: 2 + - name: "all_same_many" + in: + s: "aaaaaaaaaa" + k: 10 + - name: "all_same_one" + in: + s: "aaaaaaaaaa" + k: 1 + - name: "all_unique_exact" + in: + s: "abcdefghijklmnopqrstuvwxyz" + k: 26 + - name: "all_unique_less" + in: + s: "abcdefghijklmnopqrstuvwxyz" + k: 25 + - name: "all_unique_more" + in: + s: "abcdefghijklmnopqrstuvwxyz" + k: 27 + - name: "paired_even_counts" + in: + s: "aabbccdd" + k: 4 + - name: "paired_even_one" + in: + s: "aabbccdd" + k: 1 + - name: "two_odds_two_palindromes" + in: + s: "aabbc" + k: 2 + - name: "two_odds_one_palindrome" + in: + s: "aabbc" + k: 1 + - name: "k_equals_length" + in: + s: "abacaba" + k: 7 + - name: "k_greater_length" + in: + s: "abacaba" + k: 8 + - name: "one_odd_many_pairs" + in: + s: "aabbccdde" + k: 1 + - name: "one_odd_two_strings" + in: + s: "aabbccdde" + k: 2 + - name: "four_odds" + in: + s: "abcdeeff" + k: 4 + - name: "four_odds_three" + in: + s: "abcdeeff" + k: 3 + - name: "alternating_letters" + in: + s: "abababab" + k: 8 + - name: "alternating_with_tail" + in: + s: "abababac" + k: 3 + - name: "near_lowercase_end" + in: + s: "yyzzza" + k: 2 + - name: "long_single_odd" + in: + s: "bbbbbbbbbc" + k: 2 + - name: "many_odd_small" + in: + s: "abcdefghij" + k: 10 + - name: "many_odd_not_enough" + in: + s: "abcdefghij" + k: 9 + - name: "mixed_counts" + in: + s: "aaaabbcdefgg" + k: 5 + - name: "mixed_counts_tight" + in: + s: "aaaabbcdefgg" + k: 4 + - name: "zero_odd_large_k" + in: + s: "aabbccddeeff" + k: 6 + - name: "zero_odd_small_k" + in: + s: "aabbccddeeff" + k: 1 + - name: "odd_count_equals_k" + in: + s: "aabbccddeeffg" + k: 1 + - name: "odd_count_exceeds_k" + in: + s: "abcde" + k: 4 + - name: "extra_palindrome_from_pair" + in: + s: "aabbc" + k: 3 + - name: "large_k_boundary" + in: + s: "zzzz" + k: 100000 + - name: "generated_short" + seed: 140001 + in: + s: + gen: "str" + len: + gen: "int" + min: 1 + max: 30 + alphabet: "abcde" + k: + gen: "int" + min: 1 + max: 30 + - name: "generated_medium" + seed: 140002 + in: + s: + gen: "str" + len: + gen: "int" + min: 50 + max: 200 + alphabet: "abcdefg" + k: + gen: "int" + min: 1 + max: 250 + - name: "generated_large" + seed: 140003 + in: + s: + gen: "str" + len: 90000 + alphabet: "abcd" + k: + gen: "int" + min: 1 + max: 10000 + - name: "generated_maximum_length" + seed: 140004 + in: + s: + gen: "str" + len: 100000 + alphabet: "abcdefgh" + k: + gen: "int" + min: 1 + max: 100000 + - name: "generated_maximum_k" + in: + s: "xyzxyzxyzxyzxyzxyzxyzxyzxyzxyz" + k: 100000 + + - name: "pair_split_to_length" + seed: 140007 + in: + s: "aabbc" + k: 5 diff --git a/tests/1001-1500/1400. construct-k-palindrome-strings/sol.cpp b/tests/1001-1500/1400. construct-k-palindrome-strings/sol.cpp new file mode 100644 index 00000000..1136d0e2 --- /dev/null +++ b/tests/1001-1500/1400. construct-k-palindrome-strings/sol.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + bool canConstruct(string s, int k) { + if (s.length() < k) { + return false; + } + + vector charCount(26, 0); + for (char c : s) { + charCount[c - 'a']++; + } + + int oddCount = 0; + for (int freq : charCount) { + if (freq % 2 != 0) { + oddCount++; + } + } + + return oddCount <= k; + } +}; diff --git a/tests/1001-1500/1400. construct-k-palindrome-strings/sol.cs b/tests/1001-1500/1400. construct-k-palindrome-strings/sol.cs new file mode 100644 index 00000000..834c9dfe --- /dev/null +++ b/tests/1001-1500/1400. construct-k-palindrome-strings/sol.cs @@ -0,0 +1,21 @@ +public class Solution { + public bool CanConstruct(string s, int k) { + if (s.Length < k) { + return false; + } + + int[] charCount = new int[26]; + foreach (char c in s) { + charCount[c - 'a']++; + } + + int oddCount = 0; + foreach (int freq in charCount) { + if (freq % 2 != 0) { + oddCount++; + } + } + + return oddCount <= k; + } +} diff --git a/tests/1001-1500/1400. construct-k-palindrome-strings/sol.dart b/tests/1001-1500/1400. construct-k-palindrome-strings/sol.dart new file mode 100644 index 00000000..284fb48c --- /dev/null +++ b/tests/1001-1500/1400. construct-k-palindrome-strings/sol.dart @@ -0,0 +1,21 @@ +class Solution { + bool canConstruct(String s, int k) { + if (s.length < k) { + return false; + } + + List charCount = List.filled(26, 0); + for (int i = 0; i < s.length; i++) { + charCount[s.codeUnitAt(i) - 97]++; + } + + int oddCount = 0; + for (int freq in charCount) { + if (freq % 2 != 0) { + oddCount++; + } + } + + return oddCount <= k; + } +} diff --git a/tests/1001-1500/1400. construct-k-palindrome-strings/sol.go b/tests/1001-1500/1400. construct-k-palindrome-strings/sol.go new file mode 100644 index 00000000..90cceb5a --- /dev/null +++ b/tests/1001-1500/1400. construct-k-palindrome-strings/sol.go @@ -0,0 +1,19 @@ +func canConstruct(s string, k int) bool { + if len(s) < k { + return false + } + + charCount := make([]int, 26) + for _, c := range s { + charCount[c-'a']++ + } + + oddCount := 0 + for _, freq := range charCount { + if freq%2 != 0 { + oddCount++ + } + } + + return oddCount <= k +} diff --git a/tests/1001-1500/1400. construct-k-palindrome-strings/sol.java b/tests/1001-1500/1400. construct-k-palindrome-strings/sol.java new file mode 100644 index 00000000..c8e129f6 --- /dev/null +++ b/tests/1001-1500/1400. construct-k-palindrome-strings/sol.java @@ -0,0 +1,21 @@ +class Solution { + public boolean canConstruct(String s, int k) { + if (s.length() < k) { + return false; + } + + int[] charCount = new int[26]; + for (char c : s.toCharArray()) { + charCount[c - 'a']++; + } + + int oddCount = 0; + for (int freq : charCount) { + if (freq % 2 != 0) { + oddCount++; + } + } + + return oddCount <= k; + } +} diff --git a/tests/1001-1500/1400. construct-k-palindrome-strings/sol.kt b/tests/1001-1500/1400. construct-k-palindrome-strings/sol.kt new file mode 100644 index 00000000..c8c0adf0 --- /dev/null +++ b/tests/1001-1500/1400. construct-k-palindrome-strings/sol.kt @@ -0,0 +1,15 @@ +class Solution { + fun canConstruct(s: String, k: Int): Boolean { + if (s.length < k) { + return false + } + + val charCount = IntArray(26) + for (c in s) { + charCount[c - 'a']++ + } + + val oddCount = charCount.count { it % 2 != 0 } + return oddCount <= k + } +} diff --git a/tests/1001-1500/1400. construct-k-palindrome-strings/sol.py b/tests/1001-1500/1400. construct-k-palindrome-strings/sol.py new file mode 100644 index 00000000..f0e5ff8d --- /dev/null +++ b/tests/1001-1500/1400. construct-k-palindrome-strings/sol.py @@ -0,0 +1,11 @@ +from collections import Counter + + +class Solution: + def canConstruct(self, s: str, k: int) -> bool: + if len(s) < k: + return False + + char_count = Counter(s) + odd_count = sum(freq % 2 for freq in char_count.values()) + return odd_count <= k diff --git a/tests/1001-1500/1400. construct-k-palindrome-strings/sol.py2 b/tests/1001-1500/1400. construct-k-palindrome-strings/sol.py2 new file mode 100644 index 00000000..3f571b56 --- /dev/null +++ b/tests/1001-1500/1400. construct-k-palindrome-strings/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def canConstruct(self, s, k): + """ + :type s: str + :type k: int + :rtype: bool + """ + if len(s) < k: + return False + + char_count = {} + for c in s: + char_count[c] = char_count.get(c, 0) + 1 + + odd_count = sum(freq % 2 for freq in char_count.values()) + return odd_count <= k diff --git a/tests/1001-1500/1400. construct-k-palindrome-strings/sol.rb b/tests/1001-1500/1400. construct-k-palindrome-strings/sol.rb new file mode 100644 index 00000000..f4906d65 --- /dev/null +++ b/tests/1001-1500/1400. construct-k-palindrome-strings/sol.rb @@ -0,0 +1,12 @@ +# @param {String} s +# @param {Integer} k +# @return {Boolean} +def can_construct(s, k) + return false if s.length < k + + char_count = Hash.new(0) + s.each_char { |c| char_count[c] += 1 } + + odd_count = char_count.values.count { |freq| freq % 2 != 0 } + odd_count <= k +end diff --git a/tests/1001-1500/1400. construct-k-palindrome-strings/sol.rs b/tests/1001-1500/1400. construct-k-palindrome-strings/sol.rs new file mode 100644 index 00000000..a1904af8 --- /dev/null +++ b/tests/1001-1500/1400. construct-k-palindrome-strings/sol.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn can_construct(s: String, k: i32) -> bool { + if s.len() < k as usize { + return false; + } + + let mut char_count = vec![0; 26]; + for c in s.chars() { + char_count[c as usize - 'a' as usize] += 1; + } + + let odd_count = char_count.iter().filter(|&&freq| freq % 2 != 0).count(); + odd_count <= k as usize + } +} diff --git a/tests/1001-1500/1400. construct-k-palindrome-strings/sol.swift b/tests/1001-1500/1400. construct-k-palindrome-strings/sol.swift new file mode 100644 index 00000000..156cf237 --- /dev/null +++ b/tests/1001-1500/1400. construct-k-palindrome-strings/sol.swift @@ -0,0 +1,15 @@ +class Solution { + func canConstruct(_ s: String, _ k: Int) -> Bool { + if s.count < k { + return false + } + + var charCount = [Int](repeating: 0, count: 26) + for c in s { + charCount[Int(c.asciiValue! - 97)] += 1 + } + + let oddCount = charCount.filter { $0 % 2 != 0 }.count + return oddCount <= k + } +} diff --git a/tests/1001-1500/1400. construct-k-palindrome-strings/sol.ts b/tests/1001-1500/1400. construct-k-palindrome-strings/sol.ts new file mode 100644 index 00000000..a9b33eb7 --- /dev/null +++ b/tests/1001-1500/1400. construct-k-palindrome-strings/sol.ts @@ -0,0 +1,13 @@ +function canConstruct(s: string, k: number): boolean { + if (s.length < k) { + return false; + } + + const charCount: number[] = Array(26).fill(0); + for (const c of s) { + charCount[c.charCodeAt(0) - 97]++; + } + + const oddCount = charCount.filter((freq) => freq % 2 !== 0).length; + return oddCount <= k; +} diff --git a/tests/1001-1500/1401. circle-and-rectangle-overlapping/manifest.yaml b/tests/1001-1500/1401. circle-and-rectangle-overlapping/manifest.yaml new file mode 100644 index 00000000..1364d971 --- /dev/null +++ b/tests/1001-1500/1401. circle-and-rectangle-overlapping/manifest.yaml @@ -0,0 +1,419 @@ +entry: + id: 1401 + title: "circle-and-rectangle-overlapping" + params: + radius: + type: int + xCenter: + type: int + yCenter: + type: int + x1: + type: int + y1: + type: int + x2: + type: int + y2: + type: int + call: + cpp: "Solution().checkOverlap({radius}, {xCenter}, {yCenter}, {x1}, {y1}, {x2}, {y2})" + rust: "Solution::check_overlap({radius}, {xCenter}, {yCenter}, {x1}, {y1}, {x2}, {y2})" + python3: "Solution().checkOverlap({radius}, {xCenter}, {yCenter}, {x1}, {y1}, {x2}, {y2})" + python2: "Solution().checkOverlap({radius}, {xCenter}, {yCenter}, {x1}, {y1}, {x2}, {y2})" + ruby: "check_overlap({radius}, {xCenter}, {yCenter}, {x1}, {y1}, {x2}, {y2})" + java: "new Solution().checkOverlap({radius}, {xCenter}, {yCenter}, {x1}, {y1}, {x2}, {y2})" + csharp: "new Solution().CheckOverlap({radius}, {xCenter}, {yCenter}, {x1}, {y1}, {x2}, {y2})" + kotlin: "Solution().checkOverlap({radius}, {xCenter}, {yCenter}, {x1}, {y1}, {x2}, {y2})" + go: "checkOverlap({radius}, {xCenter}, {yCenter}, {x1}, {y1}, {x2}, {y2})" + dart: "Solution().checkOverlap({radius}, {xCenter}, {yCenter}, {x1}, {y1}, {x2}, {y2})" + swift: "Solution().checkOverlap({radius}, {xCenter}, {yCenter}, {x1}, {y1}, {x2}, {y2})" + typescript: "checkOverlap({radius}, {xCenter}, {yCenter}, {x1}, {y1}, {x2}, {y2})" +judge: + type: exact +limits: + time_ms: 300 + memory_mb: 300 +oracle: + python3: + call: "Checker().checkOverlap(radius, xCenter, yCenter, x1, y1, x2, y2, {result})" + checker: | + class Checker: + def checkOverlap(self, radius, xCenter, yCenter, x1, y1, x2, y2, result): + if not isinstance(result, bool): + return False + if xCenter < x1: + dx = x1 - xCenter + elif xCenter > x2: + dx = xCenter - x2 + else: + dx = 0 + if yCenter < y1: + dy = y1 - yCenter + elif yCenter > y2: + dy = yCenter - y2 + else: + dy = 0 + return result == (dx * dx + dy * dy <= radius * radius) +seed: 1401 +tests: + - name: example_shared_edge + in: + radius: 1 + xCenter: 0 + yCenter: 0 + x1: 1 + y1: -1 + x2: 3 + y2: 1 + - name: example_separated + in: + radius: 1 + xCenter: 1 + yCenter: 1 + x1: 1 + y1: -3 + x2: 2 + y2: -1 + - name: example_corner_touch + in: + radius: 1 + xCenter: 0 + yCenter: 0 + x1: -1 + y1: 0 + x2: 0 + y2: 1 + - name: center_inside_unit_rectangle + in: + radius: 1 + xCenter: 0 + yCenter: 0 + x1: -1 + y1: -1 + x2: 1 + y2: 1 + - name: rectangle_contains_center + in: + radius: 2 + xCenter: 17 + yCenter: -23 + x1: 10 + y1: -30 + x2: 25 + y2: -20 + - name: corner_tangent_three_four + in: + radius: 5 + xCenter: 0 + yCenter: 0 + x1: 3 + y1: 4 + x2: 8 + y2: 9 + - name: corner_just_outside + in: + radius: 5 + xCenter: 0 + yCenter: 0 + x1: 4 + y1: 4 + x2: 8 + y2: 9 + - name: horizontal_strip_overlap + in: + radius: 3 + xCenter: 0 + yCenter: 0 + x1: -50 + y1: 2 + x2: 50 + y2: 4 + - name: horizontal_strip_outside + in: + radius: 3 + xCenter: 0 + yCenter: 0 + x1: -50 + y1: 4 + x2: 50 + y2: 6 + - name: vertical_strip_overlap + in: + radius: 3 + xCenter: 0 + yCenter: 0 + x1: 2 + y1: -50 + x2: 4 + y2: 50 + - name: vertical_strip_outside + in: + radius: 3 + xCenter: 0 + yCenter: 0 + x1: 4 + y1: -50 + x2: 6 + y2: 50 + - name: negative_coordinates + in: + radius: 4 + xCenter: -5 + yCenter: -5 + x1: -3 + y1: -3 + x2: 0 + y2: 0 + - name: diagonal_near + in: + radius: 3 + xCenter: 0 + yCenter: 0 + x1: 2 + y1: 2 + x2: 5 + y2: 5 + - name: diagonal_far + in: + radius: 2 + xCenter: 0 + yCenter: 0 + x1: 2 + y1: 2 + x2: 5 + y2: 5 + - name: center_on_left_edge + in: + radius: 1 + xCenter: 2 + yCenter: 4 + x1: 2 + y1: 0 + x2: 5 + y2: 8 + - name: center_on_bottom_edge + in: + radius: 1 + xCenter: 2 + yCenter: 4 + x1: 0 + y1: 4 + x2: 5 + y2: 8 + - name: rectangle_far_right + in: + radius: 7 + xCenter: 10 + yCenter: -10 + x1: 18 + y1: -2 + x2: 22 + y2: 2 + - name: rectangle_far_left + in: + radius: 7 + xCenter: 10 + yCenter: -10 + x1: -10 + y1: -18 + x2: -6 + y2: -14 + - name: large_radius_reaches_corner + in: + radius: 2000 + xCenter: 0 + yCenter: 0 + x1: 1500 + y1: 1500 + x2: 1600 + y2: 1600 + - name: radius_minimum_far + in: + radius: 1 + xCenter: 10000 + yCenter: -10000 + x1: 9998 + y1: -10002 + x2: 9999 + y2: -10001 + - name: maximum_positive_coordinates + in: + radius: 2000 + xCenter: 10000 + yCenter: 10000 + x1: 8000 + y1: 8000 + x2: 9999 + y2: 9999 + - name: maximum_negative_coordinates + in: + radius: 2000 + xCenter: -10000 + yCenter: -10000 + x1: -9999 + y1: -9999 + x2: -8000 + y2: -8000 + - name: narrow_rectangle_inside_circle + in: + radius: 10 + xCenter: 0 + yCenter: 0 + x1: -1 + y1: -1 + x2: 1 + y2: 1 + - name: narrow_rectangle_outside_circle + in: + radius: 10 + xCenter: 0 + yCenter: 0 + x1: 8 + y1: 8 + x2: 9 + y2: 9 + - name: rectangle_encloses_circle + in: + radius: 10 + xCenter: 1 + yCenter: 1 + x1: -5 + y1: -5 + x2: 5 + y2: 5 + - name: circle_and_rectangle_same_corner + in: + radius: 2 + xCenter: 5 + yCenter: 5 + x1: 7 + y1: 7 + x2: 9 + y2: 9 + - name: same_corner_just_missed + in: + radius: 2 + xCenter: 5 + yCenter: 5 + x1: 8 + y1: 8 + x2: 10 + y2: 10 + - name: center_above_rectangle + in: + radius: 6 + xCenter: 2 + yCenter: 12 + x1: -8 + y1: 3 + x2: 8 + y2: 6 + - name: center_below_rectangle + in: + radius: 6 + xCenter: 2 + yCenter: -6 + x1: -8 + y1: 3 + x2: 8 + y2: 6 + - name: center_left_of_rectangle + in: + radius: 6 + xCenter: -8 + yCenter: 3 + x1: 2 + y1: -5 + x2: 4 + y2: 9 + - name: center_right_of_rectangle + in: + radius: 6 + xCenter: 12 + yCenter: 3 + x1: -4 + y1: -5 + x2: 2 + y2: 9 + - name: shifted_diagonal_tangent + in: + radius: 9 + xCenter: -3 + yCenter: 4 + x1: -12 + y1: 10 + x2: -10 + y2: 12 + - name: shifted_diagonal_missed + in: + radius: 9 + xCenter: -3 + yCenter: 4 + x1: 2 + y1: -5 + x2: 4 + y2: -3 + - name: long_rectangle_near + in: + radius: 15 + xCenter: 0 + yCenter: 0 + x1: 10 + y1: -2 + x2: 12 + y2: 2 + - name: long_rectangle_corner_missed + in: + radius: 15 + xCenter: 0 + yCenter: 0 + x1: 11 + y1: 11 + x2: 13 + y2: 13 + - name: large_radius_edge_tangent + in: + radius: 50 + xCenter: 100 + yCenter: 100 + x1: 150 + y1: 100 + x2: 160 + y2: 110 + - name: large_radius_corner_missed + in: + radius: 50 + xCenter: 100 + yCenter: 100 + x1: 151 + y1: 151 + x2: 160 + y2: 160 + - name: unit_radius_corner_touch + in: + radius: 1 + xCenter: 0 + yCenter: 0 + x1: 1 + y1: 0 + x2: 2 + y2: 1 + - name: unit_radius_corner_missed + in: + radius: 1 + xCenter: 0 + yCenter: 0 + x1: 1 + y1: 1 + x2: 2 + y2: 2 + - name: full_coordinate_span + in: + radius: 2000 + xCenter: 0 + yCenter: 0 + x1: -10000 + y1: -10000 + x2: 10000 + y2: 10000 diff --git a/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.cpp b/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.cpp new file mode 100644 index 00000000..e5725088 --- /dev/null +++ b/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.cpp @@ -0,0 +1,9 @@ +class Solution { +public: + bool checkOverlap(int radius, int xCenter, int yCenter, int x1, int y1, int x2, int y2) { + int nearestX = max(x1, min(x2, xCenter)); + int nearestY = max(y1, min(y2, yCenter)); + int dist = (nearestX - xCenter) * (nearestX - xCenter) + (nearestY - yCenter) * (nearestY - yCenter); + return dist <= radius * radius; + } +}; diff --git a/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.cs b/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.cs new file mode 100644 index 00000000..afa2c5c8 --- /dev/null +++ b/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.cs @@ -0,0 +1,8 @@ +public class Solution { + public bool CheckOverlap(int radius, int xCenter, int yCenter, int x1, int y1, int x2, int y2) { + int nearestX = Math.Max(x1, Math.Min(x2, xCenter)); + int nearestY = Math.Max(y1, Math.Min(y2, yCenter)); + int dist = (nearestX - xCenter) * (nearestX - xCenter) + (nearestY - yCenter) * (nearestY - yCenter); + return dist <= radius * radius; + } +} diff --git a/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.dart b/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.dart new file mode 100644 index 00000000..4c08afa9 --- /dev/null +++ b/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.dart @@ -0,0 +1,8 @@ +class Solution { + bool checkOverlap(int radius, int xCenter, int yCenter, int x1, int y1, int x2, int y2) { + int nearestX = [x1, [x2, xCenter].reduce((a, b) => a < b ? a : b)].reduce((a, b) => a > b ? a : b); + int nearestY = [y1, [y2, yCenter].reduce((a, b) => a < b ? a : b)].reduce((a, b) => a > b ? a : b); + int dist = (nearestX - xCenter) * (nearestX - xCenter) + (nearestY - yCenter) * (nearestY - yCenter); + return dist <= radius * radius; + } +} diff --git a/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.go b/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.go new file mode 100644 index 00000000..d861a0b8 --- /dev/null +++ b/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.go @@ -0,0 +1,6 @@ +func checkOverlap(radius int, xCenter int, yCenter int, x1 int, y1 int, x2 int, y2 int) bool { + nearestX := max(x1, min(x2, xCenter)) + nearestY := max(y1, min(y2, yCenter)) + dist := (nearestX - xCenter) * (nearestX - xCenter) + (nearestY - yCenter) * (nearestY - yCenter) + return dist <= radius * radius +} diff --git a/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.java b/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.java new file mode 100644 index 00000000..3ecca3bb --- /dev/null +++ b/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.java @@ -0,0 +1,8 @@ +class Solution { + public boolean checkOverlap(int radius, int xCenter, int yCenter, int x1, int y1, int x2, int y2) { + int nearestX = Math.max(x1, Math.min(x2, xCenter)); + int nearestY = Math.max(y1, Math.min(y2, yCenter)); + int dist = (nearestX - xCenter) * (nearestX - xCenter) + (nearestY - yCenter) * (nearestY - yCenter); + return dist <= radius * radius; + } +} diff --git a/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.kt b/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.kt new file mode 100644 index 00000000..a579cde7 --- /dev/null +++ b/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.kt @@ -0,0 +1,8 @@ +class Solution { + fun checkOverlap(radius: Int, xCenter: Int, yCenter: Int, x1: Int, y1: Int, x2: Int, y2: Int): Boolean { + val nearestX = maxOf(x1, minOf(x2, xCenter)) + val nearestY = maxOf(y1, minOf(y2, yCenter)) + val dist = (nearestX - xCenter) * (nearestX - xCenter) + (nearestY - yCenter) * (nearestY - yCenter) + return dist <= radius * radius + } +} diff --git a/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.py b/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.py new file mode 100644 index 00000000..13fa5b94 --- /dev/null +++ b/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.py @@ -0,0 +1,16 @@ +class Solution: + def checkOverlap( + self, + radius: int, + xCenter: int, + yCenter: int, + x1: int, + y1: int, + x2: int, + y2: int, + ) -> bool: + nearestX = max(x1, min(x2, xCenter)) + nearestY = max(y1, min(y2, yCenter)) + + dist = (nearestX - xCenter) ** 2 + (nearestY - yCenter) ** 2 + return dist <= radius * radius diff --git a/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.py2 b/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.py2 new file mode 100644 index 00000000..78ce973b --- /dev/null +++ b/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def checkOverlap(self, radius, xCenter, yCenter, x1, y1, x2, y2): + """ + :type radius: int + :type xCenter: int + :type yCenter: int + :type x1: int + :type y1: int + :type x2: int + :type y2: int + :rtype: bool + """ + nearestX = max(x1, min(x2, xCenter)) + nearestY = max(y1, min(y2, yCenter)) + dist = (nearestX - xCenter) ** 2 + (nearestY - yCenter) ** 2 + return dist <= radius * radius diff --git a/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.rb b/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.rb new file mode 100644 index 00000000..3a00d8d4 --- /dev/null +++ b/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.rb @@ -0,0 +1,14 @@ +# @param {Integer} radius +# @param {Integer} x_center +# @param {Integer} y_center +# @param {Integer} x1 +# @param {Integer} y1 +# @param {Integer} x2 +# @param {Integer} y2 +# @return {Boolean} +def check_overlap(radius, x_center, y_center, x1, y1, x2, y2) + nearest_x = [x1, [x2, x_center].min].max + nearest_y = [y1, [y2, y_center].min].max + dist = (nearest_x - x_center) ** 2 + (nearest_y - y_center) ** 2 + dist <= radius * radius +end diff --git a/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.rs b/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.rs new file mode 100644 index 00000000..c49ae3cd --- /dev/null +++ b/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.rs @@ -0,0 +1,8 @@ +impl Solution { + pub fn check_overlap(radius: i32, x_center: i32, y_center: i32, x1: i32, y1: i32, x2: i32, y2: i32) -> bool { + let nearest_x = x1.max(x2.min(x_center)); + let nearest_y = y1.max(y2.min(y_center)); + let dist = (nearest_x - x_center).pow(2) + (nearest_y - y_center).pow(2); + dist <= radius * radius + } +} diff --git a/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.swift b/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.swift new file mode 100644 index 00000000..7d27d390 --- /dev/null +++ b/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.swift @@ -0,0 +1,8 @@ +class Solution { + func checkOverlap(_ radius: Int, _ xCenter: Int, _ yCenter: Int, _ x1: Int, _ y1: Int, _ x2: Int, _ y2: Int) -> Bool { + let nearestX = max(x1, min(x2, xCenter)) + let nearestY = max(y1, min(y2, yCenter)) + let dist = (nearestX - xCenter) * (nearestX - xCenter) + (nearestY - yCenter) * (nearestY - yCenter) + return dist <= radius * radius + } +} diff --git a/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.ts b/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.ts new file mode 100644 index 00000000..0d88ebc6 --- /dev/null +++ b/tests/1001-1500/1401. circle-and-rectangle-overlapping/sol.ts @@ -0,0 +1,14 @@ +function checkOverlap( + radius: number, + xCenter: number, + yCenter: number, + x1: number, + y1: number, + x2: number, + y2: number, +): boolean { + const nearestX = Math.max(x1, Math.min(x2, xCenter)); + const nearestY = Math.max(y1, Math.min(y2, yCenter)); + const dist = (nearestX - xCenter) ** 2 + (nearestY - yCenter) ** 2; + return dist <= radius * radius; +} diff --git a/tests/1001-1500/1402. reducing-dishes/manifest.yaml b/tests/1001-1500/1402. reducing-dishes/manifest.yaml new file mode 100644 index 00000000..80e05a11 --- /dev/null +++ b/tests/1001-1500/1402. reducing-dishes/manifest.yaml @@ -0,0 +1,236 @@ +entry: + id: 1402 + title: reducing-dishes + params: + satisfaction: + type: array + items: + type: int + call: + cpp: "Solution().maxSatisfaction({satisfaction})" + rust: "Solution::max_satisfaction({satisfaction})" + python3: "Solution().maxSatisfaction({satisfaction})" + python2: "Solution().maxSatisfaction({satisfaction})" + ruby: "max_satisfaction({satisfaction})" + java: "new Solution().maxSatisfaction({satisfaction})" + csharp: "new Solution().MaxSatisfaction({satisfaction})" + kotlin: "Solution().maxSatisfaction({satisfaction})" + go: "maxSatisfaction({satisfaction})" + dart: "Solution().maxSatisfaction({satisfaction})" + swift: "Solution().maxSatisfaction({satisfaction})" + typescript: "maxSatisfaction({satisfaction})" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().maxSatisfaction(satisfaction, {result})" + checker: | + class Checker: + def maxSatisfaction(self, satisfaction, result): + values = sorted(satisfaction) + neg_inf = -10**18 + dp = [neg_inf] * (len(values) + 1) + dp[0] = 0 + for value in values: + for count in range(len(values), 0, -1): + if dp[count - 1] != neg_inf: + candidate = dp[count - 1] + count * value + if candidate > dp[count]: + dp[count] = candidate + best = max(dp) + return type(result) is int and result == best +seed: 1402 +tests: + - name: example-one + in: + satisfaction: [-1, -8, 0, 5, -9] + out: 14 + - name: example-two + in: + satisfaction: [4, 3, 2] + out: 20 + - name: example-three + in: + satisfaction: [-1, -4, -5] + out: 0 + - name: one-positive + in: + satisfaction: [1000] + out: 1000 + - name: one-negative + in: + satisfaction: [-1000] + out: 0 + - name: one-zero + in: + satisfaction: [0] + out: 0 + - name: two-positive + in: + satisfaction: [1, 2] + out: 5 + - name: mixed-pair + in: + satisfaction: [-1, 5] + out: 9 + - name: zero-and-positive + in: + satisfaction: [0, 7] + out: 14 + - name: all-positive + in: + satisfaction: [1, 2, 3, 4, 5] + out: 55 + - name: all-negative + in: + satisfaction: [-1, -2, -3, -4, -5] + out: 0 + - name: all-zero + in: + satisfaction: [0, 0, 0, 0] + out: 0 + - name: one-useful-positive + in: + satisfaction: [10, -100, -100] + out: 10 + - name: negative-threshold-kept + in: + satisfaction: [4, -1, -1] + out: 9 + - name: negative-threshold-rejected + in: + satisfaction: [5, -3, -3] + out: 7 + - name: input-ascending + in: + satisfaction: [1, 2, 3, 4, 5] + out: 55 + - name: alternating-signs + in: + satisfaction: [10, -1, 9, -2, 8, -3] + out: 127 + - name: late-positive-values + in: + satisfaction: [-10, -5, 1, 2, 3] + out: 15 + - name: zeros-between-values + in: + satisfaction: [-1, 0, 0, 4] + out: 15 + - name: duplicate-positive + in: + satisfaction: [3, 3, 3, 3] + out: 30 + - name: duplicate-negative + in: + satisfaction: [-2, -2, -2, -2] + out: 0 + - name: balanced-values + in: + satisfaction: [-3, -2, 1, 2, 3] + out: 19 + - name: exact-zero-prefix + in: + satisfaction: [-2, -1, 1, 2] + out: 7 + - name: large-positive-bound + in: + satisfaction: [1000, 1000, 1000, 1000] + out: 10000 + - name: large-negative-bound + in: + satisfaction: [-1000, -1000, -1000, 1000] + out: 1000 + - name: five-value-mix + in: + satisfaction: [-9, -1, 0, 1, 6] + out: 26 + - name: seven-value-mix + in: + satisfaction: [-4, 1, 2, 3, -1, 5, -2] + out: 56 + - name: eight-value-mix + in: + satisfaction: [8, -7, 6, -5, 4, -3, 2, -1] + out: 110 + - name: nine-value-mix + in: + satisfaction: [-9, -1, 0, 1, 2, 3, 4, 5, 6] + out: 143 + - name: ten-value-mix + in: + satisfaction: [10, 9, -8, 7, -6, 5, -4, 3, -2, 1] + out: 255 + - name: zero-with-negative-only + in: + satisfaction: [-2, -3, 0] + out: 0 + - name: high-values-with-negatives + in: + satisfaction: [1000, -999, 999, -998] + out: 4002 + - name: four-small-negatives + in: + satisfaction: [6, -1, -1, -1, -1] + out: 20 + - name: many-positive-duplicates + in: + satisfaction: [2, 2, 2, 2, 2, 2] + out: 42 + - name: boundary-symmetric-mix + in: + satisfaction: [-1000, -500, -1, 0, 1, 500, 1000] + out: 8002 + - name: generated-small + in: + satisfaction: + gen: array + len: 12 + of: + gen: int + min: -1000 + max: 1000 + elemType: int + - name: generated-medium + in: + satisfaction: + gen: array + len: 50 + of: + gen: int + min: -1000 + max: 1000 + elemType: int + - name: generated-boundary-values + in: + satisfaction: + gen: array + len: 100 + of: + gen: int + min: -1000 + max: 1000 + elemType: int + - name: generated-large + in: + satisfaction: + gen: array + len: 400 + of: + gen: int + min: -1000 + max: 1000 + elemType: int + - name: generated-maximum + in: + satisfaction: + gen: array + len: 500 + of: + gen: int + min: -1000 + max: 1000 + elemType: int diff --git a/tests/1001-1500/1402. reducing-dishes/sol.cpp b/tests/1001-1500/1402. reducing-dishes/sol.cpp new file mode 100644 index 00000000..53d30f24 --- /dev/null +++ b/tests/1001-1500/1402. reducing-dishes/sol.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + int maxSatisfaction(vector& satisfaction) { + sort(satisfaction.begin(), satisfaction.end(), greater()); + int presum = 0, res = 0; + for (int s : satisfaction) { + presum += s; + if (presum < 0) break; + res += presum; + } + return res; + } +}; diff --git a/tests/1001-1500/1402. reducing-dishes/sol.cs b/tests/1001-1500/1402. reducing-dishes/sol.cs new file mode 100644 index 00000000..8f1239d9 --- /dev/null +++ b/tests/1001-1500/1402. reducing-dishes/sol.cs @@ -0,0 +1,12 @@ +public class Solution { + public int MaxSatisfaction(int[] satisfaction) { + Array.Sort(satisfaction, (a, b) => b.CompareTo(a)); + int presum = 0, res = 0; + foreach (int s in satisfaction) { + presum += s; + if (presum < 0) break; + res += presum; + } + return res; + } +} diff --git a/tests/1001-1500/1402. reducing-dishes/sol.dart b/tests/1001-1500/1402. reducing-dishes/sol.dart new file mode 100644 index 00000000..5ef173b4 --- /dev/null +++ b/tests/1001-1500/1402. reducing-dishes/sol.dart @@ -0,0 +1,12 @@ +class Solution { + int maxSatisfaction(List satisfaction) { + satisfaction.sort((a, b) => b.compareTo(a)); + int presum = 0, res = 0; + for (int s in satisfaction) { + presum += s; + if (presum < 0) break; + res += presum; + } + return res; + } +} diff --git a/tests/1001-1500/1402. reducing-dishes/sol.go b/tests/1001-1500/1402. reducing-dishes/sol.go new file mode 100644 index 00000000..ac156683 --- /dev/null +++ b/tests/1001-1500/1402. reducing-dishes/sol.go @@ -0,0 +1,12 @@ +func maxSatisfaction(satisfaction []int) int { + sort.Sort(sort.Reverse(sort.IntSlice(satisfaction))) + presum, res := 0, 0 + for _, s := range satisfaction { + presum += s + if presum < 0 { + break + } + res += presum + } + return res +} diff --git a/tests/1001-1500/1402. reducing-dishes/sol.java b/tests/1001-1500/1402. reducing-dishes/sol.java new file mode 100644 index 00000000..2e545512 --- /dev/null +++ b/tests/1001-1500/1402. reducing-dishes/sol.java @@ -0,0 +1,12 @@ +class Solution { + public int maxSatisfaction(int[] satisfaction) { + Arrays.sort(satisfaction); + int presum = 0, res = 0; + for (int i = satisfaction.length - 1; i >= 0; i--) { + presum += satisfaction[i]; + if (presum < 0) break; + res += presum; + } + return res; + } +} diff --git a/tests/1001-1500/1402. reducing-dishes/sol.kt b/tests/1001-1500/1402. reducing-dishes/sol.kt new file mode 100644 index 00000000..0dd9407a --- /dev/null +++ b/tests/1001-1500/1402. reducing-dishes/sol.kt @@ -0,0 +1,13 @@ +class Solution { + fun maxSatisfaction(satisfaction: IntArray): Int { + satisfaction.sortDescending() + var presum = 0 + var res = 0 + for (s in satisfaction) { + presum += s + if (presum < 0) break + res += presum + } + return res + } +} diff --git a/tests/1001-1500/1402. reducing-dishes/sol.py b/tests/1001-1500/1402. reducing-dishes/sol.py new file mode 100644 index 00000000..fb48d8c2 --- /dev/null +++ b/tests/1001-1500/1402. reducing-dishes/sol.py @@ -0,0 +1,14 @@ +from typing import List + + +class Solution: + def maxSatisfaction(self, satisfaction: List[int]) -> int: + satisfaction.sort(reverse=True) + n = len(satisfaction) + presum, res = 0, 0 + for i in range(n): + presum += satisfaction[i] + if presum < 0: + break + res += presum + return res diff --git a/tests/1001-1500/1402. reducing-dishes/sol.py2 b/tests/1001-1500/1402. reducing-dishes/sol.py2 new file mode 100644 index 00000000..be26ebde --- /dev/null +++ b/tests/1001-1500/1402. reducing-dishes/sol.py2 @@ -0,0 +1,14 @@ +class Solution(object): + def maxSatisfaction(self, satisfaction): + """ + :type satisfaction: List[int] + :rtype: int + """ + satisfaction.sort(reverse=True) + presum, res = 0, 0 + for s in satisfaction: + presum += s + if presum < 0: + break + res += presum + return res diff --git a/tests/1001-1500/1402. reducing-dishes/sol.rb b/tests/1001-1500/1402. reducing-dishes/sol.rb new file mode 100644 index 00000000..c9d100ff --- /dev/null +++ b/tests/1001-1500/1402. reducing-dishes/sol.rb @@ -0,0 +1,13 @@ +# @param {Integer[]} satisfaction +# @return {Integer} +def max_satisfaction(satisfaction) + satisfaction.sort!.reverse! + presum = 0 + res = 0 + satisfaction.each do |s| + presum += s + break if presum < 0 + res += presum + end + res +end diff --git a/tests/1001-1500/1402. reducing-dishes/sol.rs b/tests/1001-1500/1402. reducing-dishes/sol.rs new file mode 100644 index 00000000..375dee46 --- /dev/null +++ b/tests/1001-1500/1402. reducing-dishes/sol.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn max_satisfaction(mut satisfaction: Vec) -> i32 { + satisfaction.sort_unstable_by(|a, b| b.cmp(a)); + let mut presum = 0; + let mut res = 0; + for s in satisfaction { + presum += s; + if presum < 0 { + break; + } + res += presum; + } + res + } +} diff --git a/tests/1001-1500/1402. reducing-dishes/sol.swift b/tests/1001-1500/1402. reducing-dishes/sol.swift new file mode 100644 index 00000000..cd5d3fd9 --- /dev/null +++ b/tests/1001-1500/1402. reducing-dishes/sol.swift @@ -0,0 +1,12 @@ +class Solution { + func maxSatisfaction(_ satisfaction: [Int]) -> Int { + var satisfaction = satisfaction.sorted(by: >) + var presum = 0, res = 0 + for s in satisfaction { + presum += s + if presum < 0 { break } + res += presum + } + return res + } +} diff --git a/tests/1001-1500/1402. reducing-dishes/sol.ts b/tests/1001-1500/1402. reducing-dishes/sol.ts new file mode 100644 index 00000000..3af18610 --- /dev/null +++ b/tests/1001-1500/1402. reducing-dishes/sol.ts @@ -0,0 +1,11 @@ +function maxSatisfaction(satisfaction: number[]): number { + satisfaction.sort((a, b) => b - a); + let presum = 0, + res = 0; + for (const s of satisfaction) { + presum += s; + if (presum < 0) break; + res += presum; + } + return res; +} diff --git a/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/manifest.yaml b/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/manifest.yaml new file mode 100644 index 00000000..4445d0e0 --- /dev/null +++ b/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/manifest.yaml @@ -0,0 +1,261 @@ +entry: + id: 1403 + title: "minimum-subsequence-in-non-increasing-order" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().minSubsequence({nums})" + rust: "Solution::min_subsequence({nums})" + python3: "Solution().minSubsequence({nums})" + python2: "Solution().minSubsequence({nums})" + ruby: "min_subsequence({nums})" + java: "new Solution().minSubsequence({nums})" + csharp: "new Solution().MinSubsequence({nums})" + kotlin: "Solution().minSubsequence({nums})" + go: "minSubsequence({nums})" + dart: "Solution().minSubsequence({nums})" + swift: "Solution().minSubsequence({nums})" + typescript: "minSubsequence({nums})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().minSubsequence(nums, {result})" + checker: | + class Checker: + def minSubsequence(self, nums, result): + if not isinstance(result, list) or not result: + return False + if any(not isinstance(value, int) for value in result): + return False + if result != sorted(result, reverse=True): + return False + available = list(nums) + for value in result: + if value not in available: + return False + available.remove(value) + chosen_sum = sum(result) + if chosen_sum <= sum(available): + return False + ordered = sorted(nums, reverse=True) + minimum_size = None + for size in range(1, len(ordered) + 1): + if sum(ordered[:size]) > sum(ordered[size:]): + minimum_size = size + break + if len(result) != minimum_size: + return False + return chosen_sum == sum(ordered[:minimum_size]) + +seed: 1403 + +tests: + - name: "example-one" + in: + nums: [4, 3, 10, 9, 8] + - name: "example-two" + in: + nums: [4, 4, 7, 6, 7] + - name: "single-one" + in: + nums: [1] + - name: "single-hundred" + in: + nums: [100] + - name: "two-equal" + in: + nums: [5, 5] + - name: "two-unequal" + in: + nums: [9, 1] + - name: "all-ones-three" + in: + nums: [1, 1, 1] + - name: "all-ones-four" + in: + nums: [1, 1, 1, 1] + - name: "strictly-increasing" + in: + nums: [1, 2, 3, 4, 5, 6] + - name: "strictly-decreasing" + in: + nums: [10, 9, 8, 7, 6, 5] + - name: "already-sorted" + in: + nums: [100, 90, 80, 70, 60] + - name: "reverse-sorted" + in: + nums: [2, 9, 1, 8, 3, 7] + - name: "dominant-maximum" + in: + nums: [100, 1, 1, 1, 1, 1] + - name: "dominant-pair" + in: + nums: [99, 98, 1, 1, 1, 1, 1] + - name: "half-sum-boundary" + in: + nums: [8, 4, 4] + - name: "equal-largest-tie" + in: + nums: [8, 8, 4, 4] + - name: "three-largest-needed" + in: + nums: [7, 7, 7, 1, 1, 1, 1] + - name: "many-fours" + in: + nums: [4, 4, 4, 4, 4, 4, 4] + - name: "mixed-small" + in: + nums: [2, 5, 1, 9, 3, 6] + - name: "mixed-medium" + in: + nums: [11, 2, 19, 7, 13, 5, 17] + - name: "near-maximum-values" + in: + nums: [100, 99, 98, 97, 1, 2, 3] + - name: "balanced-pairs" + in: + nums: [10, 10, 9, 9, 8, 8] + - name: "repeated-high" + in: + nums: [20, 20, 20, 3, 3, 3, 3, 3] + - name: "one-through-ten" + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + - name: "ten-equal" + in: + nums: [10, 10, 10, 10, 10, 10, 10, 10, 10, 10] + - name: "alternating-extremes" + in: + nums: [100, 1, 99, 2, 98, 3, 97, 4] + - name: "large-tail" + in: + nums: [50, 49, 48, 47, 46, 1, 1, 1, 1, 1, 1, 1] + - name: "small-leading" + in: + nums: [1, 100, 2, 99, 3, 98, 4, 97] + - name: "multiples-of-seven" + in: + nums: [7, 14, 21, 28, 35, 42, 49] + - name: "mixed-duplicates" + in: + nums: [6, 6, 5, 5, 4, 4, 3, 3, 2, 1] + - name: "twenty-values" + in: + nums: + [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20] + - name: "maximum-bound-values" + in: + nums: [100, 100, 100, 100, 100, 1, 1, 1, 1, 1] + - name: "long-flat-tail" + in: + nums: [30, 29, 28, 27, 26, 25, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - name: "thirty-one-elements" + 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, + ] + - name: "large-mixed" + in: + nums: [100, 1, 50, 2, 75, 3, 25, 4, 90, 5, 60, 6, 40, 7, 80, 8] + - name: "generated-small-range" + seed: 14031 + in: + nums: + gen: "array" + len: 17 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + elemType: "int" + - name: "generated-medium-range" + seed: 14032 + in: + nums: + gen: "array" + len: 64 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + elemType: "int" + - name: "generated-all-minimum" + seed: 14033 + in: + nums: + gen: "array" + len: 500 + of: + gen: "int" + min: 1 + max: 1 + distinct: false + elemType: "int" + - name: "generated-all-maximum" + seed: 14034 + in: + nums: + gen: "array" + len: 500 + of: + gen: "int" + min: 100 + max: 100 + distinct: false + elemType: "int" + - name: "generated-full-range" + seed: 14035 + in: + nums: + gen: "array" + len: 499 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + elemType: "int" diff --git a/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.cpp b/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.cpp new file mode 100644 index 00000000..0a8b1be5 --- /dev/null +++ b/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + vector minSubsequence(vector& nums) { + sort(nums.begin(), nums.end()); + vector v; + int l = nums.size(); + int sumV = 0, sumRem = accumulate(nums.begin(), nums.end(), 0); + while (sumV <= sumRem) { + l--; + sumV += nums[l]; + sumRem -= nums[l]; + v.push_back(nums[l]); + } + return v; + } +}; diff --git a/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.cs b/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.cs new file mode 100644 index 00000000..5cad52f3 --- /dev/null +++ b/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.cs @@ -0,0 +1,15 @@ +public class Solution { + public IList MinSubsequence(int[] nums) { + Array.Sort(nums); + var v = new List(); + int l = nums.Length; + int sumV = 0, sumRem = nums.Sum(); + while (sumV <= sumRem) { + l--; + sumV += nums[l]; + sumRem -= nums[l]; + v.Add(nums[l]); + } + return v; + } +} diff --git a/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.dart b/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.dart new file mode 100644 index 00000000..1fed0e7e --- /dev/null +++ b/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.dart @@ -0,0 +1,15 @@ +class Solution { + List minSubsequence(List nums) { + nums.sort(); + List v = []; + int l = nums.length; + int sumV = 0, sumRem = nums.reduce((a, b) => a + b); + while (sumV <= sumRem) { + l--; + sumV += nums[l]; + sumRem -= nums[l]; + v.add(nums[l]); + } + return v; + } +} diff --git a/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.go b/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.go new file mode 100644 index 00000000..c82b2743 --- /dev/null +++ b/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.go @@ -0,0 +1,16 @@ +func minSubsequence(nums []int) []int { + sort.Ints(nums) + v := []int{} + l := len(nums) + sumV, sumRem := 0, 0 + for _, x := range nums { + sumRem += x + } + for sumV <= sumRem { + l-- + sumV += nums[l] + sumRem -= nums[l] + v = append(v, nums[l]) + } + return v +} diff --git a/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.java b/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.java new file mode 100644 index 00000000..cba836da --- /dev/null +++ b/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.java @@ -0,0 +1,16 @@ +class Solution { + public List minSubsequence(int[] nums) { + Arrays.sort(nums); + List v = new ArrayList<>(); + int l = nums.length; + int sumV = 0, sumRem = 0; + for (int i = 0; i < l; i++) sumRem += nums[i]; + while (sumV <= sumRem) { + l--; + sumV += nums[l]; + sumRem -= nums[l]; + v.add(nums[l]); + } + return v; + } +} diff --git a/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.kt b/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.kt new file mode 100644 index 00000000..b8f73388 --- /dev/null +++ b/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun minSubsequence(nums: IntArray): List { + nums.sort() + val v = mutableListOf() + var l = nums.size + var sumV = 0 + var sumRem = nums.sum() + while (sumV <= sumRem) { + l-- + sumV += nums[l] + sumRem -= nums[l] + v.add(nums[l]) + } + return v + } +} diff --git a/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.py b/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.py new file mode 100644 index 00000000..801d6283 --- /dev/null +++ b/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.py @@ -0,0 +1,10 @@ +class Solution(object): + def minSubsequence(self, nums): + s = sorted(nums) + v = [] + l = len(nums) + while sum(v) <= sum(s[:l]): + l -= 1 + v.append(s[l]) + + return v diff --git a/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.py2 b/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.py2 new file mode 100644 index 00000000..93448cc7 --- /dev/null +++ b/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.py2 @@ -0,0 +1,10 @@ +class Solution(object): + def minSubsequence(self, nums): + s=sorted(nums) + v=[] + l=len(nums) + while sum(v)<=sum(s[:l]): + l-=1 + v.append(s[l]) + + return v diff --git a/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.rb b/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.rb new file mode 100644 index 00000000..9195cb6d --- /dev/null +++ b/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.rb @@ -0,0 +1,12 @@ +# @param {Integer[]} nums +# @return {Integer[]} +def min_subsequence(nums) + s = nums.sort + v = [] + l = nums.length + while v.sum <= s[0...l].sum + l -= 1 + v << s[l] + end + v +end diff --git a/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.rs b/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.rs new file mode 100644 index 00000000..dca17d1d --- /dev/null +++ b/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.rs @@ -0,0 +1,17 @@ +impl Solution { + pub fn min_subsequence(nums: Vec) -> Vec { + let mut s = nums.clone(); + s.sort(); + let mut v = Vec::new(); + let mut l = s.len(); + let mut sum_v = 0; + let mut sum_rem: i32 = s.iter().sum(); + while sum_v <= sum_rem { + l -= 1; + sum_v += s[l]; + sum_rem -= s[l]; + v.push(s[l]); + } + v + } +} diff --git a/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.swift b/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.swift new file mode 100644 index 00000000..c60e48e1 --- /dev/null +++ b/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.swift @@ -0,0 +1,15 @@ +class Solution { + func minSubsequence(_ nums: [Int]) -> [Int] { + var s = nums.sorted() + var v = [Int]() + var l = nums.count + var sumV = 0, sumRem = s.reduce(0, +) + while sumV <= sumRem { + l -= 1 + sumV += s[l] + sumRem -= s[l] + v.append(s[l]) + } + return v + } +} diff --git a/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.ts b/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.ts new file mode 100644 index 00000000..946566d7 --- /dev/null +++ b/tests/1001-1500/1403. minimum-subsequence-in-non-increasing-order/sol.ts @@ -0,0 +1,14 @@ +function minSubsequence(nums: number[]): number[] { + nums.sort((a, b) => a - b); + const v: number[] = []; + let l = nums.length; + let sumV = 0, + sumRem = nums.reduce((a, b) => a + b, 0); + while (sumV <= sumRem) { + l--; + sumV += nums[l]; + sumRem -= nums[l]; + v.push(nums[l]); + } + return v; +} diff --git a/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/manifest.yaml b/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/manifest.yaml new file mode 100644 index 00000000..0774dc5a --- /dev/null +++ b/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/manifest.yaml @@ -0,0 +1,153 @@ +entry: + id: 1404 + title: "number-of-steps-to-reduce-a-number-in-binary-representation-to-one" + params: + s: + type: string + call: + cpp: "Solution().numSteps({s})" + rust: "Solution::num_steps({s})" + python3: "Solution().numSteps({s})" + python2: "Solution().numSteps({s})" + ruby: "num_steps({s})" + java: "new Solution().numSteps({s})" + csharp: "new Solution().NumSteps({s})" + kotlin: "Solution().numSteps({s})" + go: "numSteps({s})" + dart: "Solution().numSteps({s})" + swift: "Solution().numSteps({s})" + typescript: "numSteps({s})" +judge: + type: "exact" +limits: + time_ms: 400 + memory_mb: 300 +oracle: + python3: + call: "Checker().numSteps(s, {result})" + checker: | + class Checker: + def numSteps(self, s, result): + if not isinstance(result, int) or isinstance(result, bool) or result < 0: + return False + value = int(s, 2) + expected = 0 + while value > 1: + if value % 2 == 0: + value //= 2 + else: + value += 1 + expected += 1 + return result == expected + +seed: 1404001 + +tests: + - name: "example_1101" + in: + s: "1101" + - name: "example_10" + in: + s: "10" + - name: "example_1" + in: + s: "1" + - name: "three" + in: + s: "11" + - name: "four" + in: + s: "100" + - name: "five" + in: + s: "101" + - name: "six" + in: + s: "110" + - name: "seven" + in: + s: "111" + - name: "eight" + in: + s: "1000" + - name: "nine" + in: + s: "1001" + - name: "fifteen" + in: + s: "1111" + - name: "sixteen" + in: + s: "10000" + - name: "power_of_two_large" + in: + s: "1000000000000000" + - name: "all_ones_short" + in: + s: "11111111" + - name: "all_ones_medium" + in: + s: "1111111111111111" + - name: "alternating_start_one" + in: + s: "1010101010101010" + - name: "alternating_start_one_odd" + in: + s: "10101010101010101" + - name: "trailing_zeros" + in: + s: "111100000000" + - name: "single_one_near_end" + in: + s: "100000000001" + - name: "carry_chain" + in: + s: "101111111111" + - name: "carry_chain_short" + in: + s: "11101" + - name: "sparse_bits" + in: + s: "1001001001001" + - name: "dense_mixed" + in: + s: "110110011011" + - name: "leading_one_many_zeroes" + in: + s: "10000000000000000001" + - name: "leading_one_many_ones" + in: + s: "11111111111111111111" + - name: "alternating_32" + in: + s: "10101010101010101010101010101010" + - name: "alternating_33" + in: + s: "101010101010101010101010101010101" + - name: "power_boundary_31" + in: + s: "1000000000000000000000000000000" + - name: "power_minus_one_31" + in: + s: "1111111111111111111111111111111" + - name: "mixed_40" + in: + s: "1100101011110001010011010111000110110011" + - name: "mixed_48" + in: + s: "100111011001010111110000101010110011011101001011" + - name: "sparse_64" + in: + s: "1000000000000001000000000000000100000000000000010000000000000001" + - name: "all_ones_64" + in: + s: "1111111111111111111111111111111111111111111111111111111111111111" + - name: "long_carry_pattern" + in: + s: "1011111111111111111111111111111111111111111111111111" + - name: "long_alternating_pattern" + in: + s: "1010101010101010101010101010101010101010101010101010101010101010101010101010" + - name: "stress_500_ones" + in: + s: "1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111" diff --git a/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.cpp b/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.cpp new file mode 100644 index 00000000..bfd2db92 --- /dev/null +++ b/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int numSteps(string s) { + int steps = 0; + int carry = 0; + + for (int i = s.length() - 1; i > 0; i--) { + int bit = (s[i] - '0') + carry; + + if (bit == 1) { + steps += 2; + carry = 1; + } else { + steps += 1; + } + } + + return steps + carry; + } +}; diff --git a/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.cs b/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.cs new file mode 100644 index 00000000..424b682e --- /dev/null +++ b/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.cs @@ -0,0 +1,19 @@ +public class Solution { + public int NumSteps(string s) { + int steps = 0; + int carry = 0; + + for (int i = s.Length - 1; i > 0; i--) { + int bit = (s[i] - '0') + carry; + + if (bit == 1) { + steps += 2; + carry = 1; + } else { + steps += 1; + } + } + + return steps + carry; + } +} diff --git a/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.dart b/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.dart new file mode 100644 index 00000000..61b993af --- /dev/null +++ b/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.dart @@ -0,0 +1,19 @@ +class Solution { + int numSteps(String s) { + int steps = 0; + int carry = 0; + + for (int i = s.length - 1; i > 0; i--) { + int bit = int.parse(s[i]) + carry; + + if (bit == 1) { + steps += 2; + carry = 1; + } else { + steps += 1; + } + } + + return steps + carry; + } +} diff --git a/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.go b/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.go new file mode 100644 index 00000000..76134b80 --- /dev/null +++ b/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.go @@ -0,0 +1,17 @@ +func numSteps(s string) int { + steps := 0 + carry := 0 + + for i := len(s) - 1; i > 0; i-- { + bit := int(s[i]-'0') + carry + + if bit == 1 { + steps += 2 + carry = 1 + } else { + steps += 1 + } + } + + return steps + carry +} diff --git a/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.java b/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.java new file mode 100644 index 00000000..1e349c8f --- /dev/null +++ b/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.java @@ -0,0 +1,19 @@ +class Solution { + public int numSteps(String s) { + int steps = 0; + int carry = 0; + + for (int i = s.length() - 1; i > 0; i--) { + int bit = (s.charAt(i) - '0') + carry; + + if (bit == 1) { + steps += 2; + carry = 1; + } else { + steps += 1; + } + } + + return steps + carry; + } +} diff --git a/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.kt b/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.kt new file mode 100644 index 00000000..2226edd4 --- /dev/null +++ b/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.kt @@ -0,0 +1,19 @@ +class Solution { + fun numSteps(s: String): Int { + var steps = 0 + var carry = 0 + + for (i in s.length - 1 downTo 1) { + val bit = (s[i] - '0') + carry + + if (bit == 1) { + steps += 2 + carry = 1 + } else { + steps += 1 + } + } + + return steps + carry + } +} diff --git a/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.py b/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.py new file mode 100644 index 00000000..0ebfa376 --- /dev/null +++ b/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.py @@ -0,0 +1,15 @@ +class Solution: + def numSteps(self, s: str) -> int: + steps = 0 + carry = 0 + + for i in range(len(s) - 1, 0, -1): + bit = int(s[i]) + carry + + if bit == 1: + steps += 2 + carry = 1 + else: + steps += 1 + + return steps + carry diff --git a/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.py2 b/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.py2 new file mode 100644 index 00000000..5826cfe2 --- /dev/null +++ b/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.py2 @@ -0,0 +1,19 @@ +class Solution(object): + def numSteps(self, s): + """ + :type s: str + :rtype: int + """ + steps = 0 + carry = 0 + + for i in range(len(s) - 1, 0, -1): + bit = int(s[i]) + carry + + if bit == 1: + steps += 2 + carry = 1 + else: + steps += 1 + + return steps + carry diff --git a/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.rb b/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.rb new file mode 100644 index 00000000..24c5a791 --- /dev/null +++ b/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.rb @@ -0,0 +1,19 @@ +# @param {String} s +# @return {Integer} +def num_steps(s) + steps = 0 + carry = 0 + + (s.length - 1).downto(1) do |i| + bit = s[i].to_i + carry + + if bit == 1 + steps += 2 + carry = 1 + else + steps += 1 + end + end + + steps + carry +end diff --git a/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.rs b/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.rs new file mode 100644 index 00000000..da7c6009 --- /dev/null +++ b/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.rs @@ -0,0 +1,20 @@ +impl Solution { + pub fn num_steps(s: String) -> i32 { + let mut steps = 0; + let mut carry = 0; + let bytes = s.as_bytes(); + + for i in (1..bytes.len()).rev() { + let bit = (bytes[i] - b'0') as i32 + carry; + + if bit == 1 { + steps += 2; + carry = 1; + } else { + steps += 1; + } + } + + steps + carry + } +} diff --git a/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.swift b/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.swift new file mode 100644 index 00000000..2bb8f55f --- /dev/null +++ b/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func numSteps(_ s: String) -> Int { + var steps = 0 + var carry = 0 + let chars = Array(s) + + for i in stride(from: chars.count - 1, to: 0, by: -1) { + let bit = (Int(String(chars[i])) ?? 0) + carry + + if bit == 1 { + steps += 2 + carry = 1 + } else { + steps += 1 + } + } + + return steps + carry + } +} diff --git a/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.ts b/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.ts new file mode 100644 index 00000000..2e0abadc --- /dev/null +++ b/tests/1001-1500/1404. number-of-steps-to-reduce-a-number-in-binary-representation-to-one/sol.ts @@ -0,0 +1,17 @@ +function numSteps(s: string): number { + let steps = 0; + let carry = 0; + + for (let i = s.length - 1; i > 0; i--) { + const bit = parseInt(s[i]) + carry; + + if (bit === 1) { + steps += 2; + carry = 1; + } else { + steps += 1; + } + } + + return steps + carry; +} diff --git a/tests/1001-1500/1405. longest-happy-string/manifest.yaml b/tests/1001-1500/1405. longest-happy-string/manifest.yaml new file mode 100644 index 00000000..b306f5cf --- /dev/null +++ b/tests/1001-1500/1405. longest-happy-string/manifest.yaml @@ -0,0 +1,279 @@ +entry: + id: 1405 + title: "longest-happy-string" + params: + a: + type: int + b: + type: int + c: + type: int + call: + cpp: "Solution().longestDiverseString({a}, {b}, {c})" + rust: "Solution::longest_diverse_string({a}, {b}, {c})" + python3: "Solution().longestDiverseString({a}, {b}, {c})" + python2: "Solution().longestDiverseString({a}, {b}, {c})" + ruby: "longest_diverse_string({a}, {b}, {c})" + java: "new Solution().longestDiverseString({a}, {b}, {c})" + csharp: "new Solution().LongestDiverseString({a}, {b}, {c})" + kotlin: "Solution().longestDiverseString({a}, {b}, {c})" + go: "longestDiverseString({a}, {b}, {c})" + dart: "Solution().longestDiverseString({a}, {b}, {c})" + swift: "Solution().longestDiverseString({a}, {b}, {c})" + typescript: "longestDiverseString({a}, {b}, {c})" +judge: + type: "exact" +limits: + time_ms: 700 + memory_mb: 300 +oracle: + python3: + call: "Checker().longestDiverseString(a, b, c, {result})" + checker: | + class Checker: + def longestDiverseString(self, a, b, c, result): + if not isinstance(result, str): + return False + if any(ch not in "abc" for ch in result): + return False + counts = [result.count("a"), result.count("b"), result.count("c")] + if counts[0] > a or counts[1] > b or counts[2] > c: + return False + if "aaa" in result or "bbb" in result or "ccc" in result: + return False + total = a + b + c + largest = max(a, b, c) + optimum = min(total, 3 * (total - largest) + 2) + return len(result) == optimum +seed: 1405 +tests: + - name: "example_one" + in: + a: 1 + b: 1 + c: 7 + - name: "example_two" + in: + a: 7 + b: 1 + c: 0 + - name: "single_a" + in: + a: 1 + b: 0 + c: 0 + - name: "single_b" + in: + a: 0 + b: 1 + c: 0 + - name: "single_c" + in: + a: 0 + b: 0 + c: 1 + - name: "balanced_one" + in: + a: 1 + b: 1 + c: 1 + - name: "balanced_two" + in: + a: 2 + b: 2 + c: 2 + - name: "balanced_three" + in: + a: 3 + b: 3 + c: 3 + - name: "only_a_with_support" + in: + a: 5 + b: 1 + c: 0 + - name: "only_b_with_support" + in: + a: 1 + b: 5 + c: 0 + - name: "only_c_with_support" + in: + a: 1 + b: 0 + c: 5 + - name: "two_equal_letters" + in: + a: 8 + b: 8 + c: 0 + - name: "two_equal_other" + in: + a: 0 + b: 8 + c: 8 + - name: "two_equal_first" + in: + a: 8 + b: 0 + c: 8 + - name: "dominant_a_short" + in: + a: 7 + b: 1 + c: 1 + - name: "dominant_b_short" + in: + a: 1 + b: 7 + c: 1 + - name: "dominant_c_short" + in: + a: 1 + b: 1 + c: 7 + - name: "dominant_a_long" + in: + a: 20 + b: 1 + c: 1 + - name: "dominant_b_long" + in: + a: 1 + b: 20 + c: 1 + - name: "dominant_c_long" + in: + a: 1 + b: 1 + c: 20 + - name: "near_dominant_a" + in: + a: 10 + b: 4 + c: 4 + - name: "near_dominant_b" + in: + a: 4 + b: 10 + c: 4 + - name: "near_dominant_c" + in: + a: 4 + b: 4 + c: 10 + - name: "balanced_medium" + in: + a: 15 + b: 14 + c: 13 + - name: "balanced_large" + in: + a: 100 + b: 100 + c: 100 + - name: "mixed_a_heavy" + in: + a: 18 + b: 7 + c: 4 + - name: "mixed_b_heavy" + in: + a: 7 + b: 18 + c: 4 + - name: "mixed_c_heavy" + in: + a: 7 + b: 4 + c: 18 + - name: "mixed_a_light" + in: + a: 2 + b: 11 + c: 9 + - name: "mixed_b_light" + in: + a: 11 + b: 2 + c: 9 + - name: "mixed_c_light" + in: + a: 11 + b: 9 + c: 2 + - name: "max_a_with_two_support" + in: + a: 100 + b: 50 + c: 50 + - name: "max_b_with_two_support" + in: + a: 50 + b: 100 + c: 50 + - name: "max_c_with_two_support" + in: + a: 50 + b: 50 + c: 100 + - name: "max_a_one_support" + in: + a: 100 + b: 1 + c: 0 + - name: "generated_a_b_with_c" + in: + a: + gen: "int" + min: 0 + max: 100 + b: + gen: "int" + min: 0 + max: 100 + c: 1 + - name: "generated_b_c_with_a" + in: + a: 1 + b: + gen: "int" + min: 0 + max: 100 + c: + gen: "int" + min: 0 + max: 100 + - name: "generated_a_c_with_b" + in: + a: + gen: "int" + min: 0 + max: 100 + b: 1 + c: + gen: "int" + min: 0 + max: 100 + - name: "generated_small_support" + in: + a: + gen: "int" + min: 0 + max: 20 + b: + gen: "int" + min: 0 + max: 20 + c: 1 + - name: "generated_max_scale" + in: + a: + gen: "int" + min: 80 + max: 100 + b: + gen: "int" + min: 0 + max: 100 + c: 1 diff --git a/tests/1001-1500/1405. longest-happy-string/sol.cpp b/tests/1001-1500/1405. longest-happy-string/sol.cpp new file mode 100644 index 00000000..2743ed6e --- /dev/null +++ b/tests/1001-1500/1405. longest-happy-string/sol.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + string longestDiverseString(int a, int b, int c) { + priority_queue> maxHeap; + string res; + + if (a > 0) maxHeap.push({a, 'a'}); + if (b > 0) maxHeap.push({b, 'b'}); + if (c > 0) maxHeap.push({c, 'c'}); + + while (!maxHeap.empty()) { + auto [count, ch] = maxHeap.top(); + maxHeap.pop(); + + int len = res.size(); + if (len >= 2 && res[len - 2] == ch && res[len - 1] == ch) { + if (maxHeap.empty()) { + break; + } + auto [count2, ch2] = maxHeap.top(); + maxHeap.pop(); + res.push_back(ch2); + count2--; + if (count2 > 0) { + maxHeap.push({count2, ch2}); + } + } else { + res.push_back(ch); + count--; + } + + if (count > 0) { + maxHeap.push({count, ch}); + } + } + + return res; + } +}; diff --git a/tests/1001-1500/1405. longest-happy-string/sol.cs b/tests/1001-1500/1405. longest-happy-string/sol.cs new file mode 100644 index 00000000..0695ae08 --- /dev/null +++ b/tests/1001-1500/1405. longest-happy-string/sol.cs @@ -0,0 +1,19 @@ +public class Solution { + public string LongestDiverseString(int a, int b, int c) { + int[] counts = { a, b, c }; + char[] letters = { 'a', 'b', 'c' }; + var result = new System.Text.StringBuilder(); + while (true) { + int choice = -1; + for (int i = 0; i < 3; i++) { + if (counts[i] == 0) continue; + if (result.Length >= 2 && result[result.Length - 1] == letters[i] && result[result.Length - 2] == letters[i]) continue; + if (choice == -1 || counts[i] > counts[choice]) choice = i; + } + if (choice == -1) break; + result.Append(letters[choice]); + counts[choice]--; + } + return result.ToString(); + } +} diff --git a/tests/1001-1500/1405. longest-happy-string/sol.dart b/tests/1001-1500/1405. longest-happy-string/sol.dart new file mode 100644 index 00000000..df9bc88d --- /dev/null +++ b/tests/1001-1500/1405. longest-happy-string/sol.dart @@ -0,0 +1,19 @@ +class Solution { + String longestDiverseString(int a, int b, int c) { + final counts = [a, b, c]; + const letters = ['a', 'b', 'c']; + final result = []; + while (true) { + var choice = -1; + for (var i = 0; i < 3; i++) { + if (counts[i] == 0) continue; + if (result.length >= 2 && result[result.length - 1] == letters[i] && result[result.length - 2] == letters[i]) continue; + if (choice == -1 || counts[i] > counts[choice]) choice = i; + } + if (choice == -1) break; + result.add(letters[choice]); + counts[choice]--; + } + return result.join(); + } +} diff --git a/tests/1001-1500/1405. longest-happy-string/sol.go b/tests/1001-1500/1405. longest-happy-string/sol.go new file mode 100644 index 00000000..b10f1ff8 --- /dev/null +++ b/tests/1001-1500/1405. longest-happy-string/sol.go @@ -0,0 +1,64 @@ +func longestDiverseString(a int, b int, c int) string { + type Item struct { + count int + char byte + } + maxHeap := []Item{} + if a > 0 { + maxHeap = append(maxHeap, Item{a, 'a'}) + } + if b > 0 { + maxHeap = append(maxHeap, Item{b, 'b'}) + } + if c > 0 { + maxHeap = append(maxHeap, Item{c, 'c'}) + } + + var res []byte + + for len(maxHeap) > 0 { + // find max + maxIdx := 0 + for i := 1; i < len(maxHeap); i++ { + if maxHeap[i].count > maxHeap[maxIdx].count { + maxIdx = i + } + } + first := maxHeap[maxIdx] + maxHeap = append(maxHeap[:maxIdx], maxHeap[maxIdx+1:]...) + + count := first.count + ch := first.char + + if len(res) >= 2 && res[len(res)-2] == ch && res[len(res)-1] == ch { + if len(maxHeap) == 0 { + break + } + maxIdx2 := 0 + for i := 1; i < len(maxHeap); i++ { + if maxHeap[i].count > maxHeap[maxIdx2].count { + maxIdx2 = i + } + } + second := maxHeap[maxIdx2] + maxHeap = append(maxHeap[:maxIdx2], maxHeap[maxIdx2+1:]...) + + count2 := second.count + ch2 := second.char + res = append(res, ch2) + count2-- + if count2 > 0 { + maxHeap = append(maxHeap, Item{count2, ch2}) + } + } else { + res = append(res, ch) + count-- + } + + if count > 0 { + maxHeap = append(maxHeap, Item{count, ch}) + } + } + + return string(res) +} diff --git a/tests/1001-1500/1405. longest-happy-string/sol.java b/tests/1001-1500/1405. longest-happy-string/sol.java new file mode 100644 index 00000000..ff89529d --- /dev/null +++ b/tests/1001-1500/1405. longest-happy-string/sol.java @@ -0,0 +1,42 @@ +import java.util.PriorityQueue; + +class Solution { + public String longestDiverseString(int a, int b, int c) { + PriorityQueue maxHeap = new PriorityQueue<>((x, y) -> y[0] - x[0]); + StringBuilder res = new StringBuilder(); + + if (a > 0) maxHeap.add(new int[]{a, 'a'}); + if (b > 0) maxHeap.add(new int[]{b, 'b'}); + if (c > 0) maxHeap.add(new int[]{c, 'c'}); + + while (!maxHeap.isEmpty()) { + int[] first = maxHeap.poll(); + int count = first[0]; + char ch = (char) first[1]; + + int len = res.length(); + if (len >= 2 && res.charAt(len - 2) == ch && res.charAt(len - 1) == ch) { + if (maxHeap.isEmpty()) { + break; + } + int[] second = maxHeap.poll(); + int count2 = second[0]; + char ch2 = (char) second[1]; + res.append(ch2); + count2--; + if (count2 > 0) { + maxHeap.add(new int[]{count2, ch2}); + } + } else { + res.append(ch); + count--; + } + + if (count > 0) { + maxHeap.add(new int[]{count, ch}); + } + } + + return res.toString(); + } +} diff --git a/tests/1001-1500/1405. longest-happy-string/sol.kt b/tests/1001-1500/1405. longest-happy-string/sol.kt new file mode 100644 index 00000000..81ba0cbb --- /dev/null +++ b/tests/1001-1500/1405. longest-happy-string/sol.kt @@ -0,0 +1,37 @@ +import java.util.PriorityQueue + +class Solution { + fun longestDiverseString(a: Int, b: Int, c: Int): String { + val maxHeap = PriorityQueue>(compareByDescending { it.first }) + val res = StringBuilder() + + if (a > 0) maxHeap.add(a to 'a') + if (b > 0) maxHeap.add(b to 'b') + if (c > 0) maxHeap.add(c to 'c') + + while (maxHeap.isNotEmpty()) { + var (count, ch) = maxHeap.poll() + val len = res.length + if (len >= 2 && res[len - 2] == ch && res[len - 1] == ch) { + if (maxHeap.isEmpty()) { + break + } + var (count2, ch2) = maxHeap.poll() + res.append(ch2) + count2-- + if (count2 > 0) { + maxHeap.add(count2 to ch2) + } + } else { + res.append(ch) + count-- + } + + if (count > 0) { + maxHeap.add(count to ch) + } + } + + return res.toString() + } +} diff --git a/tests/1001-1500/1405. longest-happy-string/sol.py b/tests/1001-1500/1405. longest-happy-string/sol.py new file mode 100644 index 00000000..4e3ff21f --- /dev/null +++ b/tests/1001-1500/1405. longest-happy-string/sol.py @@ -0,0 +1,29 @@ +import heapq + + +class Solution: + def longestDiverseString(self, a: int, b: int, c: int) -> str: + heap = [] + res = [] + for count, char in zip([a, b, c], ["a", "b", "c"]): + if count > 0: + heapq.heappush(heap, (-count, char)) + + while heap: + count, char = heapq.heappop(heap) + if len(res) >= 2 and res[-2] == res[-1] == char: + if not heap: + break + count_2, char_2 = heapq.heappop(heap) + res.append(char_2) + count_2 += 1 + if count_2 < 0: + heapq.heappush(heap, (count_2, char_2)) + else: + res.append(char) + count += 1 + + if count < 0: + heapq.heappush(heap, (count, char)) + + return "".join(res) diff --git a/tests/1001-1500/1405. longest-happy-string/sol.py2 b/tests/1001-1500/1405. longest-happy-string/sol.py2 new file mode 100644 index 00000000..1e19fabd --- /dev/null +++ b/tests/1001-1500/1405. longest-happy-string/sol.py2 @@ -0,0 +1,33 @@ +class Solution(object): + def longestDiverseString(self, a, b, c): + """ + :type a: int + :type b: int + :type c: int + :rtype: str + """ + import heapq + heap = [] + res = [] + for count, char in zip([a, b, c], ["a", "b", "c"]): + if count > 0: + heapq.heappush(heap, (-count, char)) + + while heap: + count, char = heapq.heappop(heap) + if len(res) >= 2 and res[-2] == res[-1] == char: + if not heap: + break + count_2, char_2 = heapq.heappop(heap) + res.append(char_2) + count_2 += 1 + if count_2 < 0: + heapq.heappush(heap, (count_2, char_2)) + else: + res.append(char) + count += 1 + + if count < 0: + heapq.heappush(heap, (count, char)) + + return "".join(res) diff --git a/tests/1001-1500/1405. longest-happy-string/sol.rb b/tests/1001-1500/1405. longest-happy-string/sol.rb new file mode 100644 index 00000000..146c9107 --- /dev/null +++ b/tests/1001-1500/1405. longest-happy-string/sol.rb @@ -0,0 +1,36 @@ +# @param {Integer} a +# @param {Integer} b +# @param {Integer} c +# @return {String} +def longest_diverse_string(a, b, c) + heap = [] + res = [] + [['a', a], ['b', b], ['c', c]].each do |char, count| + heap << [-count, char] if count > 0 + end + heap.sort_by! { |x| x[0] } + + while !heap.empty? + count, char = heap.shift + if res.length >= 2 && res[-2] == res[-1] && res[-1] == char + break if heap.empty? + count_2, char_2 = heap.shift + res << char_2 + count_2 += 1 + if count_2 < 0 + heap << [count_2, char_2] + heap.sort_by! { |x| x[0] } + end + else + res << char + count += 1 + end + + if count < 0 + heap << [count, char] + heap.sort_by! { |x| x[0] } + end + end + + res.join +end diff --git a/tests/1001-1500/1405. longest-happy-string/sol.rs b/tests/1001-1500/1405. longest-happy-string/sol.rs new file mode 100644 index 00000000..29f57408 --- /dev/null +++ b/tests/1001-1500/1405. longest-happy-string/sol.rs @@ -0,0 +1,19 @@ +impl Solution { + pub fn longest_diverse_string(a: i32, b: i32, c: i32) -> String { + let mut counts = [a, b, c]; + let letters = ['a', 'b', 'c']; + let mut result: Vec = Vec::new(); + loop { + let mut choice: Option = None; + for index in 0..3 { + if counts[index] == 0 || (result.len() >= 2 && result[result.len() - 1] == letters[index] && result[result.len() - 2] == letters[index]) { continue; } + if choice.is_none() || counts[index] > counts[choice.unwrap()] { choice = Some(index); } + } + match choice { + Some(index) => { result.push(letters[index]); counts[index] -= 1; } + None => break, + } + } + result.into_iter().collect() + } +} diff --git a/tests/1001-1500/1405. longest-happy-string/sol.swift b/tests/1001-1500/1405. longest-happy-string/sol.swift new file mode 100644 index 00000000..d96761bc --- /dev/null +++ b/tests/1001-1500/1405. longest-happy-string/sol.swift @@ -0,0 +1,37 @@ +class Solution { + func longestDiverseString(_ a: Int, _ b: Int, _ c: Int) -> String { + var heap = [(Int, Character)]() + if a > 0 { heap.append((a, "a")) } + if b > 0 { heap.append((b, "b")) } + if c > 0 { heap.append((c, "c")) } + heap.sort { $0.0 > $1.0 } + + var res = [Character]() + + while !heap.isEmpty { + var (count, ch) = heap.removeFirst() + if res.count >= 2 && res[res.count - 2] == ch && res[res.count - 1] == ch { + if heap.isEmpty { + break + } + var (count2, ch2) = heap.removeFirst() + res.append(ch2) + count2 -= 1 + if count2 > 0 { + heap.append((count2, ch2)) + heap.sort { $0.0 > $1.0 } + } + } else { + res.append(ch) + count -= 1 + } + + if count > 0 { + heap.append((count, ch)) + heap.sort { $0.0 > $1.0 } + } + } + + return String(res) + } +} diff --git a/tests/1001-1500/1405. longest-happy-string/sol.ts b/tests/1001-1500/1405. longest-happy-string/sol.ts new file mode 100644 index 00000000..51c769a2 --- /dev/null +++ b/tests/1001-1500/1405. longest-happy-string/sol.ts @@ -0,0 +1,22 @@ +function longestDiverseString(a: number, b: number, c: number): string { + const counts = [a, b, c]; + const letters = ["a", "b", "c"]; + const result: string[] = []; + while (true) { + let choice = -1; + for (let index = 0; index < 3; index++) { + if (counts[index] === 0) continue; + if ( + result.length >= 2 && + result[result.length - 1] === letters[index] && + result[result.length - 2] === letters[index] + ) + continue; + if (choice === -1 || counts[index] > counts[choice]) choice = index; + } + if (choice === -1) break; + result.push(letters[choice]); + counts[choice]--; + } + return result.join(""); +} diff --git a/tests/1001-1500/1406. stone-game-iii/manifest.yaml b/tests/1001-1500/1406. stone-game-iii/manifest.yaml new file mode 100644 index 00000000..ecf637d2 --- /dev/null +++ b/tests/1001-1500/1406. stone-game-iii/manifest.yaml @@ -0,0 +1,276 @@ +entry: + id: 1406 + title: stone-game-iii + params: + stoneValue: + type: array + items: + type: int + call: + cpp: "Solution().stoneGameIII({stoneValue})" + rust: "Solution::stone_game_iii({stoneValue})" + python3: "Solution().stoneGameIII({stoneValue})" + python2: "Solution().stoneGameIII({stoneValue})" + ruby: "stone_game_iii({stoneValue})" + java: "new Solution().stoneGameIII({stoneValue})" + csharp: "new Solution().StoneGameIII({stoneValue})" + kotlin: "Solution().stoneGameIII({stoneValue})" + go: "stoneGameIII({stoneValue})" + dart: "Solution().stoneGameIII({stoneValue})" + swift: "Solution().stoneGameIII({stoneValue})" + typescript: "stoneGameIII({stoneValue})" +judge: + type: exact +limits: + time_ms: 1000 + memory_mb: 256 +oracle: + python3: + call: "Checker().stoneGameIII(stoneValue, {result})" + checker: | + class Checker: + def stoneGameIII(self, values, result): + if not isinstance(values, list) or not 1 <= len(values) <= 50000: + return False + if any(not isinstance(value, int) or isinstance(value, bool) or value < -1000 or value > 1000 for value in values): + return False + if result not in ('Alice', 'Bob', 'Tie'): + return False + dp = [0] * (len(values) + 3) + for index in range(len(values) - 1, -1, -1): + total = 0 + best = -10**18 + for take in range(1, 4): + if index + take > len(values): + break + total += values[index + take - 1] + best = max(best, total - dp[index + take]) + dp[index] = best + expected = 'Alice' if dp[0] > 0 else 'Bob' if dp[0] < 0 else 'Tie' + return result == expected +seed: 1406 +tests: + - name: single_positive + in: + stoneValue: [1] + - name: single_negative + in: + stoneValue: [-1] + - name: single_zero + in: + stoneValue: [0] + - name: two_positive + in: + stoneValue: [1, 2] + - name: two_negative + in: + stoneValue: [-1, -2] + - name: two_cancel + in: + stoneValue: [1, -1] + - name: three_positive + in: + stoneValue: [1, 2, 3] + - name: three_negative + in: + stoneValue: [-1, -2, -3] + - name: three_tie + in: + stoneValue: [1, -1, 0] + - name: example_like_one + in: + stoneValue: [1, 2, 3, 7] + - name: example_like_two + in: + stoneValue: [1, 2, 3, -9] + - name: alternating + in: + stoneValue: [1, -1, 1, -1, 1, -1] + - name: all_zero + in: + stoneValue: [0, 0, 0, 0, 0] + - name: all_positive + in: + stoneValue: [5, 5, 5, 5, 5, 5] + - name: all_negative + in: + stoneValue: [-5, -5, -5, -5, -5, -5] + - name: large_first + in: + stoneValue: [1000, -1, -1, -1] + - name: large_last + in: + stoneValue: [-1, -1, -1, 1000] + - name: negative_first + in: + stoneValue: [-1000, 1, 1, 1] + - name: positive_negative_mix + in: + stoneValue: [4, -2, 7, -5, 3] + - name: forced_three_choice + in: + stoneValue: [-10, 1, 1, 1, 1] + - name: take_two_best + in: + stoneValue: [8, 8, -20, 1] + - name: take_three_best + in: + stoneValue: [4, 4, 4, -100] + - name: tie_balanced + in: + stoneValue: [2, -1, -1] + - name: repeated_pattern + in: + stoneValue: [3, -2, 3, -2, 3, -2, 3, -2] + - name: increasing + in: + stoneValue: [1, 2, 3, 4, 5, 6, 7, 8] + - name: decreasing + in: + stoneValue: [8, 7, 6, 5, 4, 3, 2, 1] + - name: boundary_values + in: + stoneValue: [1000, -1000, 1000, -1000, 1000, -1000] + - name: long_positive_tail + in: + stoneValue: [-20, -20, 1, 1, 1, 1, 1, 1, 1] + - name: long_negative_tail + in: + stoneValue: [20, 20, -1, -1, -1, -1, -1, -1, -1] + - name: twelve_mixed + in: + stoneValue: [5, -4, 3, -2, 1, -6, 7, -8, 9, -10, 11, -12] + - name: fifteen_equal + in: + stoneValue: [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] + - name: twenty_pattern + in: + stoneValue: + [ + 10, + -5, + 10, + -5, + 10, + -5, + 10, + -5, + 10, + -5, + 10, + -5, + 10, + -5, + 10, + -5, + 10, + -5, + 10, + -5, + ] + - name: generated_small + seed: 101 + in: + stoneValue: + gen: array + len: + gen: int + min: 1 + max: 20 + of: + gen: int + min: -20 + max: 20 + distinct: false + sorted: false + elemType: int + - name: generated_medium + seed: 202 + in: + stoneValue: + gen: array + len: + gen: int + min: 50 + max: 150 + of: + gen: int + min: -1000 + max: 1000 + distinct: false + sorted: false + elemType: int + - name: generated_positive + seed: 303 + in: + stoneValue: + gen: array + len: + gen: int + min: 100 + max: 300 + of: + gen: int + min: 1 + max: 1000 + distinct: false + sorted: false + elemType: int + - name: generated_negative + seed: 404 + in: + stoneValue: + gen: array + len: + gen: int + min: 100 + max: 300 + of: + gen: int + min: -1000 + max: -1 + distinct: false + sorted: false + elemType: int + - name: stress_maximum + seed: 505 + in: + stoneValue: + gen: array + len: 50000 + of: + gen: int + min: -1000 + max: 1000 + distinct: false + sorted: false + elemType: int + - name: boundary_zero_negative_choice + in: + stoneValue: [0, -1, 0, 1, -1, 1, 0] + - name: stress_maximum_positive + seed: 606 + in: + stoneValue: + gen: array + len: 50000 + of: + gen: int + min: 1 + max: 1000 + distinct: false + sorted: false + elemType: int + - name: stress_near_maximum_negative + seed: 707 + in: + stoneValue: + gen: array + len: 49999 + of: + gen: int + min: -1000 + max: -1 + distinct: false + sorted: false + elemType: int diff --git a/tests/1001-1500/1406. stone-game-iii/sol.cpp b/tests/1001-1500/1406. stone-game-iii/sol.cpp new file mode 100644 index 00000000..dc8a3eb6 --- /dev/null +++ b/tests/1001-1500/1406. stone-game-iii/sol.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + string stoneGameIII(vector& stoneValue) { + int n = stoneValue.size(); + vector dp(3, 0); + + for (int i = n - 1; i >= 0; i--) { + int takeOne = stoneValue[i] - dp[(i + 1) % 3]; + + int takeTwo = INT_MIN; + if (i + 1 < n) { + takeTwo = stoneValue[i] + stoneValue[i + 1] - dp[(i + 2) % 3]; + } + + int takeThree = INT_MIN; + if (i + 2 < n) { + takeThree = stoneValue[i] + stoneValue[i + 1] + stoneValue[i + 2] - dp[(i + 3) % 3]; + } + + dp[i % 3] = max({takeOne, takeTwo, takeThree}); + } + + int value = dp[0]; + if (value > 0) { + return "Alice"; + } else if (value < 0) { + return "Bob"; + } else { + return "Tie"; + } + } +}; diff --git a/tests/1001-1500/1406. stone-game-iii/sol.cs b/tests/1001-1500/1406. stone-game-iii/sol.cs new file mode 100644 index 00000000..8df89e0a --- /dev/null +++ b/tests/1001-1500/1406. stone-game-iii/sol.cs @@ -0,0 +1,31 @@ +public class Solution { + public string StoneGameIII(int[] stoneValue) { + int n = stoneValue.Length; + int[] dp = new int[3]; + + for (int i = n - 1; i >= 0; i--) { + int takeOne = stoneValue[i] - dp[(i + 1) % 3]; + + int takeTwo = int.MinValue; + if (i + 1 < n) { + takeTwo = stoneValue[i] + stoneValue[i + 1] - dp[(i + 2) % 3]; + } + + int takeThree = int.MinValue; + if (i + 2 < n) { + takeThree = stoneValue[i] + stoneValue[i + 1] + stoneValue[i + 2] - dp[(i + 3) % 3]; + } + + dp[i % 3] = Math.Max(takeOne, Math.Max(takeTwo, takeThree)); + } + + int value = dp[0]; + if (value > 0) { + return "Alice"; + } else if (value < 0) { + return "Bob"; + } else { + return "Tie"; + } + } +} diff --git a/tests/1001-1500/1406. stone-game-iii/sol.dart b/tests/1001-1500/1406. stone-game-iii/sol.dart new file mode 100644 index 00000000..bcc4a266 --- /dev/null +++ b/tests/1001-1500/1406. stone-game-iii/sol.dart @@ -0,0 +1,31 @@ +class Solution { + String stoneGameIII(List stoneValue) { + int n = stoneValue.length; + List dp = [0, 0, 0]; + + for (int i = n - 1; i >= 0; i--) { + int takeOne = stoneValue[i] - dp[(i + 1) % 3]; + + int takeTwo = -1e9.toInt(); + if (i + 1 < n) { + takeTwo = stoneValue[i] + stoneValue[i + 1] - dp[(i + 2) % 3]; + } + + int takeThree = -1e9.toInt(); + if (i + 2 < n) { + takeThree = stoneValue[i] + stoneValue[i + 1] + stoneValue[i + 2] - dp[(i + 3) % 3]; + } + + dp[i % 3] = [takeOne, takeTwo, takeThree].reduce((a, b) => a > b ? a : b); + } + + int value = dp[0]; + if (value > 0) { + return "Alice"; + } else if (value < 0) { + return "Bob"; + } else { + return "Tie"; + } + } +} diff --git a/tests/1001-1500/1406. stone-game-iii/sol.go b/tests/1001-1500/1406. stone-game-iii/sol.go new file mode 100644 index 00000000..5c35039f --- /dev/null +++ b/tests/1001-1500/1406. stone-game-iii/sol.go @@ -0,0 +1,29 @@ +func stoneGameIII(stoneValue []int) string { + n := len(stoneValue) + dp := make([]int, 3) + + for i := n - 1; i >= 0; i-- { + takeOne := stoneValue[i] - dp[(i+1)%3] + + takeTwo := int(-1e9) + if i+1 < n { + takeTwo = stoneValue[i] + stoneValue[i+1] - dp[(i+2)%3] + } + + takeThree := int(-1e9) + if i+2 < n { + takeThree = stoneValue[i] + stoneValue[i+1] + stoneValue[i+2] - dp[(i+3)%3] + } + + dp[i%3] = max(takeOne, max(takeTwo, takeThree)) + } + + value := dp[0] + if value > 0 { + return "Alice" + } else if value < 0 { + return "Bob" + } else { + return "Tie" + } +} diff --git a/tests/1001-1500/1406. stone-game-iii/sol.java b/tests/1001-1500/1406. stone-game-iii/sol.java new file mode 100644 index 00000000..040f36ea --- /dev/null +++ b/tests/1001-1500/1406. stone-game-iii/sol.java @@ -0,0 +1,31 @@ +class Solution { + public String stoneGameIII(int[] stoneValue) { + int n = stoneValue.length; + int[] dp = new int[3]; + + for (int i = n - 1; i >= 0; i--) { + int takeOne = stoneValue[i] - dp[(i + 1) % 3]; + + int takeTwo = Integer.MIN_VALUE; + if (i + 1 < n) { + takeTwo = stoneValue[i] + stoneValue[i + 1] - dp[(i + 2) % 3]; + } + + int takeThree = Integer.MIN_VALUE; + if (i + 2 < n) { + takeThree = stoneValue[i] + stoneValue[i + 1] + stoneValue[i + 2] - dp[(i + 3) % 3]; + } + + dp[i % 3] = Math.max(takeOne, Math.max(takeTwo, takeThree)); + } + + int value = dp[0]; + if (value > 0) { + return "Alice"; + } else if (value < 0) { + return "Bob"; + } else { + return "Tie"; + } + } +} diff --git a/tests/1001-1500/1406. stone-game-iii/sol.kt b/tests/1001-1500/1406. stone-game-iii/sol.kt new file mode 100644 index 00000000..94bdb59e --- /dev/null +++ b/tests/1001-1500/1406. stone-game-iii/sol.kt @@ -0,0 +1,29 @@ +class Solution { + fun stoneGameIII(stoneValue: IntArray): String { + val n = stoneValue.size + val dp = IntArray(3) + + for (i in n - 1 downTo 0) { + val takeOne = stoneValue[i] - dp[(i + 1) % 3] + + var takeTwo = Int.MIN_VALUE + if (i + 1 < n) { + takeTwo = stoneValue[i] + stoneValue[i + 1] - dp[(i + 2) % 3] + } + + var takeThree = Int.MIN_VALUE + if (i + 2 < n) { + takeThree = stoneValue[i] + stoneValue[i + 1] + stoneValue[i + 2] - dp[(i + 3) % 3] + } + + dp[i % 3] = maxOf(takeOne, takeTwo, takeThree) + } + + val value = dp[0] + return when { + value > 0 -> "Alice" + value < 0 -> "Bob" + else -> "Tie" + } + } +} diff --git a/tests/1001-1500/1406. stone-game-iii/sol.py b/tests/1001-1500/1406. stone-game-iii/sol.py new file mode 100644 index 00000000..5d856db5 --- /dev/null +++ b/tests/1001-1500/1406. stone-game-iii/sol.py @@ -0,0 +1,30 @@ +class Solution: + def stoneGameIII(self, stoneValue): + n = len(stoneValue) + dp = [0] * 3 + + for i in range(n - 1, -1, -1): + takeOne = stoneValue[i] - dp[(i + 1) % 3] + + takeTwo = float("-inf") + if i + 1 < n: + takeTwo = stoneValue[i] + stoneValue[i + 1] - dp[(i + 2) % 3] + + takeThree = float("-inf") + if i + 2 < n: + takeThree = ( + stoneValue[i] + + stoneValue[i + 1] + + stoneValue[i + 2] + - dp[(i + 3) % 3] + ) + + dp[i % 3] = max(takeOne, takeTwo, takeThree) + + value = dp[0] + if value > 0: + return "Alice" + elif value < 0: + return "Bob" + else: + return "Tie" diff --git a/tests/1001-1500/1406. stone-game-iii/sol.py2 b/tests/1001-1500/1406. stone-game-iii/sol.py2 new file mode 100644 index 00000000..125ab53d --- /dev/null +++ b/tests/1001-1500/1406. stone-game-iii/sol.py2 @@ -0,0 +1,29 @@ +class Solution(object): + def stoneGameIII(self, stoneValue): + """ + :type stoneValue: List[int] + :rtype: str + """ + n = len(stoneValue) + dp = [0] * 3 + + for i in range(n - 1, -1, -1): + takeOne = stoneValue[i] - dp[(i + 1) % 3] + + takeTwo = float('-inf') + if i + 1 < n: + takeTwo = stoneValue[i] + stoneValue[i + 1] - dp[(i + 2) % 3] + + takeThree = float('-inf') + if i + 2 < n: + takeThree = stoneValue[i] + stoneValue[i + 1] + stoneValue[i + 2] - dp[(i + 3) % 3] + + dp[i % 3] = max(takeOne, takeTwo, takeThree) + + value = dp[0] + if value > 0: + return "Alice" + elif value < 0: + return "Bob" + else: + return "Tie" diff --git a/tests/1001-1500/1406. stone-game-iii/sol.rb b/tests/1001-1500/1406. stone-game-iii/sol.rb new file mode 100644 index 00000000..ac460b6a --- /dev/null +++ b/tests/1001-1500/1406. stone-game-iii/sol.rb @@ -0,0 +1,31 @@ +# @param {Integer[]} stone_value +# @return {String} +def stone_game_iii(stone_value) + n = stone_value.length + dp = [0, 0, 0] + + (n - 1).downto(0) do |i| + take_one = stone_value[i] - dp[(i + 1) % 3] + + take_two = -Float::INFINITY + if i + 1 < n + take_two = stone_value[i] + stone_value[i + 1] - dp[(i + 2) % 3] + end + + take_three = -Float::INFINITY + if i + 2 < n + take_three = stone_value[i] + stone_value[i + 1] + stone_value[i + 2] - dp[(i + 3) % 3] + end + + dp[i % 3] = [take_one, take_two, take_three].max + end + + value = dp[0] + if value > 0 + return "Alice" + elsif value < 0 + return "Bob" + else + return "Tie" + end +end diff --git a/tests/1001-1500/1406. stone-game-iii/sol.rs b/tests/1001-1500/1406. stone-game-iii/sol.rs new file mode 100644 index 00000000..993b55c4 --- /dev/null +++ b/tests/1001-1500/1406. stone-game-iii/sol.rs @@ -0,0 +1,31 @@ +impl Solution { + pub fn stone_game_iii(stone_value: Vec) -> String { + let n = stone_value.len(); + let mut dp = vec![0; 3]; + + for i in (0..n).rev() { + let take_one = stone_value[i] - dp[(i + 1) % 3]; + + let mut take_two = i32::MIN; + if i + 1 < n { + take_two = stone_value[i] + stone_value[i + 1] - dp[(i + 2) % 3]; + } + + let mut take_three = i32::MIN; + if i + 2 < n { + take_three = stone_value[i] + stone_value[i + 1] + stone_value[i + 2] - dp[(i + 3) % 3]; + } + + dp[i % 3] = take_one.max(take_two).max(take_three); + } + + let value = dp[0]; + if value > 0 { + "Alice".to_string() + } else if value < 0 { + "Bob".to_string() + } else { + "Tie".to_string() + } + } +} diff --git a/tests/1001-1500/1406. stone-game-iii/sol.swift b/tests/1001-1500/1406. stone-game-iii/sol.swift new file mode 100644 index 00000000..d85257f0 --- /dev/null +++ b/tests/1001-1500/1406. stone-game-iii/sol.swift @@ -0,0 +1,31 @@ +class Solution { + func stoneGameIII(_ stoneValue: [Int]) -> String { + let n = stoneValue.count + var dp = [0, 0, 0] + + for i in stride(from: n - 1, through: 0, by: -1) { + let takeOne = stoneValue[i] - dp[(i + 1) % 3] + + var takeTwo = Int.min + if i + 1 < n { + takeTwo = stoneValue[i] + stoneValue[i + 1] - dp[(i + 2) % 3] + } + + var takeThree = Int.min + if i + 2 < n { + takeThree = stoneValue[i] + stoneValue[i + 1] + stoneValue[i + 2] - dp[(i + 3) % 3] + } + + dp[i % 3] = max(takeOne, max(takeTwo, takeThree)) + } + + let value = dp[0] + if value > 0 { + return "Alice" + } else if value < 0 { + return "Bob" + } else { + return "Tie" + } + } +} diff --git a/tests/1001-1500/1406. stone-game-iii/sol.ts b/tests/1001-1500/1406. stone-game-iii/sol.ts new file mode 100644 index 00000000..0cbdb9f7 --- /dev/null +++ b/tests/1001-1500/1406. stone-game-iii/sol.ts @@ -0,0 +1,30 @@ +function stoneGameIII(stoneValue: number[]): string { + const n: number = stoneValue.length; + const dp: number[] = [0, 0, 0]; + + for (let i = n - 1; i >= 0; i--) { + const takeOne: number = stoneValue[i] - dp[(i + 1) % 3]; + + let takeTwo: number = -Infinity; + if (i + 1 < n) { + takeTwo = stoneValue[i] + stoneValue[i + 1] - dp[(i + 2) % 3]; + } + + let takeThree: number = -Infinity; + if (i + 2 < n) { + takeThree = + stoneValue[i] + stoneValue[i + 1] + stoneValue[i + 2] - dp[(i + 3) % 3]; + } + + dp[i % 3] = Math.max(takeOne, takeTwo, takeThree); + } + + const value: number = dp[0]; + if (value > 0) { + return "Alice"; + } else if (value < 0) { + return "Bob"; + } else { + return "Tie"; + } +} diff --git a/tests/1001-1500/1408. string-matching-in-an-array/manifest.yaml b/tests/1001-1500/1408. string-matching-in-an-array/manifest.yaml new file mode 100644 index 00000000..d75e42d0 --- /dev/null +++ b/tests/1001-1500/1408. string-matching-in-an-array/manifest.yaml @@ -0,0 +1,459 @@ +entry: + id: 1408 + title: "string-matching-in-an-array" + params: + words: + type: array + items: + type: string + call: + cpp: "Solution().stringMatching({words})" + rust: "Solution::string_matching({words})" + python3: "Solution().stringMatching({words})" + python2: "Solution().stringMatching({words})" + ruby: "string_matching({words})" + java: "new Solution().stringMatching({words})" + csharp: "new Solution().StringMatching({words})" + kotlin: "Solution().stringMatching({words})" + go: "stringMatching({words})" + dart: "Solution().stringMatching({words})" + swift: "Solution().stringMatching({words})" + typescript: "stringMatching({words})" + +judge: + type: "ignore_order" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().stringMatching(words, {result})" + checker: | + class Checker: + def stringMatching(self, words, result): + if not isinstance(result, list) or any(not isinstance(x, str) for x in result): + return False + expected = [] + for i, word in enumerate(words): + if any(i != j and word in other for j, other in enumerate(words)): + expected.append(word) + return len(result) == len(expected) and len(set(result)) == len(result) and set(result) == set(expected) + +seed: 1408 + +tests: + - name: "example-one" + in: + words: ["mass", "as", "hero", "superhero"] + - name: "example-two" + in: + words: ["leetcode", "et", "code"] + - name: "example-three" + in: + words: ["blue", "green", "bu"] + - name: "single-word" + in: + words: ["alone"] + - name: "two-unrelated" + in: + words: ["cat", "dog"] + - name: "two-contained" + in: + words: ["at", "cat"] + - name: "prefix-chain" + in: + words: ["a", "ab", "abc", "abcd"] + - name: "suffix-chain" + in: + words: ["abcd", "bcd", "cd", "d"] + - name: "middle-substrings" + in: + words: ["hello", "ell", "ellx", "world"] + - name: "no-match-similar" + in: + words: ["abc", "abd", "bc", "bcd"] + - name: "overlapping-patterns" + in: + words: ["abab", "bab", "ab", "baba"] + - name: "single-character-words" + in: + words: ["a", "b", "c", "ab", "bc"] + - name: "all-contained" + in: + words: ["x", "yx", "zyx", "azyx"] + - name: "none-contained-long" + in: + words: ["alpha", "bravo", "charlie", "delta"] + - name: "multiple-containers" + in: + words: ["he", "she", "the", "them", "shell"] + - name: "substring-at-end" + in: + words: ["end", "friend", "bend", "ending"] + - name: "substring-at-start" + in: + words: ["start", "starter", "art", "cart"] + - name: "middle-and-prefix" + in: + words: ["testing", "test", "sting", "ing", "rest"] + - name: "repeated-letters" + in: + words: ["aaaa", "aa", "aaa", "bbaaab"] + - name: "palindrome-words" + in: + words: ["racecar", "ace", "car", "race"] + - name: "longest-first" + in: + words: ["substring", "string", "sub", "ring", "x"] + - name: "alternating-chain" + in: + words: ["xy", "yxy", "xyxy", "y", "x"] + - name: "disjoint-alphabet" + in: + words: ["aaa", "bbb", "ccc", "abc"] + - name: "many-short" + in: + words: ["a", "ab", "b", "ba", "aba", "bab"] + - name: "container-before-child" + in: + words: ["alphabet", "bet", "alpha", "pha", "z"] + - name: "container-after-child" + in: + words: ["bet", "alphabet", "pha", "alpha", "z"] + - name: "near-matches" + in: + words: ["abcd", "abcx", "bcdx", "bc"] + - name: "maximum-length-word" + in: + words: ["abcdefghijklmnopqrstuvwxyza", "mnop", "xyz", "z"] + - name: "large-list-of-distinct" + in: + words: + [ + "a", + "ab", + "abc", + "abcd", + "abcde", + "abcdef", + "abcdefg", + "h", + "hi", + "hij", + "k", + "kl", + "klm", + ] + - name: "empty-result-with-single-letter-noise" + in: + words: ["q", "qqq", "r", "rrr", "srs"] + - name: "nested-middle-substrings" + in: + words: ["cabinet", "bin", "inet", "abi", "net", "cab", "x"] + - name: "length-thirty-container" + in: + words: + [ + "abcdefghijklmnopqrstuvwxzyabcd", + "lmnop", + "wxyz", + "abcd", + "mnopq", + "zabcd", + "q", + ] + - name: "hundred-word-boundary-chain" + in: + words: + - "abcdefghijklmnopqrstuvwxyza" + - "bcdefghijklmnopqrstuvwxyzab" + - "cdefghijklmnopqrstuvwxyzabc" + - "defghijklmnopqrstuvwxyzabcd" + - "efghijklmnopqrstuvwxyzabcde" + - "fghijklmnopqrstuvwxyzabcdef" + - "ghijklmnopqrstuvwxyzabcdefg" + - "hijklmnopqrstuvwxyzabcdefgh" + - "ijklmnopqrstuvwxyzabcdefghi" + - "jklmnopqrstuvwxyzabcdefghij" + - "klmnopqrstuvwxyzabcdefghijk" + - "lmnopqrstuvwxyzabcdefghijkl" + - "mnopqrstuvwxyzabcdefghijklm" + - "nopqrstuvwxyzabcdefghijklmn" + - "opqrstuvwxyzabcdefghijklmno" + - "pqrstuvwxyzabcdefghijklmnop" + - "qrstuvwxyzabcdefghijklmnopq" + - "rstuvwxyzabcdefghijklmnopqr" + - "stuvwxyzabcdefghijklmnopqrs" + - "tuvwxyzabcdefghijklmnopqrst" + - "uvwxyzabcdefghijklmnopqrstu" + - "vwxyzabcdefghijklmnopqrstuv" + - "wxyzabcdefghijklmnopqrstuvw" + - "xyzabcdefghijklmnopqrstuvwx" + - "yzabcdefghijklmnopqrstuvwxy" + - "zabcdefghijklmnopqrstuvwxyza" + - "abc" + - "bcd" + - "cde" + - "def" + - "efg" + - "fgh" + - "ghi" + - "hij" + - "ijk" + - "jkl" + - "klm" + - "lmn" + - "mno" + - "nop" + - "opq" + - "pqr" + - "qrs" + - "rst" + - "stu" + - "tuv" + - "uvw" + - "vwx" + - "wxy" + - "xyz" + - "za" + - "ab" + - "bc" + - "cd" + - "de" + - "fg" + - "gh" + - "hi" + - "ij" + - "jk" + - "lm" + - "mn" + - "no" + - "op" + - "pq" + - "qr" + - "rs" + - "st" + - "tu" + - "uv" + - "vw" + - "wx" + - "xy" + - "yz" + - "zaa" + - "abb" + - "bcc" + - "cdd" + - "dee" + - "eff" + - "fgg" + - "ghh" + - "hii" + - "ijj" + - "jkk" + - "kll" + - "lmm" + - "mnn" + - "noo" + - "opp" + - "pqq" + - "qrr" + - "rss" + - "stt" + - "tuu" + - "uvv" + - "vww" + - "wxx" + - "xyy" + - "yzz" + - name: "hundred-word-disjoint-and-contained" + in: + words: + - "amberstone" + - "blueharbor" + - "crimsonfield" + - "dawnmeadow" + - "evergreen" + - "frostgarden" + - "goldenpath" + - "hollowriver" + - "indigocloud" + - "jadelantern" + - "kindredforest" + - "lilacvalley" + - "mosaicbridge" + - "northernstar" + - "opalwindow" + - "pebblecanyon" + - "quietvillage" + - "redwoodtrail" + - "silverisland" + - "thunderplain" + - "umbercastle" + - "velvetorchard" + - "willowstation" + - "xenonmarket" + - "youngsummit" + - "zephyrcoast" + - "amber" + - "stone" + - "blue" + - "harbor" + - "crimson" + - "field" + - "dawn" + - "meadow" + - "ever" + - "green" + - "frost" + - "garden" + - "gold" + - "path" + - "hollow" + - "river" + - "indigo" + - "cloud" + - "jade" + - "lantern" + - "kindred" + - "forest" + - "lilac" + - "valley" + - "mosaic" + - "bridge" + - "northern" + - "star" + - "opal" + - "window" + - "pebble" + - "canyon" + - "quiet" + - "village" + - "redwood" + - "trail" + - "silver" + - "island" + - "thunder" + - "plain" + - "umber" + - "castle" + - "velvet" + - "orchard" + - "willow" + - "station" + - "xenon" + - "market" + - "young" + - "summit" + - "zephyr" + - "coast" + - "amberstonex" + - "blueharborx" + - "crimsonfieldx" + - "dawnmeadowx" + - "evergreenx" + - "frostgardenx" + - "goldenpathx" + - "hollowriverx" + - "indigocloudx" + - "jadelanternx" + - "kindredforestx" + - "lilacvalleyx" + - "mosaicbridgex" + - "northernstarx" + - "opalwindowx" + - "pebblecanyonx" + - "quietvillagex" + - "redwoodtrailx" + - "silverislandx" + - "thunderplainx" + - "umbercastlex" + - "velvetorchardx" + - name: "generated-max-length-random" + seed: 140801 + in: + words: + gen: "array" + len: 100 + of: + gen: "str" + len: 30 + alphabet: "abcdefghijklmnopqrstuvwxyz" + distinct: true + sorted: false + elemType: "string" + - name: "generated-max-length-narrow-alphabet" + seed: 140802 + in: + words: + gen: "array" + len: 100 + of: + gen: "str" + len: 30 + alphabet: "ab" + distinct: true + sorted: false + elemType: "string" + - name: "generated-max-count-variable-length" + seed: 140803 + in: + words: + gen: "array" + len: 100 + of: + gen: "str" + len: + gen: "int" + min: 1 + max: 30 + alphabet: "abcdefghijklmnopqrstuvwxyz" + distinct: true + sorted: false + elemType: "string" + - name: "generated-max-count-short-patterns" + seed: 140804 + in: + words: + gen: "array" + len: 100 + of: + gen: "str" + len: + gen: "int" + min: 1 + max: 6 + alphabet: "abc" + distinct: true + sorted: false + elemType: "string" + - name: "generated-near-max-count-medium-words" + seed: 140805 + in: + words: + gen: "array" + len: 99 + of: + gen: "str" + len: 20 + alphabet: "abcdefghijklmnopqrstuvwxyz" + distinct: true + sorted: false + elemType: "string" + - name: "generated-near-max-count-single-alphabet" + seed: 140806 + in: + words: + gen: "array" + len: 100 + of: + gen: "str" + len: + gen: "int" + min: 1 + max: 30 + alphabet: "ab" + distinct: true + sorted: false + elemType: "string" diff --git a/tests/1001-1500/1408. string-matching-in-an-array/sol.cpp b/tests/1001-1500/1408. string-matching-in-an-array/sol.cpp new file mode 100644 index 00000000..446e2d68 --- /dev/null +++ b/tests/1001-1500/1408. string-matching-in-an-array/sol.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + vector stringMatching(vector& words) { + int n = words.size(); + vector ans; + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (i != j && words[j].find(words[i]) != string::npos) { + ans.push_back(words[i]); + break; + } + } + } + return ans; + } +}; diff --git a/tests/1001-1500/1408. string-matching-in-an-array/sol.cs b/tests/1001-1500/1408. string-matching-in-an-array/sol.cs new file mode 100644 index 00000000..1dde5793 --- /dev/null +++ b/tests/1001-1500/1408. string-matching-in-an-array/sol.cs @@ -0,0 +1,15 @@ +public class Solution { + public IList StringMatching(string[] words) { + int n = words.Length; + IList ans = new List(); + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (i != j && words[j].Contains(words[i])) { + ans.Add(words[i]); + break; + } + } + } + return ans; + } +} diff --git a/tests/1001-1500/1408. string-matching-in-an-array/sol.dart b/tests/1001-1500/1408. string-matching-in-an-array/sol.dart new file mode 100644 index 00000000..ac998d56 --- /dev/null +++ b/tests/1001-1500/1408. string-matching-in-an-array/sol.dart @@ -0,0 +1,15 @@ +class Solution { + List stringMatching(List words) { + int n = words.length; + List ans = []; + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (i != j && words[j].contains(words[i])) { + ans.add(words[i]); + break; + } + } + } + return ans; + } +} diff --git a/tests/1001-1500/1408. string-matching-in-an-array/sol.go b/tests/1001-1500/1408. string-matching-in-an-array/sol.go new file mode 100644 index 00000000..7d1d41b1 --- /dev/null +++ b/tests/1001-1500/1408. string-matching-in-an-array/sol.go @@ -0,0 +1,13 @@ +func stringMatching(words []string) []string { + n := len(words) + ans := []string{} + for i := 0; i < n; i++ { + for j := 0; j < n; j++ { + if i != j && strings.Contains(words[j], words[i]) { + ans = append(ans, words[i]) + break + } + } + } + return ans +} diff --git a/tests/1001-1500/1408. string-matching-in-an-array/sol.java b/tests/1001-1500/1408. string-matching-in-an-array/sol.java new file mode 100644 index 00000000..7e7a234e --- /dev/null +++ b/tests/1001-1500/1408. string-matching-in-an-array/sol.java @@ -0,0 +1,15 @@ +class Solution { + public List stringMatching(String[] words) { + int n = words.length; + List ans = new ArrayList<>(); + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (i != j && words[j].contains(words[i])) { + ans.add(words[i]); + break; + } + } + } + return ans; + } +} diff --git a/tests/1001-1500/1408. string-matching-in-an-array/sol.kt b/tests/1001-1500/1408. string-matching-in-an-array/sol.kt new file mode 100644 index 00000000..88887ec0 --- /dev/null +++ b/tests/1001-1500/1408. string-matching-in-an-array/sol.kt @@ -0,0 +1,15 @@ +class Solution { + fun stringMatching(words: Array): List { + val n = words.size + val ans = mutableListOf() + for (i in 0 until n) { + for (j in 0 until n) { + if (i != j && words[j].contains(words[i])) { + ans.add(words[i]) + break + } + } + } + return ans + } +} diff --git a/tests/1001-1500/1408. string-matching-in-an-array/sol.py b/tests/1001-1500/1408. string-matching-in-an-array/sol.py new file mode 100644 index 00000000..62f0578d --- /dev/null +++ b/tests/1001-1500/1408. string-matching-in-an-array/sol.py @@ -0,0 +1,12 @@ +class Solution: + def stringMatching(self, words: List[str]) -> List[str]: + n = len(words) + ans = [] + + for i in range(n): + for j in range(n): + if i != j and words[j].find(words[i]) != -1: + ans.append(words[i]) + break + + return ans diff --git a/tests/1001-1500/1408. string-matching-in-an-array/sol.py2 b/tests/1001-1500/1408. string-matching-in-an-array/sol.py2 new file mode 100644 index 00000000..4e9f8bb7 --- /dev/null +++ b/tests/1001-1500/1408. string-matching-in-an-array/sol.py2 @@ -0,0 +1,14 @@ +class Solution(object): + def stringMatching(self, words): + """ + :type words: List[str] + :rtype: List[str] + """ + n = len(words) + ans = [] + for i in range(n): + for j in range(n): + if i != j and words[i] in words[j]: + ans.append(words[i]) + break + return ans diff --git a/tests/1001-1500/1408. string-matching-in-an-array/sol.rb b/tests/1001-1500/1408. string-matching-in-an-array/sol.rb new file mode 100644 index 00000000..6a3ef876 --- /dev/null +++ b/tests/1001-1500/1408. string-matching-in-an-array/sol.rb @@ -0,0 +1,15 @@ +# @param {String[]} words +# @return {String[]} +def string_matching(words) + n = words.length + ans = [] + (0...n).each do |i| + (0...n).each do |j| + if i != j && words[j].include?(words[i]) + ans << words[i] + break + end + end + end + ans +end diff --git a/tests/1001-1500/1408. string-matching-in-an-array/sol.rs b/tests/1001-1500/1408. string-matching-in-an-array/sol.rs new file mode 100644 index 00000000..c31b43dd --- /dev/null +++ b/tests/1001-1500/1408. string-matching-in-an-array/sol.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn string_matching(words: Vec) -> Vec { + let n = words.len(); + let mut ans = Vec::new(); + for i in 0..n { + for j in 0..n { + if i != j && words[j].contains(&words[i]) { + ans.push(words[i].clone()); + break; + } + } + } + ans + } +} diff --git a/tests/1001-1500/1408. string-matching-in-an-array/sol.swift b/tests/1001-1500/1408. string-matching-in-an-array/sol.swift new file mode 100644 index 00000000..2b9b8038 --- /dev/null +++ b/tests/1001-1500/1408. string-matching-in-an-array/sol.swift @@ -0,0 +1,15 @@ +class Solution { + func stringMatching(_ words: [String]) -> [String] { + let n = words.count + var ans = [String]() + for i in 0.. last_seen[q]) + expected = newer + else: + unqueried_less = (q - 1) - sum(1 for value in last_seen if value < q) + expected = len(last_seen) + unqueried_less + if got != expected or not 0 <= got < m: + return False + last_seen[q] = index + return True +seed: 1409 +tests: + - name: "example_one" + in: + queries: [3, 1, 2, 1] + m: 5 + - name: "example_two" + in: + queries: [4, 1, 2, 2] + m: 4 + - name: "example_three" + in: + queries: [7, 5, 5, 8, 3] + m: 8 + - name: "minimum_single" + in: + queries: [1] + m: 1 + - name: "two_first_and_repeat" + in: + queries: [2, 1] + m: 2 + - name: "two_alternating" + in: + queries: [1, 2] + m: 2 + - name: "ascending_full" + in: + queries: [1, 2, 3, 4, 5] + m: 5 + - name: "descending_full" + in: + queries: [5, 4, 3, 2, 1] + m: 5 + - name: "ascending_twice" + in: + queries: [1, 2, 3, 4] + m: 4 + - name: "descending_twice" + in: + queries: [4, 3, 2, 1] + m: 4 + - name: "same_value" + in: + queries: [1, 1, 1, 1, 1] + m: 7 + - name: "same_last_value" + in: + queries: [9, 9, 9, 9] + m: 9 + - name: "front_back" + in: + queries: [1, 10, 1, 10, 1] + m: 10 + - name: "middle_repeated" + in: + queries: [5, 5, 4, 5, 6, 5] + m: 8 + - name: "all_high_values" + in: + queries: [8, 9, 10, 8, 10, 9, 8] + m: 10 + - name: "all_low_values" + in: + queries: [1, 2, 3, 1, 3, 2, 1] + m: 10 + - name: "three_value_cycle" + in: + queries: [1, 2, 3] + m: 3 + - name: "interleaved_values" + in: + queries: [2, 5, 2, 5, 1, 4] + m: 6 + - name: "new_values_then_revisit" + in: + queries: [6, 2, 9, 4, 6, 2, 9, 4] + m: 10 + - name: "sparse_large_domain" + in: + queries: [250, 500, 250, 1, 500] + m: 500 + - name: "extreme_domain" + in: + queries: [1000, 1, 500, 1000, 1, 999] + m: 1000 + - name: "complete_small_permutation" + in: + queries: [3, 1, 4, 2] + m: 4 + - name: "complete_large_permutation" + in: + queries: [10, 1, 8, 3, 6, 2, 9, 4, 7, 5] + m: 10 + - name: "boundary_pair" + in: + queries: [1, 1000, 500, 1, 1000] + m: 1000 + - name: "alternating_extremes" + in: + queries: [1, 1000, 1, 1000, 999, 2, 999, 2] + m: 1000 + - name: "repeated_three_values" + in: + queries: [7, 2, 9, 2, 7, 9, 2, 7] + m: 10 + - name: "nested_reordering" + in: + queries: [4, 3, 4, 2, 3, 4] + m: 6 + - name: "queries_length_equals_m" + in: + queries: [8, 1, 8, 2, 7, 3, 6, 4] + m: 8 + - name: "large_prefix" + in: + queries: [997, 998, 999, 1000, 997, 1, 500, 1000] + m: 1000 + - name: "middle_band" + in: + queries: [40, 41, 42, 43, 42, 41, 40, 43] + m: 50 + - name: "alternating_parity" + in: + queries: [2, 4, 6, 8, 2, 4, 6, 8] + m: 8 + - name: "mixed_small" + in: + queries: [3, 8, 1, 8, 3, 1] + m: 8 + - name: "mixed_medium" + in: + queries: [12, 1, 6, 12, 6, 1] + m: 12 + - name: "long_cycle" + in: + queries: [1, 2, 3, 4, 5] + m: 5 + - name: "long_high_pattern" + in: + queries: [9, 8, 7, 9, 8, 7, 9, 8, 7] + m: 9 + - name: "generated_small" + seed: 1410 + in: + queries: + gen: "array" + len: 7 + of: + gen: "int" + min: 1 + max: 12 + distinct: false + elemType: "int" + m: 12 + - name: "generated_medium" + seed: 1411 + in: + queries: + gen: "array" + len: 40 + of: + gen: "int" + min: 1 + max: 60 + distinct: false + elemType: "int" + m: 60 + - name: "generated_boundary" + seed: 1412 + in: + queries: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + elemType: "int" + m: 1000 + - name: "generated_large_full" + seed: 1413 + in: + queries: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + elemType: "int" + m: 1000 + - name: "generated_large_repeated_domain" + seed: 1414 + in: + queries: + gen: "array" + len: 999 + of: + gen: "int" + min: 1 + max: 999 + distinct: false + elemType: "int" + m: 999 diff --git a/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.cpp b/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.cpp new file mode 100644 index 00000000..65ffe002 --- /dev/null +++ b/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + vector processQueries(vector& queries, int m) { + vector ans; + vector arr; + for (int i = 1; i <= m; i++) { + arr.push_back(i); + } + for (int x : queries) { + int idx = -1; + for (int j = 0; j < arr.size(); j++) { + if (arr[j] == x) { + idx = j; + break; + } + } + ans.push_back(idx); + arr.erase(arr.begin() + idx); + arr.insert(arr.begin(), x); + } + return ans; + } +}; diff --git a/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.cs b/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.cs new file mode 100644 index 00000000..c18e6658 --- /dev/null +++ b/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.cs @@ -0,0 +1,17 @@ +public class Solution { + public int[] ProcessQueries(int[] queries, int m) { + int[] ans = new int[queries.Length]; + List arr = new List(); + for (int i = 1; i <= m; i++) { + arr.Add(i); + } + for (int i = 0; i < queries.Length; i++) { + int x = queries[i]; + int idx = arr.IndexOf(x); + ans[i] = idx; + arr.RemoveAt(idx); + arr.Insert(0, x); + } + return ans; + } +} diff --git a/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.dart b/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.dart new file mode 100644 index 00000000..46a1a711 --- /dev/null +++ b/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.dart @@ -0,0 +1,13 @@ +class Solution { + List processQueries(List queries, int m) { + List ans = []; + List arr = List.generate(m, (i) => i + 1); + for (int x in queries) { + int idx = arr.indexOf(x); + ans.add(idx); + arr.removeAt(idx); + arr.insert(0, x); + } + return ans; + } +} diff --git a/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.go b/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.go new file mode 100644 index 00000000..52a80115 --- /dev/null +++ b/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.go @@ -0,0 +1,20 @@ +func processQueries(queries []int, m int) []int { + ans := make([]int, len(queries)) + arr := make([]int, m) + for i := 1; i <= m; i++ { + arr[i-1] = i + } + for i, x := range queries { + idx := -1 + for j, v := range arr { + if v == x { + idx = j + break + } + } + ans[i] = idx + arr = append(arr[:idx], arr[idx+1:]...) + arr = append([]int{x}, arr...) + } + return ans +} diff --git a/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.java b/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.java new file mode 100644 index 00000000..b9f0fa2a --- /dev/null +++ b/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.java @@ -0,0 +1,17 @@ +class Solution { + public int[] processQueries(int[] queries, int m) { + int[] ans = new int[queries.length]; + List arr = new ArrayList<>(); + for (int i = 1; i <= m; i++) { + arr.add(i); + } + for (int i = 0; i < queries.length; i++) { + int x = queries[i]; + int idx = arr.indexOf(x); + ans[i] = idx; + arr.remove(idx); + arr.add(0, x); + } + return ans; + } +} diff --git a/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.kt b/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.kt new file mode 100644 index 00000000..dab9ef30 --- /dev/null +++ b/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.kt @@ -0,0 +1,17 @@ +class Solution { + fun processQueries(queries: IntArray, m: Int): IntArray { + val ans = IntArray(queries.size) + val arr = mutableListOf() + for (i in 1..m) { + arr.add(i) + } + for (i in queries.indices) { + val x = queries[i] + val idx = arr.indexOf(x) + ans[i] = idx + arr.removeAt(idx) + arr.add(0, x) + } + return ans + } +} diff --git a/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.py b/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.py new file mode 100644 index 00000000..3e839f78 --- /dev/null +++ b/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.py @@ -0,0 +1,14 @@ +from typing import List + + +class Solution: + def processQueries(self, queries: List[int], m: int) -> List[int]: + arr = [] + ans = [] + for i in range(1, m + 1): + arr.append(i) + for x in queries: + ans.append(arr.index(x)) + arr.remove(x) + arr.insert(0, x) + return ans diff --git a/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.py2 b/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.py2 new file mode 100644 index 00000000..fd2c5231 --- /dev/null +++ b/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def processQueries(self, queries, m): + """ + :type queries: List[int] + :type m: int + :rtype: List[int] + """ + arr = [] + ans = [] + for i in range(1, m + 1): + arr.append(i) + for x in queries: + ans.append(arr.index(x)) + arr.remove(x) + arr.insert(0, x) + return ans diff --git a/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.rb b/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.rb new file mode 100644 index 00000000..4cf181cd --- /dev/null +++ b/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.rb @@ -0,0 +1,13 @@ +# @param {Integer[]} queries +# @param {Integer} m +# @return {Integer[]} +def process_queries(queries, m) + arr = (1..m).to_a + ans = [] + queries.each do |x| + ans << arr.index(x) + arr.delete(x) + arr.unshift(x) + end + ans +end diff --git a/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.rs b/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.rs new file mode 100644 index 00000000..83733423 --- /dev/null +++ b/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.rs @@ -0,0 +1,13 @@ +impl Solution { + pub fn process_queries(queries: Vec, m: i32) -> Vec { + let mut ans: Vec = Vec::new(); + let mut arr: Vec = (1..=m).collect(); + for &x in &queries { + let idx = arr.iter().position(|&v| v == x).unwrap() as i32; + ans.push(idx); + arr.remove(idx as usize); + arr.insert(0, x); + } + ans + } +} diff --git a/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.swift b/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.swift new file mode 100644 index 00000000..cdfb4f57 --- /dev/null +++ b/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.swift @@ -0,0 +1,13 @@ +class Solution { + func processQueries(_ queries: [Int], _ m: Int) -> [Int] { + var ans: [Int] = [] + var arr = Array(1...m) + for x in queries { + let idx = arr.firstIndex(of: x)! + ans.append(idx) + arr.remove(at: idx) + arr.insert(x, at: 0) + } + return ans + } +} diff --git a/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.ts b/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.ts new file mode 100644 index 00000000..420b8442 --- /dev/null +++ b/tests/1001-1500/1409. queries-on-a-permutation-with-key/sol.ts @@ -0,0 +1,14 @@ +function processQueries(queries: number[], m: number): number[] { + const ans: number[] = []; + const arr: number[] = []; + for (let i = 1; i <= m; i++) { + arr.push(i); + } + for (const x of queries) { + const idx = arr.indexOf(x); + ans.push(idx); + arr.splice(idx, 1); + arr.unshift(x); + } + return ans; +} diff --git a/tests/1001-1500/1410. html-entity-parser/manifest.yaml b/tests/1001-1500/1410. html-entity-parser/manifest.yaml new file mode 100644 index 00000000..e2b37235 --- /dev/null +++ b/tests/1001-1500/1410. html-entity-parser/manifest.yaml @@ -0,0 +1,201 @@ +entry: + id: 1410 + title: html-entity-parser + params: + text: + type: string + call: + cpp: "Solution().entityParser({text})" + rust: "Solution::entity_parser({text})" + python3: "Solution().entityParser({text})" + python2: "Solution().entityParser({text})" + ruby: "entity_parser({text})" + java: "new Solution().entityParser({text})" + csharp: "new Solution().EntityParser({text})" + kotlin: "Solution().entityParser({text})" + go: "entityParser({text})" + dart: "Solution().entityParser({text})" + swift: "Solution().entityParser({text})" + typescript: "entityParser({text})" + +judge: + type: exact + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().entityParser(text, {result})" + checker: | + class Checker: + def entityParser(self, text, result): + replacements = { + """: '"', + "'": "'", + "&": "&", + ">": ">", + "<": "<", + "⁄": "/", + } + expected = [] + i = 0 + while i < len(text): + if text[i] != "&": + expected.append(text[i]) + i += 1 + continue + end = i + 1 + while end < len(text) and text[end] not in ";&" and not text[end].isspace(): + end += 1 + if end < len(text) and text[end] == ";": + token = text[i:end + 1] + expected.append(replacements.get(token, token)) + i = end + 1 + else: + expected.append("&") + i += 1 + return result == "".join(expected) + +seed: 1410 + +tests: + - name: example_ampersand + in: + text: "& is an HTML entity but &ambassador; is not." + - name: example_quotes + in: + text: "and I quote: "..."" + - name: single_character_entity + in: + text: "&" + - name: all_supported_entities + in: + text: ""'&><⁄" + - name: adjacent_entities + in: + text: "<>&"'⁄" + - name: entity_between_words + in: + text: "left&right" + - name: html_fragment + in: + text: "<p>Tom&Jerry</p>" + - name: quoted_attribute + in: + text: "<div title="a&b">ok</div>" + - name: slash_path + in: + text: "https:&frasl;&frasl;example.com&frasl;a" + - name: repeated_ampersands + in: + text: "&&&&&" + - name: repeated_quotes + in: + text: ""a""b""c"" + - name: repeated_apostrophes + in: + text: "'one' 'two'" + - name: comparison_expression + in: + text: "a < b && b > a" + - name: whitespace_preserved + in: + text: " < x > " + - name: newline_preserved + in: + text: "line1&line2\\nline3" + - name: ordinary_ampersand + in: + text: "rock & roll" + - name: malformed_without_semicolon + in: + text: "keep & and < unchanged" + - name: malformed_with_space + in: + text: "& value; < other;" + - name: unknown_entities + in: + text: "© &unknown; &ersand;" + - name: partial_entity_names + in: + text: "&am; &quo; &fr;" + - name: case_sensitive_names + in: + text: "& ≪ > <" + - name: double_encoded + in: + text: "&amp; &lt; &quot;" + - name: entity_after_entity + in: + text: "&<&>" + - name: ampersand_before_entity + in: + text: "&& &" + - name: ampersand_inside_candidate + in: + text: "&foo& &bar;" + - name: semicolon_without_ampersand + in: + text: "a;b;c;;;" + - name: punctuation_and_entities + in: + text: "("hello"), ['world']!" + - name: unicode_untouched + in: + text: "cafe eclair & tea" + - name: ascii_punctuation + in: + text: "!#$%()*+,-./: \\t" + - name: generated_large_mixed + in: + text: + gen: str + len: 90000 + alphabet: "aeiou&; -_" + - name: generated_maximum_length + in: + text: + gen: str + len: 100000 + alphabet: "x&;quot " + - name: generated_entity_focused + in: + text: + gen: str + len: 12000 + alphabet: "&;ampltgrefsqu o" diff --git a/tests/1001-1500/1410. html-entity-parser/sol.cpp b/tests/1001-1500/1410. html-entity-parser/sol.cpp new file mode 100644 index 00000000..a9388c8c --- /dev/null +++ b/tests/1001-1500/1410. html-entity-parser/sol.cpp @@ -0,0 +1,42 @@ +class Solution { +public: + string entityParser(string text) { + unordered_map entities = { + {""", "\""}, + {"&apos", "'"}, + {"&", "&"}, + {">", ">"}, + {"<", "<"}, + {"&frasl", "/"} + }; + string result; + size_t i = 0; + while (i < text.size()) { + if (text[i] != '&') { + result += text[i++]; + continue; + } + + size_t end = i + 1; + while (end < text.size() && text[end] != ';' && + text[end] != '&' && + !isspace(static_cast(text[end]))) { + ++end; + } + if (end < text.size() && text[end] == ';') { + string entity = text.substr(i, end - i); + auto it = entities.find(entity); + if (it != entities.end()) { + result += it->second; + } else { + result.append(text, i, end - i + 1); + } + i = end + 1; + } else { + result += '&'; + ++i; + } + } + return result; + } +}; diff --git a/tests/1001-1500/1410. html-entity-parser/sol.cs b/tests/1001-1500/1410. html-entity-parser/sol.cs new file mode 100644 index 00000000..f29979c0 --- /dev/null +++ b/tests/1001-1500/1410. html-entity-parser/sol.cs @@ -0,0 +1,20 @@ +public class Solution { + public string EntityParser(string text) { + var entities = new Dictionary { + {""", "\""}, + {"&apos", "'"}, + {"&", "&"}, + {">", ">"}, + {"<", "<"}, + {"&frasl", "/"} + }; + + var pattern = new Regex(@"&[^;&\s]+;"); + + return pattern.Replace(text, match => { + string matched = match.Value; + string entity = matched.Substring(0, matched.Length - 1); + return entities.ContainsKey(entity) ? entities[entity] : matched; + }); + } +} diff --git a/tests/1001-1500/1410. html-entity-parser/sol.dart b/tests/1001-1500/1410. html-entity-parser/sol.dart new file mode 100644 index 00000000..94763ea2 --- /dev/null +++ b/tests/1001-1500/1410. html-entity-parser/sol.dart @@ -0,0 +1,20 @@ +class Solution { + String entityParser(String text) { + final entities = { + """: '"', + "&apos": "'", + "&": "&", + ">": ">", + "<": "<", + "&frasl": "/" + }; + + final pattern = RegExp(r'&[^;&\s]+;'); + + return text.replaceAllMapped(pattern, (match) { + final matched = match.group(0)!; + final entity = matched.substring(0, matched.length - 1); + return entities.containsKey(entity) ? entities[entity]! : matched; + }); + } +} diff --git a/tests/1001-1500/1410. html-entity-parser/sol.go b/tests/1001-1500/1410. html-entity-parser/sol.go new file mode 100644 index 00000000..3b8514eb --- /dev/null +++ b/tests/1001-1500/1410. html-entity-parser/sol.go @@ -0,0 +1,20 @@ +func entityParser(text string) string { + entities := map[string]string{ + """: "\"", + "&apos": "'", + "&": "&", + ">": ">", + "<": "<", + "&frasl": "/", + } + + re := regexp.MustCompile(`&[^;&\s]+;`) + + return re.ReplaceAllStringFunc(text, func(match string) string { + entity := match[:len(match)-1] + if val, ok := entities[entity]; ok { + return val + } + return match + }) +} diff --git a/tests/1001-1500/1410. html-entity-parser/sol.java b/tests/1001-1500/1410. html-entity-parser/sol.java new file mode 100644 index 00000000..d78b7147 --- /dev/null +++ b/tests/1001-1500/1410. html-entity-parser/sol.java @@ -0,0 +1,25 @@ +class Solution { + public String entityParser(String text) { + java.util.Map entities = new java.util.HashMap<>(); + entities.put(""", "\""); + entities.put("&apos", "'"); + entities.put("&", "&"); + entities.put(">", ">"); + entities.put("<", "<"); + entities.put("&frasl", "/"); + + java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("&[^;&\\s]+;"); + java.util.regex.Matcher matcher = pattern.matcher(text); + + StringBuffer result = new StringBuffer(); + while (matcher.find()) { + String match = matcher.group(); + String entity = match.substring(0, match.length() - 1); + String replacement = entities.getOrDefault(entity, match); + matcher.appendReplacement(result, java.util.regex.Matcher.quoteReplacement(replacement)); + } + matcher.appendTail(result); + + return result.toString(); + } +} diff --git a/tests/1001-1500/1410. html-entity-parser/sol.kt b/tests/1001-1500/1410. html-entity-parser/sol.kt new file mode 100644 index 00000000..5fc233c5 --- /dev/null +++ b/tests/1001-1500/1410. html-entity-parser/sol.kt @@ -0,0 +1,20 @@ +class Solution { + fun entityParser(text: String): String { + val entities = mapOf( + """ to "\"", + "&apos" to "'", + "&" to "&", + ">" to ">", + "<" to "<", + "&frasl" to "/" + ) + + val pattern = Regex("&[^;&\\s]+;") + + return pattern.replace(text) { matchResult -> + val match = matchResult.value + val entity = match.dropLast(1) + entities.getOrDefault(entity, match) + } + } +} diff --git a/tests/1001-1500/1410. html-entity-parser/sol.py b/tests/1001-1500/1410. html-entity-parser/sol.py new file mode 100644 index 00000000..8951d987 --- /dev/null +++ b/tests/1001-1500/1410. html-entity-parser/sol.py @@ -0,0 +1,21 @@ +import re + + +class Solution: + def entityParser(self, text: str) -> str: + entities = { + """: '"', + "&apos": "'", + "&": "&", + ">": ">", + "<": "<", + "&frasl": "/", + } + + pattern = r"&[^;&\s]+;" + + def replacer(match): + entity = match.group(0)[:-1] # remove trailing ';' + return entities.get(entity, match.group(0)) + + return re.sub(pattern, replacer, text) diff --git a/tests/1001-1500/1410. html-entity-parser/sol.py2 b/tests/1001-1500/1410. html-entity-parser/sol.py2 new file mode 100644 index 00000000..856cc909 --- /dev/null +++ b/tests/1001-1500/1410. html-entity-parser/sol.py2 @@ -0,0 +1,23 @@ +class Solution(object): + def entityParser(self, text): + """ + :type text: str + :rtype: str + """ + entities = { + """: '"', + "&apos": "'", + "&": "&", + ">": ">", + "<": "<", + "&frasl": "/" + } + + import re + pattern = r'&[^;&\s]+;' + + def replacer(match): + entity = match.group(0)[:-1] + return entities.get(entity, match.group(0)) + + return re.sub(pattern, replacer, text) diff --git a/tests/1001-1500/1410. html-entity-parser/sol.rb b/tests/1001-1500/1410. html-entity-parser/sol.rb new file mode 100644 index 00000000..2b5fd8b0 --- /dev/null +++ b/tests/1001-1500/1410. html-entity-parser/sol.rb @@ -0,0 +1,17 @@ +# @param {String} text +# @return {String} +def entity_parser(text) + entities = { + """ => '"', + "&apos" => "'", + "&" => "&", + ">" => ">", + "<" => "<", + "&frasl" => "/" + } + + text.gsub(/&[^;&\s]+;/) do |match| + entity = match[0...-1] + entities.fetch(entity, match) + end +end diff --git a/tests/1001-1500/1410. html-entity-parser/sol.rs b/tests/1001-1500/1410. html-entity-parser/sol.rs new file mode 100644 index 00000000..269b8f6b --- /dev/null +++ b/tests/1001-1500/1410. html-entity-parser/sol.rs @@ -0,0 +1,62 @@ +impl Solution { + pub fn entity_parser(text: String) -> String { + use std::collections::HashMap; + + let mut entities = HashMap::new(); + entities.insert(""", "\""); + entities.insert("&apos", "'"); + entities.insert("&", "&"); + entities.insert(">", ">"); + entities.insert("<", "<"); + entities.insert("&frasl", "/"); + + let bytes = text.as_bytes(); + let mut result = String::new(); + let mut i = 0; + while i < bytes.len() { + if bytes[i] != b'&' { + result.push(bytes[i] as char); + i += 1; + continue; + } + + let mut end = i + 1; + while end < bytes.len() + && bytes[end] != b';' + && bytes[end] != b'&' + && !bytes[end].is_ascii_whitespace() + { + end += 1; + } + if end < bytes.len() && bytes[end] == b';' { + let entity = &text[i..end]; + if let Some(replacement) = entities.get(entity) { + result.push_str(replacement); + } else { + result.push_str(&text[i..=end]); + } + i = end + 1; + } else { + result.push('&'); + i += 1; + } + } + let mut escaped = String::with_capacity(result.len()); + for ch in result.chars() { + match ch { + '"' => escaped.push_str("\\\""), + '\\' => escaped.push_str("\\\\"), + '\n' => escaped.push_str("\\n"), + '\r' => escaped.push_str("\\r"), + '\t' => escaped.push_str("\\t"), + '\u{08}' => escaped.push_str("\\b"), + '\u{0c}' => escaped.push_str("\\f"), + ch if ch < '\u{20}' => { + escaped.push_str(&format!("\\u{:04x}", ch as u32)); + } + ch => escaped.push(ch), + } + } + escaped + } +} diff --git a/tests/1001-1500/1410. html-entity-parser/sol.swift b/tests/1001-1500/1410. html-entity-parser/sol.swift new file mode 100644 index 00000000..76860c46 --- /dev/null +++ b/tests/1001-1500/1410. html-entity-parser/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func entityParser(_ text: String) -> String { + let entities: [String: String] = [ + """: "\"", + "&apos": "'", + "&": "&", + ">": ">", + "<": "<", + "&frasl": "/" + ] + + let pattern = #/&[^;&\s]+;/# + + return text.replacing(pattern) { match in + let matched = String(match.output) + let entity = String(matched.dropLast()) + return entities[entity] ?? matched + } + } +} diff --git a/tests/1001-1500/1410. html-entity-parser/sol.ts b/tests/1001-1500/1410. html-entity-parser/sol.ts new file mode 100644 index 00000000..c7299649 --- /dev/null +++ b/tests/1001-1500/1410. html-entity-parser/sol.ts @@ -0,0 +1,17 @@ +function entityParser(text: string): string { + const entities: Record = { + """: '"', + "&apos": "'", + "&": "&", + ">": ">", + "<": "<", + "&frasl": "/", + }; + + const pattern = /&[^;&\s]+;/g; + + return text.replace(pattern, (match) => { + const entity = match.slice(0, -1); + return entities[entity] || match; + }); +} diff --git a/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/manifest.yaml b/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/manifest.yaml new file mode 100644 index 00000000..8c795862 --- /dev/null +++ b/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/manifest.yaml @@ -0,0 +1,182 @@ +entry: + id: 1411 + title: "number-of-ways-to-paint-n-3-grid" + params: + n: + type: int + call: + cpp: "Solution().numOfWays({n})" + rust: "Solution::num_of_ways({n})" + python3: "Solution().numOfWays({n})" + python2: "Solution().numOfWays({n})" + ruby: "num_of_ways({n})" + java: "new Solution().numOfWays({n})" + csharp: "new Solution().NumOfWays({n})" + kotlin: "Solution().numOfWays({n})" + go: "numOfWays({n})" + dart: "Solution().numOfWays({n})" + swift: "Solution().numOfWays({n})" + typescript: "numOfWays({n})" +judge: + type: "exact" +limits: + time_ms: 500 + memory_mb: 300 +oracle: + python3: + call: "Checker().numOfWays(n, {result})" + checker: | + class Checker: + def numOfWays(self, n, result): + if not isinstance(n, int) or isinstance(n, bool) or not 1 <= n <= 5000: + return False + if not isinstance(result, int) or isinstance(result, bool): + return False + mod = 1000000007 + if n == 1: + expected = 12 + else: + previous, current = 12, 54 + for _ in range(3, n + 1): + previous, current = current, (5 * current - 2 * previous) % mod + expected = current + return result == expected +seed: 1411 +tests: + - name: n1 + in: + n: 1 + out: 12 + - name: n2 + in: + n: 2 + - name: n3 + in: + n: 3 + - name: n4 + in: + n: 4 + - name: n5 + in: + n: 5 + - name: n6 + in: + n: 6 + - name: n7 + in: + n: 7 + - name: n8 + in: + n: 8 + - name: n9 + in: + n: 9 + - name: n10 + in: + n: 10 + - name: n11 + in: + n: 11 + - name: n12 + in: + n: 12 + - name: n13 + in: + n: 13 + - name: n14 + in: + n: 14 + - name: n15 + in: + n: 15 + - name: n16 + in: + n: 16 + - name: n17 + in: + n: 17 + - name: n18 + in: + n: 18 + - name: n19 + in: + n: 19 + - name: n20 + in: + n: 20 + - name: n21 + in: + n: 21 + - name: n22 + in: + n: 22 + - name: n23 + in: + n: 23 + - name: n24 + in: + n: 24 + - name: n25 + in: + n: 25 + - name: n31 + in: + n: 31 + - name: n42 + in: + n: 42 + - name: n63 + in: + n: 63 + - name: n100 + in: + n: 100 + - name: n250 + in: + n: 250 + - name: n500 + in: + n: 500 + - name: n1000 + in: + n: 1000 + - name: n2048 + in: + n: 2048 + - name: n3000 + in: + n: 3000 + - name: n5000 + in: + n: 5000 + out: 30228214 + - name: generated-small + in: + n: + gen: "int" + min: 1 + max: 5000 + - name: generated-midrange + in: + n: + gen: "int" + min: 100 + max: 4900 + - name: generated-near-min + in: + n: + gen: "int" + min: 1 + max: 25 + - name: generated-near-max + in: + n: + gen: "int" + min: 4975 + max: 5000 + - name: generated-wide + in: + n: + gen: "int" + min: 2000 + max: 5000 diff --git a/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.cpp b/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.cpp new file mode 100644 index 00000000..c28433c4 --- /dev/null +++ b/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int numOfWays(int n) { + const int MOD = 1000000007; + long long x = 6, y = 6; + + for (int i = 2; i <= n; i++) { + long long newX = (3 * x + 2 * y) % MOD; + long long newY = (2 * x + 2 * y) % MOD; + x = newX; + y = newY; + } + + return (int)((x + y) % MOD); + } +}; diff --git a/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.cs b/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.cs new file mode 100644 index 00000000..84d7b4f8 --- /dev/null +++ b/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.cs @@ -0,0 +1,15 @@ +public class Solution { + public int NumOfWays(int n) { + const int MOD = 1000000007; + long x = 6, y = 6; + + for (int i = 2; i <= n; i++) { + long newX = (3 * x + 2 * y) % MOD; + long newY = (2 * x + 2 * y) % MOD; + x = newX; + y = newY; + } + + return (int)((x + y) % MOD); + } +} diff --git a/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.dart b/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.dart new file mode 100644 index 00000000..6e0a8850 --- /dev/null +++ b/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.dart @@ -0,0 +1,15 @@ +class Solution { + int numOfWays(int n) { + const MOD = 1000000007; + int x = 6, y = 6; + + for (int i = 2; i <= n; i++) { + int newX = (3 * x + 2 * y) % MOD; + int newY = (2 * x + 2 * y) % MOD; + x = newX; + y = newY; + } + + return (x + y) % MOD; + } +} diff --git a/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.go b/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.go new file mode 100644 index 00000000..f0ea91be --- /dev/null +++ b/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.go @@ -0,0 +1,12 @@ +func numOfWays(n int) int { + const MOD = 1000000007 + x, y := 6, 6 + + for i := 2; i <= n; i++ { + newX := (3*x + 2*y) % MOD + newY := (2*x + 2*y) % MOD + x, y = newX, newY + } + + return (x + y) % MOD +} diff --git a/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.java b/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.java new file mode 100644 index 00000000..9b28a01f --- /dev/null +++ b/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.java @@ -0,0 +1,15 @@ +class Solution { + public int numOfWays(int n) { + final int MOD = 1000000007; + long x = 6, y = 6; + + for (int i = 2; i <= n; i++) { + long newX = (3 * x + 2 * y) % MOD; + long newY = (2 * x + 2 * y) % MOD; + x = newX; + y = newY; + } + + return (int)((x + y) % MOD); + } +} diff --git a/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.kt b/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.kt new file mode 100644 index 00000000..242d9e0c --- /dev/null +++ b/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun numOfWays(n: Int): Int { + val MOD = 1000000007 + var x = 6L + var y = 6L + + for (i in 2..n) { + val newX = (3 * x + 2 * y) % MOD + val newY = (2 * x + 2 * y) % MOD + x = newX + y = newY + } + + return ((x + y) % MOD).toInt() + } +} diff --git a/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.py b/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.py new file mode 100644 index 00000000..edffecfc --- /dev/null +++ b/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.py @@ -0,0 +1,11 @@ +class Solution: + def numOfWays(self, n: int) -> int: + MOD = 1000000007 + x, y = 6, 6 + + for i in range(2, n + 1): + new_x = (3 * x + 2 * y) % MOD + new_y = (2 * x + 2 * y) % MOD + x, y = new_x, new_y + + return (x + y) % MOD diff --git a/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.py2 b/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.py2 new file mode 100644 index 00000000..254913b9 --- /dev/null +++ b/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.py2 @@ -0,0 +1,15 @@ +class Solution(object): + def numOfWays(self, n): + """ + :type n: int + :rtype: int + """ + MOD = 1000000007 + x, y = 6, 6 + + for i in range(2, n + 1): + new_x = (3 * x + 2 * y) % MOD + new_y = (2 * x + 2 * y) % MOD + x, y = new_x, new_y + + return (x + y) % MOD diff --git a/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.rb b/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.rb new file mode 100644 index 00000000..29b9d382 --- /dev/null +++ b/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.rb @@ -0,0 +1,14 @@ +# @param {Integer} n +# @return {Integer} +def num_of_ways(n) + mod = 1000000007 + x, y = 6, 6 + + (2..n).each do |i| + new_x = (3 * x + 2 * y) % mod + new_y = (2 * x + 2 * y) % mod + x, y = new_x, new_y + end + + (x + y) % mod +end diff --git a/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.rs b/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.rs new file mode 100644 index 00000000..aef28cdd --- /dev/null +++ b/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn num_of_ways(n: i32) -> i32 { + const MOD: i64 = 1000000007; + let mut x: i64 = 6; + let mut y: i64 = 6; + + for _ in 2..=n { + let new_x = (3 * x + 2 * y) % MOD; + let new_y = (2 * x + 2 * y) % MOD; + x = new_x; + y = new_y; + } + + ((x + y) % MOD) as i32 + } +} diff --git a/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.swift b/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.swift new file mode 100644 index 00000000..a1d3ea17 --- /dev/null +++ b/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.swift @@ -0,0 +1,18 @@ +class Solution { + func numOfWays(_ n: Int) -> Int { + let MOD = 1000000007 + var x = 6 + var y = 6 + + if n > 1 { + for _ in 2...n { + let newX = (3 * x + 2 * y) % MOD + let newY = (2 * x + 2 * y) % MOD + x = newX + y = newY + } + } + + return (x + y) % MOD + } +} diff --git a/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.ts b/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.ts new file mode 100644 index 00000000..1ff300b5 --- /dev/null +++ b/tests/1001-1500/1411. number-of-ways-to-paint-n-3-grid/sol.ts @@ -0,0 +1,14 @@ +function numOfWays(n: number): number { + const MOD = 1000000007; + let x = 6, + y = 6; + + for (let i = 2; i <= n; i++) { + let newX = (3 * x + 2 * y) % MOD; + let newY = (2 * x + 2 * y) % MOD; + x = newX; + y = newY; + } + + return (x + y) % MOD; +} diff --git a/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/manifest.yaml b/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/manifest.yaml new file mode 100644 index 00000000..6f693abd --- /dev/null +++ b/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/manifest.yaml @@ -0,0 +1,220 @@ +entry: + id: 1413 + title: "minimum-value-to-get-positive-step-by-step-sum" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().minStartValue({nums})" + rust: "Solution::min_start_value({nums})" + python3: "Solution().minStartValue({nums})" + python2: "Solution().minStartValue({nums})" + ruby: "min_start_value({nums})" + java: "new Solution().minStartValue({nums})" + csharp: "new Solution().MinStartValue({nums})" + kotlin: "Solution().minStartValue({nums})" + go: "minStartValue({nums})" + dart: "Solution().minStartValue({nums})" + swift: "Solution().minStartValue({nums})" + typescript: "minStartValue({nums})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().minStartValue(nums, {result})" + checker: | + class Checker: + def minStartValue(self, nums, result): + prefix = 0 + lowest = 0 + for value in nums: + prefix += value + lowest = min(lowest, prefix) + return result == max(1, 1 - lowest) + +seed: 1413 + +tests: + - name: "example-one" + in: + nums: [-3, 2, -3, 4, 2] + out: 5 + - name: "example-two" + in: + nums: [1, 2] + out: 1 + - name: "example-three" + in: + nums: [1, -2, -3] + out: 5 + - name: "single-positive" + in: + nums: [7] + - name: "single-negative" + in: + nums: [-7] + - name: "single-zero" + in: + nums: [0] + - name: "all-positive" + in: + nums: [1, 2, 3, 4, 5] + - name: "all-negative" + in: + nums: [-1, -2, -3, -4] + - name: "zeros-only" + in: + nums: [0, 0, 0, 0, 0] + - name: "negative-first" + in: + nums: [-10, 10, 10] + - name: "negative-last" + in: + nums: [10, 10, -25] + - name: "deepest-prefix" + in: + nums: [-5, -5, -5, 20] + - name: "recovery-before-drop" + in: + nums: [-8, 12, -9] + - name: "alternating-small" + in: + nums: [-1, 1, -1, 1, -1] + - name: "alternating-large" + in: + nums: [-100, 100, -100, 100] + - name: "minimum-element-bound" + in: + nums: [-100] + - name: "maximum-element-bound" + in: + nums: [100] + - name: "balanced-pair" + in: + nums: [50, -50] + - name: "positive-total-negative-prefix" + in: + nums: [-20, 5, 5, 20] + - name: "negative-total-positive-prefix" + in: + nums: [20, -5, -5, -20] + - name: "late-deep-drop" + in: + nums: [10, 10, 10, -50] + - name: "early-deep-drop" + in: + nums: [-50, 10, 10, 10] + - name: "repeated-negative" + in: + nums: [-9, -9, -9, -9, -9] + - name: "repeated-positive" + in: + nums: [9, 9, 9, 9, 9] + - name: "mixed-small-values" + in: + nums: [2, -3, 4, -5, 6, -7] + - name: "mixed-medium-values" + in: + nums: [-20, 15, -10, 12, -8, 7] + - name: "zeros-between-drops" + in: + nums: [-4, 0, 0, -6, 0, 20] + - name: "zero-recovery" + in: + nums: [0, -3, 0, 0, 4] + - name: "exactly-positive-prefixes" + in: + nums: [-1, 2, -1, 2, -1] + - name: "large-recovery" + in: + nums: [-100, 100, 100, -100] + - name: "nine-element-wave" + in: + nums: [-4, 3, -2, 5, -6, 7, -8, 9, -10] + - name: "ten-element-positive" + in: + nums: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + - name: "ten-element-negative" + in: + nums: [-1, -2, -3, -4, -5, -6, -7, -8, -9, -10] + - name: "long-balanced" + in: + nums: [5, -10, 5, -10, 5, -10, 5, -10, 5, 50] + - name: "twenty-element-mixed" + in: + nums: + [1, -2, 3, -4, 5, -6, 7, -8, 9, -10, 10, -9, 8, -7, 6, -5, 4, -3, 2, -1] + - name: "generated-small-general" + seed: 141301 + in: + nums: + gen: "array" + len: + gen: "int" + min: 1 + max: 12 + of: + gen: "int" + min: -100 + max: 100 + distinct: false + sorted: false + - name: "generated-medium-general" + seed: 141302 + in: + nums: + gen: "array" + len: + gen: "int" + min: 13 + max: 50 + of: + gen: "int" + min: -100 + max: 100 + distinct: false + sorted: false + - name: "generated-max-range" + seed: 141303 + in: + nums: + gen: "array" + len: 100 + of: + gen: "int" + min: -100 + max: 100 + distinct: false + sorted: false + - name: "generated-max-negative-biased" + seed: 141304 + in: + nums: + gen: "array" + len: 100 + of: + gen: "int" + min: -100 + max: -1 + distinct: false + sorted: false + - name: "generated-max-positive-biased" + seed: 141305 + in: + nums: + gen: "array" + len: 100 + of: + gen: "int" + min: 0 + max: 100 + distinct: false + sorted: false diff --git a/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.cpp b/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.cpp new file mode 100644 index 00000000..4ab96953 --- /dev/null +++ b/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + int minStartValue(vector& nums) { + int curr = 0, ans = 0; + for (int i : nums) { + curr += i; + if (curr < ans) { + ans = curr; + } + } + return max(ans, 1 - ans); + } +}; diff --git a/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.cs b/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.cs new file mode 100644 index 00000000..421c2e20 --- /dev/null +++ b/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.cs @@ -0,0 +1,12 @@ +public class Solution { + public int MinStartValue(int[] nums) { + int curr = 0, ans = 0; + foreach (int i in nums) { + curr += i; + if (curr < ans) { + ans = curr; + } + } + return Math.Max(ans, 1 - ans); + } +} diff --git a/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.dart b/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.dart new file mode 100644 index 00000000..2ade1dba --- /dev/null +++ b/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.dart @@ -0,0 +1,12 @@ +class Solution { + int minStartValue(List nums) { + int curr = 0, ans = 0; + for (int i in nums) { + curr += i; + if (curr < ans) { + ans = curr; + } + } + return ans > 1 - ans ? ans : 1 - ans; + } +} diff --git a/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.go b/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.go new file mode 100644 index 00000000..e3446172 --- /dev/null +++ b/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.go @@ -0,0 +1,13 @@ +func minStartValue(nums []int) int { + curr, ans := 0, 0 + for _, i := range nums { + curr += i + if curr < ans { + ans = curr + } + } + if ans > 1-ans { + return ans + } + return 1 - ans +} diff --git a/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.java b/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.java new file mode 100644 index 00000000..b4cbae2b --- /dev/null +++ b/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.java @@ -0,0 +1,12 @@ +class Solution { + public int minStartValue(int[] nums) { + int curr = 0, ans = 0; + for (int i : nums) { + curr += i; + if (curr < ans) { + ans = curr; + } + } + return Math.max(ans, 1 - ans); + } +} diff --git a/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.kt b/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.kt new file mode 100644 index 00000000..30b8116b --- /dev/null +++ b/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.kt @@ -0,0 +1,13 @@ +class Solution { + fun minStartValue(nums: IntArray): Int { + var curr = 0 + var ans = 0 + for (i in nums) { + curr += i + if (curr < ans) { + ans = curr + } + } + return maxOf(ans, 1 - ans) + } +} diff --git a/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.py b/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.py new file mode 100644 index 00000000..431840f0 --- /dev/null +++ b/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.py @@ -0,0 +1,8 @@ +class Solution: + def minStartValue(self, nums: List[int]) -> int: + curr = ans = 0 + for i in nums: + curr += i + if curr < ans: + ans = curr + return max(ans, 1 - ans) diff --git a/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.py2 b/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.py2 new file mode 100644 index 00000000..15fc327a --- /dev/null +++ b/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.py2 @@ -0,0 +1,8 @@ +class Solution(object): + def minStartValue(self, nums): + curr = ans = 0 + for i in nums: + curr += i + if curr < ans: + ans = curr + return max(ans, 1 - ans) diff --git a/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.rb b/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.rb new file mode 100644 index 00000000..78b87cb3 --- /dev/null +++ b/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.rb @@ -0,0 +1,12 @@ +# @param {Integer[]} nums +# @return {Integer} +def min_start_value(nums) + curr = ans = 0 + nums.each do |i| + curr += i + if curr < ans + ans = curr + end + end + [ans, 1 - ans].max +end diff --git a/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.rs b/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.rs new file mode 100644 index 00000000..d604f379 --- /dev/null +++ b/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.rs @@ -0,0 +1,13 @@ +impl Solution { + pub fn min_start_value(nums: Vec) -> i32 { + let mut curr = 0; + let mut ans = 0; + for i in nums { + curr += i; + if curr < ans { + ans = curr; + } + } + ans.max(1 - ans) + } +} diff --git a/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.swift b/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.swift new file mode 100644 index 00000000..51737176 --- /dev/null +++ b/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.swift @@ -0,0 +1,13 @@ +class Solution { + func minStartValue(_ nums: [Int]) -> Int { + var curr = 0 + var ans = 0 + for i in nums { + curr += i + if curr < ans { + ans = curr + } + } + return max(ans, 1 - ans) + } +} diff --git a/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.ts b/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.ts new file mode 100644 index 00000000..61c968b9 --- /dev/null +++ b/tests/1001-1500/1413. minimum-value-to-get-positive-step-by-step-sum/sol.ts @@ -0,0 +1,11 @@ +function minStartValue(nums: number[]): number { + let curr = 0, + ans = 0; + for (const i of nums) { + curr += i; + if (curr < ans) { + ans = curr; + } + } + return Math.max(ans, 1 - ans); +} diff --git a/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/manifest.yaml b/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/manifest.yaml new file mode 100644 index 00000000..6d36074e --- /dev/null +++ b/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/manifest.yaml @@ -0,0 +1,189 @@ +entry: + id: 1414 + title: "find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k" + params: + k: + type: int + call: + cpp: "Solution().findMinFibonacciNumbers({k})" + rust: "Solution::find_min_fibonacci_numbers({k})" + python3: "Solution().findMinFibonacciNumbers({k})" + python2: "Solution().findMinFibonacciNumbers({k})" + ruby: "find_min_fibonacci_numbers({k})" + java: "new Solution().findMinFibonacciNumbers({k})" + csharp: "new Solution().FindMinFibonacciNumbers({k})" + kotlin: "Solution().findMinFibonacciNumbers({k})" + go: "findMinFibonacciNumbers({k})" + dart: "Solution().findMinFibonacciNumbers({k})" + swift: "Solution().findMinFibonacciNumbers({k})" + typescript: "findMinFibonacciNumbers({k})" + +judge: + type: "exact" + +limits: + time_ms: 500 + memory_mb: 256 + +oracle: + python3: + call: "Checker().findMinFibonacciNumbers(k, {result})" + checker: | + class Checker: + def findMinFibonacciNumbers(self, k, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + fib = [1, 2] + while fib[-1] < k: + fib.append(fib[-1] + fib[-2]) + remaining = k + expected = 0 + for value in reversed(fib): + if value <= remaining: + remaining -= value + expected += 1 + return remaining == 0 and result == expected + +seed: 1414 + +tests: + - name: "example-seven" + in: + k: 7 + - name: "example-ten" + in: + k: 10 + - name: "example-nineteen" + in: + k: 19 + - name: "minimum-one" + in: + k: 1 + - name: "duplicate-one-boundary" + in: + k: 2 + - name: "small-three" + in: + k: 3 + - name: "small-four" + in: + k: 4 + - name: "fibonacci-five" + in: + k: 5 + - name: "fibonacci-eight" + in: + k: 8 + - name: "fibonacci-thirteen" + in: + k: 13 + - name: "fibonacci-twenty-one" + in: + k: 21 + - name: "fibonacci-thirty-four" + in: + k: 34 + - name: "below-fibonacci-thirteen" + in: + k: 12 + - name: "above-fibonacci-thirteen" + in: + k: 14 + - name: "below-fibonacci-fifty-five" + in: + k: 54 + - name: "above-fibonacci-fifty-five" + in: + k: 56 + - name: "zeckendorf-adjacent" + in: + k: 42 + - name: "many-small-summands" + in: + k: 100 + - name: "round-hundred" + in: + k: 1000 + - name: "power-two-sixteen" + in: + k: 16 + - name: "power-two-one-twenty-eight" + in: + k: 128 + - name: "power-two-one-thousand-twenty-four" + in: + k: 1024 + - name: "near-thousand" + in: + k: 999 + - name: "near-million" + in: + k: 999999 + - name: "million" + in: + k: 1000000 + - name: "large-nine-digits" + in: + k: 123456789 + - name: "large-patterned" + in: + k: 400000000 + - name: "near-maximum" + in: + k: 999999999 + - name: "maximum" + in: + k: 1000000000 + - name: "boundary-forty-four" + in: + k: 44 + - name: "boundary-eighty-eight" + in: + k: 88 + - name: "boundary-one-forty-four" + in: + k: 144 + - name: "boundary-two-thirty-three" + in: + k: 233 + - name: "boundary-three-seven-seven" + in: + k: 377 + - name: "boundary-six-one-zero" + in: + k: 610 + - name: "generated-min-range" + seed: 141401 + in: + k: + gen: "int" + min: 1 + max: 100 + - name: "generated-small-range" + seed: 141402 + in: + k: + gen: "int" + min: 101 + max: 10000 + - name: "generated-medium-range" + seed: 141403 + in: + k: + gen: "int" + min: 10001 + max: 1000000 + - name: "generated-large-range" + seed: 141404 + in: + k: + gen: "int" + min: 1000001 + max: 999999999 + - name: "generated-full-constraint-range" + seed: 141405 + in: + k: + gen: "int" + min: 1 + max: 1000000000 diff --git a/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.cpp b/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.cpp new file mode 100644 index 00000000..058f0947 --- /dev/null +++ b/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int findMinFibonacciNumbers(int k) { + vector fib = {1, 1}; + while (fib.back() <= k) { + fib.push_back(fib[fib.size() - 1] + fib[fib.size() - 2]); + } + + int count = 0; + int i = fib.size() - 1; + + while (k > 0) { + if (fib[i] <= k) { + k -= fib[i]; + count++; + } + i--; + } + + return count; + } +}; diff --git a/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.cs b/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.cs new file mode 100644 index 00000000..cfd0a175 --- /dev/null +++ b/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.cs @@ -0,0 +1,21 @@ +public class Solution { + public int FindMinFibonacciNumbers(int k) { + List fib = new List {1, 1}; + while (fib[fib.Count - 1] <= k) { + fib.Add(fib[fib.Count - 1] + fib[fib.Count - 2]); + } + + int count = 0; + int i = fib.Count - 1; + + while (k > 0) { + if (fib[i] <= k) { + k -= fib[i]; + count++; + } + i--; + } + + return count; + } +} diff --git a/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.dart b/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.dart new file mode 100644 index 00000000..59fc3d2d --- /dev/null +++ b/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.dart @@ -0,0 +1,21 @@ +class Solution { + int findMinFibonacciNumbers(int k) { + List fib = [1, 1]; + while (fib.last <= k) { + fib.add(fib[fib.length - 1] + fib[fib.length - 2]); + } + + int count = 0; + int i = fib.length - 1; + + while (k > 0) { + if (fib[i] <= k) { + k -= fib[i]; + count++; + } + i--; + } + + return count; + } +} diff --git a/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.go b/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.go new file mode 100644 index 00000000..eafd523e --- /dev/null +++ b/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.go @@ -0,0 +1,19 @@ +func findMinFibonacciNumbers(k int) int { + fib := []int{1, 1} + for fib[len(fib)-1] <= k { + fib = append(fib, fib[len(fib)-1] + fib[len(fib)-2]) + } + + count := 0 + i := len(fib) - 1 + + for k > 0 { + if fib[i] <= k { + k -= fib[i] + count++ + } + i-- + } + + return count +} diff --git a/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.java b/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.java new file mode 100644 index 00000000..1bc0d52d --- /dev/null +++ b/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.java @@ -0,0 +1,23 @@ +class Solution { + public int findMinFibonacciNumbers(int k) { + java.util.ArrayList fib = new java.util.ArrayList<>(); + fib.add(1); + fib.add(1); + while (fib.get(fib.size() - 1) <= k) { + fib.add(fib.get(fib.size() - 1) + fib.get(fib.size() - 2)); + } + + int count = 0; + int i = fib.size() - 1; + + while (k > 0) { + if (fib.get(i) <= k) { + k -= fib.get(i); + count++; + } + i--; + } + + return count; + } +} diff --git a/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.kt b/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.kt new file mode 100644 index 00000000..7cb8d0ee --- /dev/null +++ b/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.kt @@ -0,0 +1,22 @@ +class Solution { + fun findMinFibonacciNumbers(k: Int): Int { + val fib = mutableListOf(1, 1) + while (fib.last() <= k) { + fib.add(fib[fib.size - 1] + fib[fib.size - 2]) + } + + var count = 0 + var i = fib.size - 1 + var remaining = k + + while (remaining > 0) { + if (fib[i] <= remaining) { + remaining -= fib[i] + count++ + } + i-- + } + + return count + } +} diff --git a/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.py b/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.py new file mode 100644 index 00000000..edea6c2b --- /dev/null +++ b/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.py @@ -0,0 +1,20 @@ +class Solution(object): + def findMinFibonacciNumbers(self, k): + """ + :type k: int + :rtype: int + """ + fib = [1, 1] + while fib[-1] <= k: + fib.append(fib[-1] + fib[-2]) + + count = 0 + i = len(fib) - 1 + + while k > 0: + if fib[i] <= k: + k -= fib[i] + count += 1 + i -= 1 + + return count diff --git a/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.py2 b/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.py2 new file mode 100644 index 00000000..3116e588 --- /dev/null +++ b/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.py2 @@ -0,0 +1,20 @@ +class Solution(object): + def findMinFibonacciNumbers(self, k): + """ + :type k: int + :rtype: int + """ + fib = [1, 1] + while fib[-1] <= k: + fib.append(fib[-1] + fib[-2]) + + count = 0 + i = len(fib) - 1 + + while k > 0: + if fib[i] <= k: + k -= fib[i] + count += 1 + i -= 1 + + return count diff --git a/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.rb b/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.rb new file mode 100644 index 00000000..bdaba9ba --- /dev/null +++ b/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.rb @@ -0,0 +1,21 @@ +# @param {Integer} k +# @return {Integer} +def find_min_fibonacci_numbers(k) + fib = [1, 1] + while fib[-1] <= k + fib.push(fib[-1] + fib[-2]) + end + + count = 0 + i = fib.length - 1 + + while k > 0 + if fib[i] <= k + k -= fib[i] + count += 1 + end + i -= 1 + end + + count +end diff --git a/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.rs b/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.rs new file mode 100644 index 00000000..df5d2463 --- /dev/null +++ b/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.rs @@ -0,0 +1,27 @@ +impl Solution { + pub fn find_min_fibonacci_numbers(k: i32) -> i32 { + let mut fib = vec![1, 1]; + while fib[fib.len() - 1] <= k { + let next = fib[fib.len() - 1] + fib[fib.len() - 2]; + fib.push(next); + } + + let mut count = 0; + let mut i = fib.len() - 1; + let mut remaining = k; + + while remaining > 0 { + if fib[i] <= remaining { + remaining -= fib[i]; + count += 1; + } + if i > 0 { + i -= 1; + } else { + break; + } + } + + count + } +} diff --git a/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.swift b/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.swift new file mode 100644 index 00000000..9b765d3e --- /dev/null +++ b/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.swift @@ -0,0 +1,22 @@ +class Solution { + func findMinFibonacciNumbers(_ k: Int) -> Int { + var fib = [1, 1] + while fib.last! <= k { + fib.append(fib[fib.count - 1] + fib[fib.count - 2]) + } + + var count = 0 + var i = fib.count - 1 + var remaining = k + + while remaining > 0 { + if fib[i] <= remaining { + remaining -= fib[i] + count += 1 + } + i -= 1 + } + + return count + } +} diff --git a/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.ts b/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.ts new file mode 100644 index 00000000..3d442f52 --- /dev/null +++ b/tests/1001-1500/1414. find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/sol.ts @@ -0,0 +1,19 @@ +function findMinFibonacciNumbers(k: number): number { + const fib: number[] = [1, 1]; + while (fib[fib.length - 1] <= k) { + fib.push(fib[fib.length - 1] + fib[fib.length - 2]); + } + + let count = 0; + let i = fib.length - 1; + + while (k > 0) { + if (fib[i] <= k) { + k -= fib[i]; + count++; + } + i--; + } + + return count; +} diff --git a/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/manifest.yaml b/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/manifest.yaml new file mode 100644 index 00000000..71925026 --- /dev/null +++ b/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/manifest.yaml @@ -0,0 +1,232 @@ +entry: + id: 1415 + title: "the-k-th-lexicographical-string-of-all-happy-strings-of-length-n" + params: + n: + type: int + k: + type: int + call: + cpp: "Solution().getHappyString({n}, {k})" + rust: "Solution::get_happy_string({n}, {k})" + python3: "Solution().getHappyString({n}, {k})" + python2: "Solution().getHappyString({n}, {k})" + ruby: "get_happy_string({n}, {k})" + java: "new Solution().getHappyString({n}, {k})" + csharp: "new Solution().GetHappyString({n}, {k})" + kotlin: "Solution().getHappyString({n}, {k})" + go: "getHappyString({n}, {k})" + dart: "Solution().getHappyString({n}, {k})" + swift: "Solution().getHappyString({n}, {k})" + typescript: "getHappyString({n}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 300 + memory_mb: 300 + +oracle: + python3: + call: "Checker().getHappyString(n, k, {result})" + checker: | + class Checker: + def getHappyString(self, n, k, result): + strings = [] + + def build(prefix): + if len(prefix) == n: + strings.append(prefix) + return + for char in "abc": + if not prefix or prefix[-1] != char: + build(prefix + char) + + build("") + expected = strings[k - 1] if 1 <= k <= len(strings) else "" + return result == expected + +seed: 1415 + +tests: + - name: "example-n1-k3" + in: + n: 1 + k: 3 + - name: "example-n1-k4" + in: + n: 1 + k: 4 + - name: "example-n3-k9" + in: + n: 3 + k: 9 + - name: "n1-first" + in: + n: 1 + k: 1 + - name: "n1-second" + in: + n: 1 + k: 2 + - name: "n2-first" + in: + n: 2 + k: 1 + - name: "n2-last" + in: + n: 2 + k: 6 + - name: "n2-invalid" + in: + n: 2 + k: 7 + - name: "n3-first" + in: + n: 3 + k: 1 + - name: "n3-block-boundary" + in: + n: 3 + k: 5 + - name: "n3-last" + in: + n: 3 + k: 12 + - name: "n3-invalid" + in: + n: 3 + k: 13 + - name: "n4-first" + in: + n: 4 + k: 1 + - name: "n4-boundary" + in: + n: 4 + k: 8 + - name: "n4-middle" + in: + n: 4 + k: 15 + - name: "n4-last" + in: + n: 4 + k: 24 + - name: "n5-first" + in: + n: 5 + k: 1 + - name: "n5-second" + in: + n: 5 + k: 2 + - name: "n5-boundary" + in: + n: 5 + k: 16 + - name: "n5-middle" + in: + n: 5 + k: 30 + - name: "n5-last" + in: + n: 5 + k: 48 + - name: "n5-invalid" + in: + n: 5 + k: 49 + - name: "n6-first" + in: + n: 6 + k: 1 + - name: "n6-quarter" + in: + n: 6 + k: 24 + - name: "n6-middle" + in: + n: 6 + k: 48 + - name: "n6-last" + in: + n: 6 + k: 96 + - name: "n7-first" + in: + n: 7 + k: 1 + - name: "n7-boundary" + in: + n: 7 + k: 64 + - name: "n8-first" + in: + n: 8 + k: 1 + - name: "n8-k63" + in: + n: 8 + k: 63 + - name: "n9-first" + in: + n: 9 + k: 1 + - name: "n10-first" + in: + n: 10 + k: 1 + - name: "n10-k100" + in: + n: 10 + k: 100 + - name: "large-generated-1" + seed: 141501 + in: + n: 10 + k: + gen: "int" + min: 1 + max: 100 + - name: "large-generated-2" + seed: 141502 + in: + n: 10 + k: + gen: "int" + min: 1 + max: 100 + - name: "large-generated-3" + seed: 141503 + in: + n: 10 + k: + gen: "int" + min: 1 + max: 100 + - name: "large-generated-4" + seed: 141504 + in: + n: 10 + k: + gen: "int" + min: 1 + max: 100 + - name: "large-generated-5" + seed: 141505 + in: + n: 10 + k: + gen: "int" + min: 1 + max: 100 + - name: "large-generated-6" + seed: 141506 + in: + n: 10 + k: + gen: "int" + min: 1 + max: 100 diff --git a/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.cpp b/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.cpp new file mode 100644 index 00000000..7de2edc8 --- /dev/null +++ b/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + string getHappyString(int n, int k) { + int total = 3 * (1 << (n - 1)); + if (k > total) { + return ""; + } + + k -= 1; + string result = ""; + char last = '\0'; + + for (int pos = 0; pos < n; pos++) { + int branch = 1 << (n - pos - 1); + vector choices; + for (char c : {'a', 'b', 'c'}) { + if (c != last) { + choices.push_back(c); + } + } + + int idx = k / branch; + result += choices[idx]; + + last = choices[idx]; + k %= branch; + } + + return result; + } +}; diff --git a/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.cs b/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.cs new file mode 100644 index 00000000..be740f61 --- /dev/null +++ b/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.cs @@ -0,0 +1,30 @@ +public class Solution { + public string GetHappyString(int n, int k) { + int total = 3 * (1 << (n - 1)); + if (k > total) { + return ""; + } + + k -= 1; + char[] result = new char[n]; + char last = '\0'; + + for (int pos = 0; pos < n; pos++) { + int branch = 1 << (n - pos - 1); + List choices = new List(); + foreach (char c in "abc") { + if (c != last) { + choices.Add(c); + } + } + + int idx = k / branch; + result[pos] = choices[idx]; + + last = choices[idx]; + k %= branch; + } + + return new string(result); + } +} diff --git a/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.dart b/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.dart new file mode 100644 index 00000000..560663a9 --- /dev/null +++ b/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.dart @@ -0,0 +1,30 @@ +class Solution { + String getHappyString(int n, int k) { + int total = 3 * (1 << (n - 1)); + if (k > total) { + return ""; + } + + k -= 1; + StringBuffer result = StringBuffer(); + String last = ""; + + for (int pos = 0; pos < n; pos++) { + int branch = 1 << (n - pos - 1); + List choices = []; + for (String c in ["a", "b", "c"]) { + if (c != last) { + choices.add(c); + } + } + + int idx = k ~/ branch; + result.write(choices[idx]); + + last = choices[idx]; + k %= branch; + } + + return result.toString(); + } +} diff --git a/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.go b/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.go new file mode 100644 index 00000000..466057cf --- /dev/null +++ b/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.go @@ -0,0 +1,28 @@ +func getHappyString(n int, k int) string { + total := 3 * (1 << (n - 1)) + if k > total { + return "" + } + + k-- + result := make([]byte, 0, n) + var last byte = 0 + + for pos := 0; pos < n; pos++ { + branch := 1 << (n - pos - 1) + choices := []byte{} + for _, c := range []byte{'a', 'b', 'c'} { + if c != last { + choices = append(choices, c) + } + } + + idx := k / branch + result = append(result, choices[idx]) + + last = choices[idx] + k %= branch + } + + return string(result) +} diff --git a/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.java b/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.java new file mode 100644 index 00000000..0013ca9a --- /dev/null +++ b/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.java @@ -0,0 +1,31 @@ +class Solution { + public String getHappyString(int n, int k) { + int total = 3 * (1 << (n - 1)); + if (k > total) { + return ""; + } + + k -= 1; + StringBuilder result = new StringBuilder(); + char last = '\0'; + + for (int pos = 0; pos < n; pos++) { + int branch = 1 << (n - pos - 1); + char[] choices = new char[last == '\0' ? 3 : 2]; + int idx = 0; + for (char c = 'a'; c <= 'c'; c++) { + if (c != last) { + choices[idx++] = c; + } + } + + int choiceIdx = k / branch; + result.append(choices[choiceIdx]); + + last = choices[choiceIdx]; + k %= branch; + } + + return result.toString(); + } +} diff --git a/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.kt b/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.kt new file mode 100644 index 00000000..d3330cce --- /dev/null +++ b/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.kt @@ -0,0 +1,30 @@ +class Solution { + fun getHappyString(n: Int, k: Int): String { + val total = 3 * (1 shl (n - 1)) + if (k > total) { + return "" + } + + var kVar = k - 1 + val result = StringBuilder() + var last = '\u0000' + + for (pos in 0 until n) { + val branch = 1 shl (n - pos - 1) + val choices = mutableListOf() + for (c in "abc") { + if (c != last) { + choices.add(c) + } + } + + val idx = kVar / branch + result.append(choices[idx]) + + last = choices[idx] + kVar %= branch + } + + return result.toString() + } +} diff --git a/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.py b/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.py new file mode 100644 index 00000000..347a587e --- /dev/null +++ b/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.py @@ -0,0 +1,22 @@ +class Solution: + def getHappyString(self, n: int, k: int) -> str: + + total = 3 * (2 ** (n - 1)) + if k > total: + return "" + + k -= 1 + result = [] + last = "" + + for pos in range(n): + branch = 2 ** (n - pos - 1) + choices = [c for c in "abc" if c != last] + + idx = k // branch + result.append(choices[idx]) + + last = choices[idx] + k %= branch + + return "".join(result) diff --git a/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.py2 b/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.py2 new file mode 100644 index 00000000..de1fa5bc --- /dev/null +++ b/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.py2 @@ -0,0 +1,26 @@ +class Solution(object): + def getHappyString(self, n, k): + """ + :type n: int + :type k: int + :rtype: str + """ + total = 3 * (2 ** (n - 1)) + if k > total: + return "" + + k -= 1 + result = [] + last = "" + + for pos in range(n): + branch = 2 ** (n - pos - 1) + choices = [c for c in "abc" if c != last] + + idx = k // branch + result.append(choices[idx]) + + last = choices[idx] + k %= branch + + return "".join(result) diff --git a/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.rb b/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.rb new file mode 100644 index 00000000..cca28a60 --- /dev/null +++ b/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.rb @@ -0,0 +1,24 @@ +# @param {Integer} n +# @param {Integer} k +# @return {String} +def get_happy_string(n, k) + total = 3 * (2 ** (n - 1)) + return "" if k > total + + k -= 1 + result = [] + last = "" + + n.times do |pos| + branch = 2 ** (n - pos - 1) + choices = ["a", "b", "c"].select { |c| c != last } + + idx = k / branch + result.push(choices[idx]) + + last = choices[idx] + k %= branch + end + + result.join +end diff --git a/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.rs b/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.rs new file mode 100644 index 00000000..06ec8278 --- /dev/null +++ b/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.rs @@ -0,0 +1,32 @@ +impl Solution { + pub fn get_happy_string(n: i32, k: i32) -> String { + let n = n as usize; + let mut k = k as i32; + let total = 3 * (1 << (n - 1)); + if k > total { + return String::new(); + } + + k -= 1; + let mut result = String::with_capacity(n); + let mut last = '\0'; + + for pos in 0..n { + let branch = 1 << (n - pos - 1); + let mut choices = Vec::new(); + for &c in &['a', 'b', 'c'] { + if c != last { + choices.push(c); + } + } + + let idx = (k / branch) as usize; + result.push(choices[idx]); + + last = choices[idx]; + k %= branch; + } + + result + } +} diff --git a/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.swift b/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.swift new file mode 100644 index 00000000..105e5e7b --- /dev/null +++ b/tests/1001-1500/1415. the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/sol.swift @@ -0,0 +1,30 @@ +class Solution { + func getHappyString(_ n: Int, _ k: Int) -> String { + let total = 3 * (1 << (n - 1)) + if k > total { + return "" + } + + var k = k - 1 + var result = "" + var last: Character? = nil + + for pos in 0.. total) { + return ""; + } + + k -= 1; + let result = ""; + let last = ""; + + for (let pos = 0; pos < n; pos++) { + const branch = 1 << (n - pos - 1); + const choices: string[] = []; + for (const c of ["a", "b", "c"]) { + if (c !== last) { + choices.push(c); + } + } + + const idx = Math.floor(k / branch); + result += choices[idx]; + + last = choices[idx]; + k %= branch; + } + + return result; +} diff --git a/tests/1001-1500/1416. restore-the-array/manifest.yaml b/tests/1001-1500/1416. restore-the-array/manifest.yaml new file mode 100644 index 00000000..0a8bbcf1 --- /dev/null +++ b/tests/1001-1500/1416. restore-the-array/manifest.yaml @@ -0,0 +1,230 @@ +entry: + id: 1416 + title: restore-the-array + params: + s: + type: string + k: + type: int + call: + cpp: "Solution().numberOfArrays({s}, {k})" + rust: "Solution::number_of_arrays({s}, {k})" + python3: "Solution().numberOfArrays({s}, {k})" + python2: "Solution().numberOfArrays({s}, {k})" + ruby: "number_of_arrays({s}, {k})" + java: "new Solution().numberOfArrays({s}, {k})" + csharp: "new Solution().NumberOfArrays({s}, {k})" + kotlin: "Solution().numberOfArrays({s}, {k})" + go: "numberOfArrays({s}, {k})" + dart: "Solution().numberOfArrays({s}, {k})" + swift: "Solution().numberOfArrays({s}, {k})" + typescript: "numberOfArrays({s}, {k})" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().numberOfArrays(s, k, {result})" + checker: | + class Checker: + def numberOfArrays(self, s, k, result): + if type(result) is not int: + return False + mod = 1000000007 + ways = [0] * (len(s) + 1) + ways[len(s)] = 1 + width = len(str(k)) + for start in range(len(s) - 1, -1, -1): + if s[start] == '0': + continue + value = 0 + for end in range(start, min(len(s), start + width)): + value = value * 10 + ord(s[end]) - 48 + if value > k: + break + ways[start] = (ways[start] + ways[end + 1]) % mod + return result == ways[0] +seed: 1416 +tests: + - name: example-single + in: + s: "1000" + k: 10000 + - name: example-impossible + in: + s: "1000" + k: 10 + - name: example-eight + in: + s: "1317" + k: 2000 + - name: minimum-digit + in: + s: "1" + k: 1 + - name: minimum-k-nonzero + in: + s: "9" + k: 1 + - name: exact-two-digit-limit + in: + s: "12" + k: 12 + - name: two-digit-too-large + in: + s: "12" + k: 9 + - name: all-ones-k-one + in: + s: "11111" + k: 1 + - name: all-ones-k-eleven + in: + s: "11111" + k: 11 + - name: internal-zero + in: + s: "101" + k: 100 + - name: zero-after-prefix + in: + s: "1001" + k: 1000 + - name: zero-after-one + in: + s: "1200" + k: 1000 + - name: exact-nines + in: + s: "99" + k: 99 + - name: nines-single-only + in: + s: "99" + k: 9 + - name: three-digit-boundary + in: + s: "123" + k: 12 + - name: four-digit-splits + in: + s: "1234" + k: 100 + - name: restrictive-increasing + in: + s: "9876" + k: 9 + - name: permissive-short + in: + s: "9876" + k: 10000 + - name: alternating-zero + in: + s: "101010" + k: 101 + - name: repeated-two + in: + s: "222222" + k: 22 + - name: pi-prefix + in: + s: "314159" + k: 1000 + - name: all-nines-six + in: + s: "999999" + k: 999999 + - name: k-one-digit + in: + s: "123456" + k: 10 + - name: k-two-digit + in: + s: "123456" + k: 99 + - name: zero-block + in: + s: "1000001" + k: 1000000 + - name: long-ones-static + in: + s: "1111111" + k: 11 + - name: increasing-nine + in: + s: "123456789" + k: 100 + - name: decreasing-nine + in: + s: "987654321" + k: 100 + - name: repeated-pattern + in: + s: "123123123" + k: 123 + - name: zero-separated + in: + s: "10203040" + k: 1000 + - name: nine-digit-permissive + in: + s: "999999999" + k: 1000000000 + - name: nine-digit-restrictive + in: + s: "999999999" + k: 9 + - name: ten-digit-mixed + in: + s: "1234567891" + k: 10000 + - name: pi-long + in: + s: "3141592653" + k: 100000 + - name: billion-boundary + in: + s: "1000000000" + k: 1000000000 + - name: generated-small + seed: 141601 + in: + s: + gen: "str" + len: 37 + alphabet: "123456789" + k: 999 + - name: generated-medium + seed: 141602 + in: + s: + gen: "str" + len: 121 + alphabet: "123456789" + k: 100000 + - name: generated-wide-k + seed: 141603 + in: + s: + gen: "str" + len: 503 + alphabet: "123456789" + k: 1000000000 + - name: generated-large + seed: 141604 + in: + s: + gen: "str" + len: 100000 + alphabet: "123456789" + k: 999999999 + - name: generated-large-small-k + seed: 141605 + in: + s: + gen: "str" + len: 100000 + alphabet: "123456789" + k: 9 diff --git a/tests/1001-1500/1416. restore-the-array/sol.cpp b/tests/1001-1500/1416. restore-the-array/sol.cpp new file mode 100644 index 00000000..fa6c0640 --- /dev/null +++ b/tests/1001-1500/1416. restore-the-array/sol.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int numberOfArrays(string s, int k) { + const int mod = 1000000007; + int n = s.size(); + vector dp(n + 1, 0); + dp[0] = 1; + int width = to_string(k).size(); + for (int i = 0; i < n; i++) { + if (s[i] == '0' || dp[i] == 0) continue; + long long value = 0; + for (int j = i; j < min(n, i + width); j++) { + value = value * 10 + (s[j] - '0'); + if (value > k) break; + dp[j + 1] = (dp[j + 1] + dp[i]) % mod; + } + } + return dp[n]; + } +}; diff --git a/tests/1001-1500/1416. restore-the-array/sol.cs b/tests/1001-1500/1416. restore-the-array/sol.cs new file mode 100644 index 00000000..73256d30 --- /dev/null +++ b/tests/1001-1500/1416. restore-the-array/sol.cs @@ -0,0 +1,19 @@ +public class Solution { + public int NumberOfArrays(string s, int k) { + int mod = 1000000007; + int n = s.Length; + int[] dp = new int[n + 1]; + dp[0] = 1; + int width = k.ToString().Length; + for (int i = 0; i < n; i++) { + if (s[i] == '0' || dp[i] == 0) continue; + long value = 0; + for (int j = i; j < Math.Min(n, i + width); j++) { + value = value * 10 + (s[j] - '0'); + if (value > k) break; + dp[j + 1] = (dp[j + 1] + dp[i]) % mod; + } + } + return dp[n]; + } +} diff --git a/tests/1001-1500/1416. restore-the-array/sol.dart b/tests/1001-1500/1416. restore-the-array/sol.dart new file mode 100644 index 00000000..32c3b436 --- /dev/null +++ b/tests/1001-1500/1416. restore-the-array/sol.dart @@ -0,0 +1,19 @@ +class Solution { + int numberOfArrays(String s, int k) { + int mod = 1000000007; + int n = s.length; + List dp = List.filled(n + 1, 0); + dp[0] = 1; + int width = k.toString().length; + for (int i = 0; i < n; i++) { + if (s[i] == '0' || dp[i] == 0) continue; + int value = 0; + for (int j = i; j < n && j < i + width; j++) { + value = value * 10 + (s.codeUnitAt(j) - 48); + if (value > k) break; + dp[j + 1] = (dp[j + 1] + dp[i]) % mod; + } + } + return dp[n]; + } +} diff --git a/tests/1001-1500/1416. restore-the-array/sol.go b/tests/1001-1500/1416. restore-the-array/sol.go new file mode 100644 index 00000000..ff8649fc --- /dev/null +++ b/tests/1001-1500/1416. restore-the-array/sol.go @@ -0,0 +1,21 @@ +func numberOfArrays(s string, k int) int { + mod := 1000000007 + n := len(s) + dp := make([]int, n+1) + dp[0] = 1 + width := len(fmt.Sprint(k)) + for i := 0; i < n; i++ { + if s[i] == '0' || dp[i] == 0 { + continue + } + value := 0 + for j := i; j < n && j < i+width; j++ { + value = value*10 + int(s[j]-'0') + if value > k { + break + } + dp[j+1] = (dp[j+1] + dp[i]) % mod + } + } + return dp[n] +} diff --git a/tests/1001-1500/1416. restore-the-array/sol.java b/tests/1001-1500/1416. restore-the-array/sol.java new file mode 100644 index 00000000..825f8bb8 --- /dev/null +++ b/tests/1001-1500/1416. restore-the-array/sol.java @@ -0,0 +1,19 @@ +class Solution { + public int numberOfArrays(String s, int k) { + int mod = 1000000007; + int n = s.length(); + int[] dp = new int[n + 1]; + dp[0] = 1; + int width = String.valueOf(k).length(); + for (int i = 0; i < n; i++) { + if (s.charAt(i) == '0' || dp[i] == 0) continue; + long value = 0; + for (int j = i; j < Math.min(n, i + width); j++) { + value = value * 10 + (s.charAt(j) - '0'); + if (value > k) break; + dp[j + 1] = (dp[j + 1] + dp[i]) % mod; + } + } + return dp[n]; + } +} diff --git a/tests/1001-1500/1416. restore-the-array/sol.kt b/tests/1001-1500/1416. restore-the-array/sol.kt new file mode 100644 index 00000000..351439cb --- /dev/null +++ b/tests/1001-1500/1416. restore-the-array/sol.kt @@ -0,0 +1,19 @@ +class Solution { + fun numberOfArrays(s: String, k: Int): Int { + val mod = 1000000007 + val n = s.length + val dp = IntArray(n + 1) + dp[0] = 1 + val width = k.toString().length + for (i in 0 until n) { + if (s[i] == '0' || dp[i] == 0) continue + var value = 0L + for (j in i until minOf(n, i + width)) { + value = value * 10 + (s[j] - '0') + if (value > k) break + dp[j + 1] = (dp[j + 1] + dp[i]) % mod + } + } + return dp[n] + } +} diff --git a/tests/1001-1500/1416. restore-the-array/sol.py b/tests/1001-1500/1416. restore-the-array/sol.py new file mode 100644 index 00000000..deb61fb0 --- /dev/null +++ b/tests/1001-1500/1416. restore-the-array/sol.py @@ -0,0 +1,16 @@ +class Solution: + def numberOfArrays(self, s: str, k: int) -> int: + mod = 1000000007 + dp = [0] * (len(s) + 1) + dp[0] = 1 + width = len(str(k)) + for i, digit in enumerate(s): + if digit == "0" or dp[i] == 0: + continue + value = 0 + for j in range(i, min(len(s), i + width)): + value = value * 10 + ord(s[j]) - 48 + if value > k: + break + dp[j + 1] = (dp[j + 1] + dp[i]) % mod + return dp[-1] diff --git a/tests/1001-1500/1416. restore-the-array/sol.py2 b/tests/1001-1500/1416. restore-the-array/sol.py2 new file mode 100644 index 00000000..18b888a3 --- /dev/null +++ b/tests/1001-1500/1416. restore-the-array/sol.py2 @@ -0,0 +1,22 @@ +class Solution(object): + def numberOfArrays(self, s, k): + """ + :type s: str + :type k: int + :rtype: int + """ + mod = 1000000007 + n = len(s) + dp = [0] * (n + 1) + dp[0] = 1 + width = len(str(k)) + for i in range(n): + if s[i] == '0' or dp[i] == 0: + continue + value = 0 + for j in range(i, min(n, i + width)): + value = value * 10 + ord(s[j]) - 48 + if value > k: + break + dp[j + 1] = (dp[j + 1] + dp[i]) % mod + return dp[-1] diff --git a/tests/1001-1500/1416. restore-the-array/sol.rb b/tests/1001-1500/1416. restore-the-array/sol.rb new file mode 100644 index 00000000..e5f5ea6b --- /dev/null +++ b/tests/1001-1500/1416. restore-the-array/sol.rb @@ -0,0 +1,20 @@ +# @param {String} s +# @param {Integer} k +# @return {Integer} +def number_of_arrays(s, k) + mod = 1000000007 + n = s.length + dp = Array.new(n + 1, 0) + dp[0] = 1 + width = k.to_s.length + (0...n).each do |i| + next if s[i] == '0' || dp[i] == 0 + value = 0 + (i...[n, i + width].min).each do |j| + value = value * 10 + s[j].ord - 48 + break if value > k + dp[j + 1] = (dp[j + 1] + dp[i]) % mod + end + end + dp[-1] +end diff --git a/tests/1001-1500/1416. restore-the-array/sol.rs b/tests/1001-1500/1416. restore-the-array/sol.rs new file mode 100644 index 00000000..859f9edb --- /dev/null +++ b/tests/1001-1500/1416. restore-the-array/sol.rs @@ -0,0 +1,25 @@ +impl Solution { + pub fn number_of_arrays(s: String, k: i32) -> i32 { + let m: i32 = 1000000007; + let n = s.len(); + let mut dp = vec![0i32; n + 1]; + dp[0] = 1; + let width = k.to_string().len(); + let s_bytes = s.as_bytes(); + for i in 0..n { + if s_bytes[i] == b'0' || dp[i] == 0 { + continue; + } + let mut value: i64 = 0; + let k_i64 = k as i64; + for j in i..std::cmp::min(n, i + width) { + value = value * 10 + (s_bytes[j] - b'0') as i64; + if value > k_i64 { + break; + } + dp[j + 1] = (dp[j + 1] + dp[i]) % m; + } + } + dp[n] + } +} diff --git a/tests/1001-1500/1416. restore-the-array/sol.swift b/tests/1001-1500/1416. restore-the-array/sol.swift new file mode 100644 index 00000000..b4eb33bf --- /dev/null +++ b/tests/1001-1500/1416. restore-the-array/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func numberOfArrays(_ s: String, _ k: Int) -> Int { + let mod = 1000000007 + let chars = Array(s) + let n = chars.count + var dp = [Int](repeating: 0, count: n + 1) + dp[0] = 1 + let width = String(k).count + for i in 0.. k { break } + dp[j + 1] = (dp[j + 1] + dp[i]) % mod + } + } + return dp[n] + } +} diff --git a/tests/1001-1500/1416. restore-the-array/sol.ts b/tests/1001-1500/1416. restore-the-array/sol.ts new file mode 100644 index 00000000..e6466d19 --- /dev/null +++ b/tests/1001-1500/1416. restore-the-array/sol.ts @@ -0,0 +1,17 @@ +function numberOfArrays(s: string, k: number): number { + const mod = 1000000007; + const n = s.length; + const dp = new Array(n + 1).fill(0); + dp[0] = 1; + const width = k.toString().length; + for (let i = 0; i < n; i++) { + if (s[i] === "0" || dp[i] === 0) continue; + let value = 0; + for (let j = i; j < Math.min(n, i + width); j++) { + value = value * 10 + (s.charCodeAt(j) - 48); + if (value > k) break; + dp[j + 1] = (dp[j + 1] + dp[i]) % mod; + } + } + return dp[n]; +} diff --git a/tests/1001-1500/1417. reformat-the-string/manifest.yaml b/tests/1001-1500/1417. reformat-the-string/manifest.yaml new file mode 100644 index 00000000..2e1449ba --- /dev/null +++ b/tests/1001-1500/1417. reformat-the-string/manifest.yaml @@ -0,0 +1,175 @@ +entry: + id: 1417 + title: "reformat-the-string" + params: + s: + type: string + call: + cpp: "Solution().reformat({s})" + rust: "Solution::reformat({s})" + python3: "Solution().reformat({s})" + python2: "Solution().reformat({s})" + ruby: "reformat({s})" + java: "new Solution().reformat({s})" + csharp: "new Solution().Reformat({s})" + kotlin: "Solution().reformat({s})" + go: "reformat({s})" + dart: "Solution().reformat({s})" + swift: "Solution().reformat({s})" + typescript: "reformat({s})" +judge: + type: "exact" +limits: + time_ms: 300 + memory_mb: 300 +oracle: + python3: + call: "Checker().reformat(s, {result})" + checker: | + from collections import Counter + class Checker: + def reformat(self, s, result): + if not isinstance(result, str): return False + d = [c for c in s if c.isdigit()] + a = [c for c in s if c.isalpha()] + if abs(len(d)-len(a)) >= 2: return result == '' + if len(result) != len(s): return False + if Counter(result) != Counter(s): return False + return all(result[i].isdigit() != result[i+1].isdigit() for i in range(len(result)-1)) +seed: 1417 +tests: + - name: ex1 + in: + s: a0b1c2 + - name: ex2 + in: + s: leetcode + out: "" + - name: ex3 + in: + s: 1229857369 + out: "" + - name: one_letter + in: + s: a + - name: one_digit + in: + s: 7 + - name: pair_letter_digit + in: + s: a1 + - name: pair_digit_letter + in: + s: 1a + - name: two_letters + in: + s: ab + out: "" + - name: two_digits + in: + s: 12 + out: "" + - name: balanced_three + in: + s: a1b + - name: balanced_four + in: + s: a1b2 + - name: letters_more_one + in: + s: abc12 + - name: digits_more_one + in: + s: 123ab + - name: letters_more_two + in: + s: abcd12 + out: "" + - name: digits_more_two + in: + s: 1234ab + out: "" + - name: alternating_start_letter + in: + s: a1b2c3d + - name: alternating_start_digit + in: + s: 1a2b3c4 + - name: repeated_letters + in: + s: aaa111 + - name: repeated_digits + in: + s: 111aaa + - name: mixed_a + in: + s: z9y8x7 + - name: mixed_b + in: + s: 0a1b2c + - name: mixed_c + in: + s: q1w2e3r + - name: mixed_d + in: + s: 4t5y6u7 + - name: long_balanced + in: + s: abcdefghij1234567890 + - name: long_letters + in: + s: abcdefghijklmno12 + - name: long_digits + in: + s: 123456789012345ab + - name: zeros + in: + s: 000aaa + - name: nines + in: + s: 999zzz + - name: boundary_letters + in: + s: az09 + - name: boundary_digits + in: + s: 0a9z + - name: six_balanced + in: + s: a1b2c3 + - name: seven_letters + in: + s: abcdef1 + - name: seven_digits + in: + s: 123456a + - name: eight_balanced + in: + s: a1b2c3d4 + - name: final_case + in: + s: 5a6b7c8d9 + - name: max_length_mixed + in: + s: + gen: "str" + len: 500 + alphabet: "abcdefghijklmnopqrstuvwxyz0123456789" + - name: max_length_letters + in: + s: + gen: "str" + len: 500 + alphabet: "abcdefghijklmnopqrstuvwxyz" + - name: max_length_digits + in: + s: + gen: "str" + len: 500 + alphabet: "0123456789" + - name: near_balance_repeated + in: + s: aaabbb111222 + - name: near_balance_digits + in: + s: 0000111222aaa diff --git a/tests/1001-1500/1417. reformat-the-string/sol.cpp b/tests/1001-1500/1417. reformat-the-string/sol.cpp new file mode 100644 index 00000000..1e332001 --- /dev/null +++ b/tests/1001-1500/1417. reformat-the-string/sol.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + string reformat(string s) { + vector digits; + vector letters; + for (char c : s) { + if (isdigit(c)) { + digits.push_back(c); + } else if (isalpha(c)) { + letters.push_back(c); + } + } + if (abs((int)digits.size() - (int)letters.size()) >= 2) { + return ""; + } + string ans(s.length(), ' '); + if (digits.size() > letters.size()) { + for (int i = 0; i < s.length(); i++) { + if (i % 2 == 0) { + ans[i] = digits[i / 2]; + } else { + ans[i] = letters[i / 2]; + } + } + } else { + for (int i = 0; i < s.length(); i++) { + if (i % 2 == 0) { + ans[i] = letters[i / 2]; + } else { + ans[i] = digits[i / 2]; + } + } + } + return ans; + } +}; diff --git a/tests/1001-1500/1417. reformat-the-string/sol.cs b/tests/1001-1500/1417. reformat-the-string/sol.cs new file mode 100644 index 00000000..41bf8fdc --- /dev/null +++ b/tests/1001-1500/1417. reformat-the-string/sol.cs @@ -0,0 +1,35 @@ +public class Solution { + public string Reformat(string s) { + var digits = new List(); + var letters = new List(); + foreach (char c in s) { + if (char.IsDigit(c)) { + digits.Add(c); + } else if (char.IsLetter(c)) { + letters.Add(c); + } + } + if (Math.Abs(digits.Count - letters.Count) >= 2) { + return ""; + } + char[] ans = new char[s.Length]; + if (digits.Count > letters.Count) { + for (int i = 0; i < s.Length; i++) { + if (i % 2 == 0) { + ans[i] = digits[i / 2]; + } else { + ans[i] = letters[i / 2]; + } + } + } else { + for (int i = 0; i < s.Length; i++) { + if (i % 2 == 0) { + ans[i] = letters[i / 2]; + } else { + ans[i] = digits[i / 2]; + } + } + } + return new string(ans); + } +} diff --git a/tests/1001-1500/1417. reformat-the-string/sol.dart b/tests/1001-1500/1417. reformat-the-string/sol.dart new file mode 100644 index 00000000..191ce6c7 --- /dev/null +++ b/tests/1001-1500/1417. reformat-the-string/sol.dart @@ -0,0 +1,27 @@ +class Solution { + String reformat(String s) { + List digits = []; + List letters = []; + for (var c in s.split('')) { + if (RegExp(r'\d').hasMatch(c)) { + digits.add(c); + } else if (RegExp(r'[a-zA-Z]').hasMatch(c)) { + letters.add(c); + } + } + if ((digits.length - letters.length).abs() >= 2) { + return ""; + } + List ans = List.filled(s.length, ''); + if (digits.length > letters.length) { + for (int i = 0; i < s.length; i++) { + ans[i] = i % 2 == 0 ? digits[i ~/ 2] : letters[i ~/ 2]; + } + } else { + for (int i = 0; i < s.length; i++) { + ans[i] = i % 2 == 0 ? letters[i ~/ 2] : digits[i ~/ 2]; + } + } + return ans.join(''); + } +} diff --git a/tests/1001-1500/1417. reformat-the-string/sol.go b/tests/1001-1500/1417. reformat-the-string/sol.go new file mode 100644 index 00000000..5dfdd284 --- /dev/null +++ b/tests/1001-1500/1417. reformat-the-string/sol.go @@ -0,0 +1,41 @@ +func reformat(s string) string { + digits := []byte{} + letters := []byte{} + for i := 0; i < len(s); i++ { + c := s[i] + if c >= '0' && c <= '9' { + digits = append(digits, c) + } else if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') { + letters = append(letters, c) + } + } + if abs(len(digits)-len(letters)) >= 2 { + return "" + } + ans := make([]byte, len(s)) + if len(digits) > len(letters) { + for i := 0; i < len(s); i++ { + if i%2 == 0 { + ans[i] = digits[i/2] + } else { + ans[i] = letters[i/2] + } + } + } else { + for i := 0; i < len(s); i++ { + if i%2 == 0 { + ans[i] = letters[i/2] + } else { + ans[i] = digits[i/2] + } + } + } + return string(ans) +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} diff --git a/tests/1001-1500/1417. reformat-the-string/sol.java b/tests/1001-1500/1417. reformat-the-string/sol.java new file mode 100644 index 00000000..a713d91b --- /dev/null +++ b/tests/1001-1500/1417. reformat-the-string/sol.java @@ -0,0 +1,35 @@ +class Solution { + public String reformat(String s) { + List digits = new ArrayList<>(); + List letters = new ArrayList<>(); + for (char c : s.toCharArray()) { + if (Character.isDigit(c)) { + digits.add(c); + } else if (Character.isLetter(c)) { + letters.add(c); + } + } + if (Math.abs(digits.size() - letters.size()) >= 2) { + return ""; + } + char[] ans = new char[s.length()]; + if (digits.size() > letters.size()) { + for (int i = 0; i < s.length(); i++) { + if (i % 2 == 0) { + ans[i] = digits.get(i / 2); + } else { + ans[i] = letters.get(i / 2); + } + } + } else { + for (int i = 0; i < s.length(); i++) { + if (i % 2 == 0) { + ans[i] = letters.get(i / 2); + } else { + ans[i] = digits.get(i / 2); + } + } + } + return new String(ans); + } +} diff --git a/tests/1001-1500/1417. reformat-the-string/sol.kt b/tests/1001-1500/1417. reformat-the-string/sol.kt new file mode 100644 index 00000000..ac0035db --- /dev/null +++ b/tests/1001-1500/1417. reformat-the-string/sol.kt @@ -0,0 +1,27 @@ +class Solution { + fun reformat(s: String): String { + val digits = mutableListOf() + val letters = mutableListOf() + for (c in s) { + if (c.isDigit()) { + digits.add(c) + } else if (c.isLetter()) { + letters.add(c) + } + } + if (Math.abs(digits.size - letters.size) >= 2) { + return "" + } + val ans = CharArray(s.length) + if (digits.size > letters.size) { + for (i in ans.indices) { + ans[i] = if (i % 2 == 0) digits[i / 2] else letters[i / 2] + } + } else { + for (i in ans.indices) { + ans[i] = if (i % 2 == 0) letters[i / 2] else digits[i / 2] + } + } + return String(ans) + } +} diff --git a/tests/1001-1500/1417. reformat-the-string/sol.py b/tests/1001-1500/1417. reformat-the-string/sol.py new file mode 100644 index 00000000..dfd39a32 --- /dev/null +++ b/tests/1001-1500/1417. reformat-the-string/sol.py @@ -0,0 +1,16 @@ +class Solution: + def reformat(self, s): + digits = [c for c in s if c.isdigit()] + letters = [c for c in s if c.isalpha()] + if abs(len(digits) - len(letters)) >= 2: + return "" + ans = [] + if len(digits) > len(letters): + ans = [None] * (len(s)) + ans[::2] = digits + ans[1::2] = letters + else: + ans = [None] * (len(s)) + ans[::2] = letters + ans[1::2] = digits + return "".join(ans) diff --git a/tests/1001-1500/1417. reformat-the-string/sol.py2 b/tests/1001-1500/1417. reformat-the-string/sol.py2 new file mode 100644 index 00000000..8287b973 --- /dev/null +++ b/tests/1001-1500/1417. reformat-the-string/sol.py2 @@ -0,0 +1,18 @@ +class Solution(object): + def reformat(self, s): + """ + :type s: str + :rtype: str + """ + digits = [c for c in s if c.isdigit()] + letters = [c for c in s if c.isalpha()] + if abs(len(digits) - len(letters)) >= 2: + return "" + ans = [None] * len(s) + if len(digits) > len(letters): + ans[::2] = digits + ans[1::2] = letters + else: + ans[::2] = letters + ans[1::2] = digits + return "".join(ans) diff --git a/tests/1001-1500/1417. reformat-the-string/sol.rb b/tests/1001-1500/1417. reformat-the-string/sol.rb new file mode 100644 index 00000000..c4adeff8 --- /dev/null +++ b/tests/1001-1500/1417. reformat-the-string/sol.rb @@ -0,0 +1,16 @@ +# @param {String} s +# @return {String} +def reformat(s) + digits = s.chars.select { |c| c =~ /\d/ } + letters = s.chars.select { |c| c =~ /[a-zA-Z]/ } + if (digits.length - letters.length).abs >= 2 + return "" + end + ans = Array.new(s.length) + if digits.length > letters.length + ans.each_index { |i| ans[i] = i.even? ? digits[i/2] : letters[i/2] } + else + ans.each_index { |i| ans[i] = i.even? ? letters[i/2] : digits[i/2] } + end + ans.join +end diff --git a/tests/1001-1500/1417. reformat-the-string/sol.rs b/tests/1001-1500/1417. reformat-the-string/sol.rs new file mode 100644 index 00000000..faebe056 --- /dev/null +++ b/tests/1001-1500/1417. reformat-the-string/sol.rs @@ -0,0 +1,20 @@ +impl Solution { + pub fn reformat(s: String) -> String { + let digits: Vec = s.chars().filter(|c| c.is_digit(10)).collect(); + let letters: Vec = s.chars().filter(|c| c.is_alphabetic()).collect(); + if (digits.len() as i32 - letters.len() as i32).abs() >= 2 { + return String::new(); + } + let mut ans = vec![' '; s.len()]; + if digits.len() > letters.len() { + for i in 0..s.len() { + ans[i] = if i % 2 == 0 { digits[i / 2] } else { letters[i / 2] }; + } + } else { + for i in 0..s.len() { + ans[i] = if i % 2 == 0 { letters[i / 2] } else { digits[i / 2] }; + } + } + ans.into_iter().collect() + } +} diff --git a/tests/1001-1500/1417. reformat-the-string/sol.swift b/tests/1001-1500/1417. reformat-the-string/sol.swift new file mode 100644 index 00000000..e04a7ef1 --- /dev/null +++ b/tests/1001-1500/1417. reformat-the-string/sol.swift @@ -0,0 +1,35 @@ +class Solution { + func reformat(_ s: String) -> String { + var digits = [Character]() + var letters = [Character]() + for c in s { + if c.isNumber { + digits.append(c) + } else if c.isLetter { + letters.append(c) + } + } + if abs(digits.count - letters.count) >= 2 { + return "" + } + var ans = [Character](repeating: " ", count: s.count) + if digits.count > letters.count { + for i in 0..= 2) { + return ""; + } + const ans: string[] = new Array(s.length); + if (digits.length > letters.length) { + for (let i = 0; i < s.length; i++) { + ans[i] = i % 2 === 0 ? digits[(i / 2) | 0] : letters[(i / 2) | 0]; + } + } else { + for (let i = 0; i < s.length; i++) { + ans[i] = i % 2 === 0 ? letters[(i / 2) | 0] : digits[(i / 2) | 0]; + } + } + return ans.join(""); +} diff --git a/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/manifest.yaml b/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/manifest.yaml new file mode 100644 index 00000000..0b24e5eb --- /dev/null +++ b/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/manifest.yaml @@ -0,0 +1,597 @@ +entry: + id: 1418 + title: "display-table-of-food-orders-in-a-restaurant" + params: + orders: + type: array + items: + type: array + items: + type: string + call: + cpp: "Solution().displayTable({orders})" + rust: "Solution::display_table({orders})" + python3: "Solution().displayTable({orders})" + python2: "Solution().displayTable({orders})" + ruby: "display_table({orders})" + java: "new Solution().displayTable({orders})" + csharp: "new Solution().DisplayTable({orders})" + kotlin: "Solution().displayTable({orders})" + go: "displayTable({orders})" + dart: "Solution().displayTable({orders})" + swift: "Solution().displayTable({orders})" + typescript: "displayTable({orders})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().displayTable(orders, {result})" + checker: | + class Checker: + def displayTable(self, orders, result): + foods = sorted({order[2] for order in orders}) + tables = {} + for _, table, food in orders: + tables.setdefault(int(table), {}) + tables[int(table)][food] = tables[int(table)].get(food, 0) + 1 + expected = [["Table"] + foods] + for table in sorted(tables): + expected.append([str(table)] + [str(tables[table].get(food, 0)) for food in foods]) + return result == expected + +seed: 1418 + +tests: + - name: "example-one" + in: + orders: + elemType: "string" + value: + - ["David", "3", "Ceviche"] + - ["Corina", "10", "Beef Burrito"] + - ["David", "3", "Fried Chicken"] + - ["Carla", "5", "Water"] + - ["Carla", "5", "Ceviche"] + - ["Rous", "3", "Ceviche"] + out: + - ["Table", "Beef Burrito", "Ceviche", "Fried Chicken", "Water"] + - ["3", "0", "2", "1", "0"] + - ["5", "0", "1", "0", "1"] + - ["10", "1", "0", "0", "0"] + - name: "example-two" + in: + orders: + elemType: "string" + value: + - ["James", "12", "Fried Chicken"] + - ["Ratesh", "12", "Fried Chicken"] + - ["Amadeus", "12", "Fried Chicken"] + - ["Adam", "1", "Canadian Waffles"] + - ["Brianna", "1", "Canadian Waffles"] + out: + - ["Table", "Canadian Waffles", "Fried Chicken"] + - ["1", "2", "0"] + - ["12", "0", "3"] + - name: "example-three" + in: + orders: + elemType: "string" + value: + - ["Laura", "2", "Bean Burrito"] + - ["Jhon", "2", "Beef Burrito"] + - ["Melissa", "2", "Soda"] + out: + - ["Table", "Bean Burrito", "Beef Burrito", "Soda"] + - ["2", "1", "1", "1"] + - name: "single-order" + in: + orders: + elemType: "string" + value: + - ["A", "1", "Soup"] + out: + - ["Table", "Soup"] + - ["1", "1"] + - name: "same-table-different-foods" + in: + orders: + elemType: "string" + value: + - ["A", "2", "Tea"] + - ["B", "2", "Coffee"] + - ["C", "2", "Cake"] + out: + - ["Table", "Cake", "Coffee", "Tea"] + - ["2", "1", "1", "1"] + - name: "same-food-different-tables" + in: + orders: + elemType: "string" + value: + - ["A", "1", "Pizza"] + - ["B", "3", "Pizza"] + - ["C", "2", "Pizza"] + out: + - ["Table", "Pizza"] + - ["1", "1"] + - ["2", "1"] + - ["3", "1"] + - name: "repeated-orders" + in: + orders: + elemType: "string" + value: + - ["A", "4", "Rice"] + - ["B", "4", "Rice"] + - ["C", "4", "Rice"] + - ["D", "4", "Noodles"] + out: + - ["Table", "Noodles", "Rice"] + - ["4", "1", "3"] + - name: "numeric-table-order" + in: + orders: + elemType: "string" + value: + - ["A", "10", "A"] + - ["B", "2", "B"] + - ["C", "1", "C"] + out: + - ["Table", "A", "B", "C"] + - ["1", "0", "0", "1"] + - ["2", "0", "1", "0"] + - ["10", "1", "0", "0"] + - name: "lexical-food-order" + in: + orders: + elemType: "string" + value: + - ["A", "1", "Zebra"] + - ["B", "1", "Apple"] + - ["C", "1", "Mango"] + out: + - ["Table", "Apple", "Mango", "Zebra"] + - ["1", "1", "1", "1"] + - name: "multiword-foods" + in: + orders: + elemType: "string" + value: + - ["A", "5", "Beef Burrito"] + - ["B", "5", "Chicken Soup"] + - ["C", "6", "Apple Pie"] + out: + - ["Table", "Apple Pie", "Beef Burrito", "Chicken Soup"] + - ["5", "0", "1", "1"] + - ["6", "1", "0", "0"] + - name: "sparse-two-tables" + in: + orders: + elemType: "string" + value: + - ["A", "1", "A"] + - ["B", "100", "B"] + out: + - ["Table", "A", "B"] + - ["1", "1", "0"] + - ["100", "0", "1"] + - name: "three-food-counts" + in: + orders: + elemType: "string" + value: + - ["A", "7", "X"] + - ["B", "7", "X"] + - ["C", "7", "Y"] + - ["D", "7", "Z"] + - ["E", "8", "Y"] + out: + - ["Table", "X", "Y", "Z"] + - ["7", "2", "1", "1"] + - ["8", "0", "1", "0"] + - name: "food-name-prefixes" + in: + orders: + elemType: "string" + value: + - ["A", "3", "Rice"] + - ["B", "3", "Rice Bowl"] + - ["C", "3", "R"] + out: + - ["Table", "R", "Rice", "Rice Bowl"] + - ["3", "1", "1", "1"] + - name: "reverse-input-tables" + in: + orders: + elemType: "string" + value: + - ["A", "9", "Soup"] + - ["B", "2", "Soup"] + - ["C", "5", "Soup"] + out: + - ["Table", "Soup"] + - ["2", "1"] + - ["5", "1"] + - ["9", "1"] + - name: "four-tables" + in: + orders: + elemType: "string" + value: + - ["A", "4", "A"] + - ["B", "1", "B"] + - ["C", "3", "C"] + - ["D", "2", "D"] + out: + - ["Table", "A", "B", "C", "D"] + - ["1", "0", "1", "0", "0"] + - ["2", "0", "0", "0", "1"] + - ["3", "0", "0", "1", "0"] + - ["4", "1", "0", "0", "0"] + - name: "four-foods-one-table" + in: + orders: + elemType: "string" + value: + - ["A", "11", "D"] + - ["B", "11", "B"] + - ["C", "11", "C"] + - ["D", "11", "A"] + out: + - ["Table", "A", "B", "C", "D"] + - ["11", "1", "1", "1", "1"] + - name: "zero-count-columns" + in: + orders: + elemType: "string" + value: + - ["A", "1", "Only One"] + - ["B", "2", "Only Two"] + out: + - ["Table", "Only One", "Only Two"] + - ["1", "1", "0"] + - ["2", "0", "1"] + - name: "repeated-foods-two-tables" + in: + orders: + elemType: "string" + value: + - ["A", "12", "Fish"] + - ["B", "12", "Fish"] + - ["C", "3", "Fish"] + - ["D", "3", "Fish"] + out: + - ["Table", "Fish"] + - ["3", "2"] + - ["12", "2"] + - name: "large-table-number" + in: + orders: + elemType: "string" + value: + - ["A", "500", "Meal"] + - ["B", "100", "Drink"] + - ["C", "500", "Dessert"] + out: + - ["Table", "Dessert", "Drink", "Meal"] + - ["100", "0", "1", "0"] + - ["500", "1", "0", "1"] + - name: "alphabetic-customers" + in: + orders: + elemType: "string" + value: + - ["Zoe", "1", "Tea"] + - ["Adam", "1", "Tea"] + - ["Mia", "2", "Coffee"] + out: + - ["Table", "Coffee", "Tea"] + - ["1", "0", "2"] + - ["2", "1", "0"] + - name: "food-space-order" + in: + orders: + elemType: "string" + value: + - ["A", "2", "Hot Dog"] + - ["B", "2", "Hot Chocolate"] + - ["C", "2", "Hot Sauce"] + out: + - ["Table", "Hot Chocolate", "Hot Dog", "Hot Sauce"] + - ["2", "1", "1", "1"] + - name: "six-orders" + in: + orders: + elemType: "string" + value: + - ["A", "1", "A"] + - ["B", "1", "B"] + - ["C", "2", "A"] + - ["D", "2", "C"] + - ["E", "3", "B"] + - ["F", "3", "C"] + out: + - ["Table", "A", "B", "C"] + - ["1", "1", "1", "0"] + - ["2", "1", "0", "1"] + - ["3", "0", "1", "1"] + - name: "seven-orders" + in: + orders: + elemType: "string" + value: + - ["A", "7", "Pasta"] + - ["B", "7", "Pasta"] + - ["C", "7", "Salad"] + - ["D", "8", "Pasta"] + - ["E", "8", "Salad"] + - ["F", "8", "Salad"] + - ["G", "8", "Water"] + out: + - ["Table", "Pasta", "Salad", "Water"] + - ["7", "2", "1", "0"] + - ["8", "1", "2", "1"] + - name: "ten-table" + in: + orders: + elemType: "string" + value: + - ["A", "10", "Soup"] + - ["B", "10", "Soup"] + - ["C", "10", "Bread"] + out: + - ["Table", "Bread", "Soup"] + - ["10", "1", "2"] + - name: "leading-table-numbers" + in: + orders: + elemType: "string" + value: + - ["A", "01", "A"] + - ["B", "1", "B"] + - ["C", "2", "C"] + out: + - ["Table", "A", "B", "C"] + - ["1", "1", "1", "0"] + - ["2", "0", "0", "1"] + - name: "many-foods" + in: + orders: + elemType: "string" + value: + - ["A", "4", "Apple"] + - ["B", "4", "Banana"] + - ["C", "4", "Cherry"] + - ["D", "4", "Date"] + - ["E", "4", "Eclair"] + - ["F", "4", "Fig"] + out: + - ["Table", "Apple", "Banana", "Cherry", "Date", "Eclair", "Fig"] + - ["4", "1", "1", "1", "1", "1", "1"] + - name: "mixed-counts" + in: + orders: + elemType: "string" + value: + - ["A", "2", "A"] + - ["B", "2", "A"] + - ["C", "2", "B"] + - ["D", "3", "B"] + - ["E", "3", "C"] + - ["F", "3", "C"] + - ["G", "3", "C"] + out: + - ["Table", "A", "B", "C"] + - ["2", "2", "1", "0"] + - ["3", "0", "1", "3"] + - name: "restaurant-menu" + in: + orders: + elemType: "string" + value: + - ["A", "1", "Burger"] + - ["B", "1", "Fries"] + - ["C", "2", "Burger"] + - ["D", "2", "Shake"] + - ["E", "3", "Fries"] + out: + - ["Table", "Burger", "Fries", "Shake"] + - ["1", "1", "1", "0"] + - ["2", "1", "0", "1"] + - ["3", "0", "1", "0"] + - name: "eight-orders" + in: + orders: + elemType: "string" + value: + - ["A", "1", "Soup"] + - ["B", "1", "Soup"] + - ["C", "1", "Tea"] + - ["D", "2", "Tea"] + - ["E", "2", "Cake"] + - ["F", "3", "Cake"] + - ["G", "3", "Cake"] + - ["H", "3", "Tea"] + out: + - ["Table", "Cake", "Soup", "Tea"] + - ["1", "0", "2", "1"] + - ["2", "1", "0", "1"] + - ["3", "2", "0", "1"] + - name: "case-sensitive-foods" + judge: + type: "ignore_order" + in: + orders: + elemType: "string" + value: + - ["A", "4", "apple"] + - ["B", "4", "Apple"] + - ["C", "4", "APPLE"] + out: + - ["Table", "APPLE", "Apple", "apple"] + - ["4", "1", "1", "1"] + - name: "ten-food-columns" + in: + orders: + elemType: "string" + value: + - ["A", "6", "A"] + - ["B", "6", "B"] + - ["C", "6", "C"] + - ["D", "6", "D"] + - ["E", "6", "E"] + - ["F", "6", "F"] + - ["G", "6", "G"] + - ["H", "6", "H"] + - ["I", "6", "I"] + - ["J", "6", "J"] + out: + - ["Table", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J"] + - ["6", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1"] + - name: "maximum-style-table-set" + in: + orders: + elemType: "string" + value: + - ["A", "100", "Noodles"] + - ["B", "20", "Sushi"] + - ["C", "3", "Curry"] + - ["D", "45", "Noodles"] + - ["E", "20", "Curry"] + - ["F", "100", "Sushi"] + out: + - ["Table", "Curry", "Noodles", "Sushi"] + - ["3", "1", "0", "0"] + - ["20", "1", "0", "1"] + - ["45", "0", "1", "0"] + - ["100", "0", "1", "1"] + - name: "single-food-many-tables" + in: + orders: + elemType: "string" + value: + - ["A", "1", "Water"] + - ["B", "2", "Water"] + - ["C", "3", "Water"] + - ["D", "4", "Water"] + - ["E", "5", "Water"] + out: + - ["Table", "Water"] + - ["1", "1"] + - ["2", "1"] + - ["3", "1"] + - ["4", "1"] + - ["5", "1"] + - name: "three-foods-repeated" + in: + orders: + elemType: "string" + value: + - ["A", "9", "Rice"] + - ["B", "9", "Rice"] + - ["C", "9", "Beans"] + - ["D", "10", "Rice"] + - ["E", "10", "Beans"] + - ["F", "10", "Taco"] + - ["G", "10", "Taco"] + out: + - ["Table", "Beans", "Rice", "Taco"] + - ["9", "1", "2", "0"] + - ["10", "1", "1", "2"] + - name: "irregular-input-order" + in: + orders: + elemType: "string" + value: + - ["A", "20", "Z"] + - ["B", "2", "A"] + - ["C", "11", "M"] + - ["D", "2", "Z"] + - ["E", "20", "A"] + out: + - ["Table", "A", "M", "Z"] + - ["2", "1", "0", "1"] + - ["11", "0", "1", "0"] + - ["20", "1", "0", "1"] + + - name: "maximum-valid-table-number" + in: + orders: + elemType: "string" + value: + - ["Customer One", "500", "abcdefghijklmnopqrst"] + - ["Customer Two", "499", "abcdefghijklmnopqrs"] + - ["Customer Three", "500", "abcdefghijklmnopqrst"] + out: + - ["Table", "abcdefghijklmnopqrs", "abcdefghijklmnopqrst"] + - ["499", "1", "0"] + - ["500", "0", "2"] + + - name: "maximum-single-cell-count" + in: + orders: + elemType: "string" + value: + - ["A", "250", "Special"] + - ["B", "250", "Special"] + - ["C", "250", "Special"] + - ["D", "250", "Special"] + - ["E", "250", "Special"] + - ["F", "250", "Special"] + - ["G", "250", "Special"] + - ["H", "250", "Special"] + - ["I", "250", "Special"] + - ["J", "250", "Special"] + out: + - ["Table", "Special"] + - ["250", "10"] + + - name: "customer-names-with-spaces" + in: + orders: + elemType: "string" + value: + - ["A B", "6", "Tea"] + - ["Customer Name", "6", "Tea"] + - ["C", "7", "Cake"] + out: + - ["Table", "Cake", "Tea"] + - ["6", "0", "2"] + - ["7", "1", "0"] + + - name: "twenty-character-food-boundary" + judge: + type: "ignore_order" + in: + orders: + elemType: "string" + value: + - ["A", "1", "abcdefghijklmnopqrst"] + - ["B", "2", "abcdefghijklmnopqrsT"] + - ["C", "3", "abcdefghijklmnopqrsT"] + out: + - ["Table", "abcdefghijklmnopqrsT", "abcdefghijklmnopqrst"] + - ["1", "0", "1"] + - ["2", "1", "0"] + - ["3", "1", "0"] + + - name: "adjacent-table-number-sorting" + in: + orders: + elemType: "string" + value: + - ["A", "100", "Meal"] + - ["B", "99", "Meal"] + - ["C", "101", "Drink"] + - ["D", "100", "Drink"] + out: + - ["Table", "Drink", "Meal"] + - ["99", "0", "1"] + - ["100", "1", "1"] + - ["101", "1", "0"] diff --git a/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.cpp b/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.cpp new file mode 100644 index 00000000..a692ed8d --- /dev/null +++ b/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + vector> displayTable(vector>& orders) { + set foodItems; + map> tableOrders; + + for (auto& order : orders) { + int table = stoi(order[1]); + string food = order[2]; + foodItems.insert(food); + tableOrders[table][food]++; + } + + vector sortedFoodItems(foodItems.begin(), foodItems.end()); + vector header = {"Table"}; + header.insert(header.end(), sortedFoodItems.begin(), sortedFoodItems.end()); + + vector> result; + result.push_back(header); + + for (auto& [table, foodMap] : tableOrders) { + vector row = {to_string(table)}; + for (auto& food : sortedFoodItems) { + row.push_back(to_string(foodMap[food])); + } + result.push_back(row); + } + + return result; + } +}; diff --git a/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.cs b/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.cs new file mode 100644 index 00000000..f2a287c7 --- /dev/null +++ b/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.cs @@ -0,0 +1,36 @@ +public class Solution { + public IList> DisplayTable(IList> orders) { + var foodItems = new SortedSet(); + var tableOrders = new SortedDictionary>(); + + foreach (var order in orders) { + int table = int.Parse(order[1]); + string food = order[2]; + foodItems.Add(food); + if (!tableOrders.ContainsKey(table)) { + tableOrders[table] = new Dictionary(); + } + if (tableOrders[table].ContainsKey(food)) { + tableOrders[table][food]++; + } else { + tableOrders[table][food] = 1; + } + } + + var header = new List { "Table" }; + header.AddRange(foodItems); + + var result = new List> { header }; + + foreach (var kvp in tableOrders) { + var row = new List { kvp.Key.ToString() }; + foreach (var food in foodItems) { + kvp.Value.TryGetValue(food, out int count); + row.Add(count.ToString()); + } + result.Add(row); + } + + return result; + } +} diff --git a/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.dart b/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.dart new file mode 100644 index 00000000..36dc68be --- /dev/null +++ b/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.dart @@ -0,0 +1,31 @@ +class Solution { + List> displayTable(List> orders) { + final Set foods = {}; + final Map> tableOrders = {}; + + for (final order in orders) { + final int table = int.parse(order[1]); + final String food = order[2]; + foods.add(food); + final counts = tableOrders.putIfAbsent(table, () => {}); + counts[food] = (counts[food] ?? 0) + 1; + } + + final sortedFoods = foods.toList()..sort(); + final sortedTables = tableOrders.keys.toList()..sort(); + + final result = >[ + ['Table', ...sortedFoods], + ]; + + for (final table in sortedTables) { + final counts = tableOrders[table]!; + result.add([ + table.toString(), + for (final food in sortedFoods) (counts[food] ?? 0).toString(), + ]); + } + + return result; + } +} diff --git a/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.go b/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.go new file mode 100644 index 00000000..eb85bd58 --- /dev/null +++ b/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.go @@ -0,0 +1,41 @@ +func displayTable(orders [][]string) [][]string { + foodItems := make(map[string]bool) + tableOrders := make(map[int]map[string]int) + + for _, order := range orders { + table, _ := strconv.Atoi(order[1]) + food := order[2] + foodItems[food] = true + if tableOrders[table] == nil { + tableOrders[table] = make(map[string]int) + } + tableOrders[table][food]++ + } + + sortedFoodItems := make([]string, 0, len(foodItems)) + for food := range foodItems { + sortedFoodItems = append(sortedFoodItems, food) + } + sort.Strings(sortedFoodItems) + + header := []string{"Table"} + header = append(header, sortedFoodItems...) + + result := [][]string{header} + + sortedTables := make([]int, 0, len(tableOrders)) + for table := range tableOrders { + sortedTables = append(sortedTables, table) + } + sort.Ints(sortedTables) + + for _, table := range sortedTables { + row := []string{strconv.Itoa(table)} + for _, food := range sortedFoodItems { + row = append(row, strconv.Itoa(tableOrders[table][food])) + } + result = append(result, row) + } + + return result +} diff --git a/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.java b/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.java new file mode 100644 index 00000000..1708a228 --- /dev/null +++ b/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.java @@ -0,0 +1,46 @@ +class Solution { + public List> displayTable(String[][] orders) { + List> converted = new ArrayList<>(); + for (String[] order : orders) { + converted.add(Arrays.asList(order)); + } + return displayTable(converted); + } + + public List> displayTable(List> orders) { + Set foodItems = new HashSet<>(); + Map> tableOrders = new HashMap<>(); + + for (List order : orders) { + String food = order.get(2); + int table = Integer.parseInt(order.get(1)); + foodItems.add(food); + tableOrders.computeIfAbsent(table, k -> new HashMap<>()) + .merge(food, 1, Integer::sum); + } + + List sortedFoodItems = new ArrayList<>(foodItems); + Collections.sort(sortedFoodItems); + List header = new ArrayList<>(); + header.add("Table"); + header.addAll(sortedFoodItems); + + List> result = new ArrayList<>(); + result.add(header); + + List sortedTables = new ArrayList<>(tableOrders.keySet()); + Collections.sort(sortedTables); + + for (int table : sortedTables) { + List row = new ArrayList<>(); + row.add(String.valueOf(table)); + Map tableMap = tableOrders.get(table); + for (String food : sortedFoodItems) { + row.add(String.valueOf(tableMap.getOrDefault(food, 0))); + } + result.add(row); + } + + return result; + } +} diff --git a/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.kt b/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.kt new file mode 100644 index 00000000..bb98efa9 --- /dev/null +++ b/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.kt @@ -0,0 +1,35 @@ +class Solution { + fun displayTable(orders: Array>): List> { + return displayTable(orders.map { it.toList() }) + } + + fun displayTable(orders: List>): List> { + val foodItems = mutableSetOf() + val tableOrders = mutableMapOf>() + + for ((_, table, food) in orders) { + foodItems.add(food) + val t = table.toInt() + tableOrders.getOrPut(t) { mutableMapOf() } + .merge(food, 1, Int::plus) + } + + val sortedFoodItems = foodItems.toList().sorted() + val header = mutableListOf("Table") + header.addAll(sortedFoodItems) + + val result = mutableListOf>() + result.add(header) + + for (table in tableOrders.keys.sorted()) { + val row = mutableListOf(table.toString()) + val tableMap = tableOrders[table]!! + for (food in sortedFoodItems) { + row.add((tableMap[food] ?: 0).toString()) + } + result.add(row) + } + + return result + } +} diff --git a/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.py b/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.py new file mode 100644 index 00000000..0b1e80a4 --- /dev/null +++ b/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.py @@ -0,0 +1,27 @@ +from collections import defaultdict + + +class Solution(object): + def displayTable(self, orders): + """ + :type orders: List[List[str]] + :rtype: List[List[str]] + """ + food_items = set() + table_orders = defaultdict(lambda: defaultdict(int)) + + for customer, table, food in orders: + food_items.add(food) + table_orders[int(table)][food] += 1 + + sorted_food_items = sorted(food_items) + header = ["Table"] + sorted_food_items + + result = [header] + for table in sorted(table_orders): + row = [str(table)] + for food in sorted_food_items: + row.append(str(table_orders[table][food])) + result.append(row) + + return result diff --git a/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.py2 b/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.py2 new file mode 100644 index 00000000..fee731b0 --- /dev/null +++ b/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.py2 @@ -0,0 +1,25 @@ +class Solution(object): + def displayTable(self, orders): + """ + :type orders: List[List[str]] + :rtype: List[List[str]] + """ + food_items = set() + from collections import defaultdict + table_orders = defaultdict(lambda: defaultdict(int)) + + for customer, table, food in orders: + food_items.add(food) + table_orders[int(table)][food] += 1 + + sorted_food_items = sorted(food_items) + header = ["Table"] + sorted_food_items + + result = [header] + for table in sorted(table_orders): + row = [str(table)] + for food in sorted_food_items: + row.append(str(table_orders[table][food])) + result.append(row) + + return result diff --git a/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.rb b/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.rb new file mode 100644 index 00000000..fa398289 --- /dev/null +++ b/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.rb @@ -0,0 +1,25 @@ +# @param {String[][]} orders +# @return {String[][]} +def display_table(orders) + food_items = Set.new + table_orders = Hash.new { |h, k| h[k] = Hash.new(0) } + + orders.each do |customer, table, food| + food_items.add(food) + table_orders[table.to_i][food] += 1 + end + + sorted_food_items = food_items.to_a.sort + header = ["Table"] + sorted_food_items + + result = [header] + table_orders.keys.sort.each do |table| + row = [table.to_s] + sorted_food_items.each do |food| + row << table_orders[table][food].to_s + end + result << row + end + + result +end diff --git a/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.rs b/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.rs new file mode 100644 index 00000000..fdba1b79 --- /dev/null +++ b/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.rs @@ -0,0 +1,35 @@ +impl Solution { + pub fn display_table(orders: Vec>) -> Vec> { + use std::collections::{BTreeSet, HashMap, BTreeMap}; + + let mut food_items = BTreeSet::new(); + let mut table_orders: BTreeMap> = BTreeMap::new(); + + for order in &orders { + let table: i32 = order[1].parse().unwrap(); + let food = &order[2]; + food_items.insert(food.clone()); + table_orders.entry(table) + .or_insert_with(HashMap::new) + .entry(food.clone()) + .and_modify(|e| *e += 1) + .or_insert(1); + } + + let sorted_food_items: Vec = food_items.into_iter().collect(); + let mut header = vec!["Table".to_string()]; + header.extend(sorted_food_items.clone()); + + let mut result = vec![header]; + + for (table, food_map) in &table_orders { + let mut row = vec![table.to_string()]; + for food in &sorted_food_items { + row.push(food_map.get(food).unwrap_or(&0).to_string()); + } + result.push(row); + } + + result + } +} diff --git a/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.swift b/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.swift new file mode 100644 index 00000000..a9e09079 --- /dev/null +++ b/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.swift @@ -0,0 +1,31 @@ +class Solution { + func displayTable(_ orders: [[String]]) -> [[String]] { + var foodItems = Set() + var tableOrders = [Int: [String: Int]]() + + for order in orders { + let table = Int(order[1])! + let food = order[2] + foodItems.insert(food) + tableOrders[table, default: [:]][food, default: 0] += 1 + } + + let sortedFoodItems = foodItems.sorted() + var header = ["Table"] + header.append(contentsOf: sortedFoodItems) + + var result = [[String]]() + result.append(header) + + for table in tableOrders.keys.sorted() { + var row = [String(table)] + let tableMap = tableOrders[table]! + for food in sortedFoodItems { + row.append(String(tableMap[food] ?? 0)) + } + result.append(row) + } + + return result + } +} diff --git a/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.ts b/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.ts new file mode 100644 index 00000000..ff1bf054 --- /dev/null +++ b/tests/1001-1500/1418. display-table-of-food-orders-in-a-restaurant/sol.ts @@ -0,0 +1,31 @@ +function displayTable(orders: string[][]): string[][] { + const foodItems = new Set(); + const tableOrders = new Map>(); + + for (const [, tableStr, food] of orders) { + const table = parseInt(tableStr, 10); + foodItems.add(food); + if (!tableOrders.has(table)) { + tableOrders.set(table, new Map()); + } + const foodMap = tableOrders.get(table)!; + foodMap.set(food, (foodMap.get(food) || 0) + 1); + } + + const sortedFoodItems = Array.from(foodItems).sort(); + const header = ["Table", ...sortedFoodItems]; + + const result: string[][] = [header]; + const sortedTables = Array.from(tableOrders.keys()).sort((a, b) => a - b); + + for (const table of sortedTables) { + const row: string[] = [table.toString()]; + const foodMap = tableOrders.get(table)!; + for (const food of sortedFoodItems) { + row.push((foodMap.get(food) || 0).toString()); + } + result.push(row); + } + + return result; +} diff --git a/tests/1001-1500/1419. minimum-number-of-frogs-croaking/manifest.yaml b/tests/1001-1500/1419. minimum-number-of-frogs-croaking/manifest.yaml new file mode 100644 index 00000000..f7e62da8 --- /dev/null +++ b/tests/1001-1500/1419. minimum-number-of-frogs-croaking/manifest.yaml @@ -0,0 +1,223 @@ +entry: + id: 1419 + title: minimum-number-of-frogs-croaking + params: + croakOfFrogs: + type: string + call: + cpp: "Solution().minNumberOfFrogs({croakOfFrogs})" + rust: "Solution::min_number_of_frogs({croakOfFrogs})" + python3: "Solution().minNumberOfFrogs({croakOfFrogs})" + python2: "Solution().minNumberOfFrogs({croakOfFrogs})" + ruby: "min_number_of_frogs({croakOfFrogs})" + java: "new Solution().minNumberOfFrogs({croakOfFrogs})" + csharp: "new Solution().MinNumberOfFrogs({croakOfFrogs})" + kotlin: "Solution().minNumberOfFrogs({croakOfFrogs})" + go: "minNumberOfFrogs({croakOfFrogs})" + dart: "Solution().minNumberOfFrogs({croakOfFrogs})" + swift: "Solution().minNumberOfFrogs({croakOfFrogs})" + typescript: "minNumberOfFrogs({croakOfFrogs})" +judge: + type: exact +limits: + time_ms: 500 + memory_mb: 256 +oracle: + python3: + call: "Checker().minNumberOfFrogs(croakOfFrogs, {result})" + checker: | + class Checker: + def minNumberOfFrogs(self, text, result): + if not isinstance(text, str) or not isinstance(result, int) or isinstance(result, bool): + return False + order = {'c': 0, 'r': 1, 'o': 2, 'a': 3, 'k': 4} + stages = [0] * 5 + active = 0 + maximum = 0 + for char in text: + if char not in order: + return result == -1 + stage = order[char] + if stage == 0: + stages[0] += 1 + active += 1 + maximum = max(maximum, active) + else: + if stages[stage - 1] <= stages[stage]: + return result == -1 + stages[stage] += 1 + if stage == 4: + active -= 1 + expected = maximum if active == 0 and stages[0] == stages[1] == stages[2] == stages[3] == stages[4] else -1 + return result == expected +seed: 1419 +tests: + - name: single_invalid_o + in: + croakOfFrogs: o + out: -1 + - name: one_call + in: + croakOfFrogs: croak + out: 1 + - name: two_sequential + in: + croakOfFrogs: croakcroak + out: 1 + - name: three_sequential + in: + croakOfFrogs: croakcroakcroak + out: 1 + - name: two_overlapping + in: + croakOfFrogs: ccrrooaakk + out: 2 + - name: three_overlapping + in: + croakOfFrogs: cccrrroooaaakkk + out: 3 + - name: example_valid + in: + croakOfFrogs: croakcroak + out: 1 + - name: example_invalid_order + in: + croakOfFrogs: croakcroakcr + out: -1 + - name: invalid_starts_r + in: + croakOfFrogs: r + out: -1 + - name: invalid_starts_k + in: + croakOfFrogs: k + out: -1 + - name: incomplete_c + in: + croakOfFrogs: c + out: -1 + - name: incomplete_cro + in: + croakOfFrogs: cro + out: -1 + - name: incomplete_croa + in: + croakOfFrogs: croa + out: -1 + - name: wrong_cr + in: + croakOfFrogs: cr + out: -1 + - name: wrong_co + in: + croakOfFrogs: co + out: -1 + - name: wrong_ca + in: + croakOfFrogs: ca + out: -1 + - name: wrong_ck + in: + croakOfFrogs: ck + out: -1 + - name: extra_r + in: + croakOfFrogs: croakr + out: -1 + - name: early_k + in: + croakOfFrogs: croakkk + out: -1 + - name: late_r + in: + croakOfFrogs: croakcr + out: -1 + - name: split_overlap + in: + croakOfFrogs: ccroakrokak + out: -1 + - name: alternating_calls + in: + croakOfFrogs: ccrrooaakkcroak + out: 2 + - name: four_overlap + in: + croakOfFrogs: ccccrrrrooooaaaakkkk + out: 4 + - name: invalid_extra_c + in: + croakOfFrogs: ccrcrooaakkak + out: -1 + - name: invalid_missing_o + in: + croakOfFrogs: crak + out: -1 + - name: invalid_missing_a + in: + croakOfFrogs: crok + out: -1 + - name: invalid_missing_r + in: + croakOfFrogs: coak + out: -1 + - name: invalid_suffix_c + in: + croakOfFrogs: croakcroakc + out: -1 + - name: invalid_prefix_c + in: + croakOfFrogs: ccroak + out: -1 + - name: five_sequential + in: + croakOfFrogs: croakcroakcroakcroakcroak + out: 1 + - name: five_overlap + in: + croakOfFrogs: cccccrrrrroooooaaaaakkkkk + out: 5 + - name: six_sequential + in: + croakOfFrogs: croakcroakcroakcroakcroakcroak + out: 1 + - name: stage_switching + in: + croakOfFrogs: ccrroakcroak + out: -1 + - name: invalid_o_first + in: + croakOfFrogs: ocrak + out: -1 + - name: invalid_a_first + in: + croakOfFrogs: acrok + out: -1 + - name: long_valid_overlap + in: + croakOfFrogs: ccccrrrrooooaaaakkkkcroak + out: 4 + - name: final_invalid + in: + croakOfFrogs: croakcroakcro + out: -1 + - name: max_length_random_a + seed: 1419001 + in: + croakOfFrogs: + gen: str + len: 100000 + alphabet: croak + - name: max_length_random_b + seed: 1419002 + in: + croakOfFrogs: + gen: str + len: 99999 + alphabet: croak + - name: medium_random_boundary + seed: 1419003 + in: + croakOfFrogs: + gen: str + len: 50000 + alphabet: croak diff --git a/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.cpp b/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.cpp new file mode 100644 index 00000000..75ea83da --- /dev/null +++ b/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + int minNumberOfFrogs(string croakOfFrogs) { + int maxi = 0; + int curr = 0; + int c = 0, r = 0, o = 0, a = 0, k = 0; + for (char ch : croakOfFrogs) { + if (ch == 'c') { + c++; + curr++; + } else if (ch == 'r') { + r++; + } else if (ch == 'o') { + o++; + } else if (ch == 'a') { + a++; + } else if (ch == 'k') { + k++; + curr--; + } + maxi = max(maxi, curr); + if (c < r || r < o || o < a || a < k) { + return -1; + } + } + if (curr == 0 && c == r && r == o && o == a && a == k) { + return maxi; + } else { + return -1; + } + } +}; diff --git a/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.cs b/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.cs new file mode 100644 index 00000000..3012a279 --- /dev/null +++ b/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.cs @@ -0,0 +1,31 @@ +public class Solution { + public int MinNumberOfFrogs(string croakOfFrogs) { + int maxi = 0; + int curr = 0; + int c = 0, r = 0, o = 0, a = 0, k = 0; + foreach (char ch in croakOfFrogs) { + if (ch == 'c') { + c++; + curr++; + } else if (ch == 'r') { + r++; + } else if (ch == 'o') { + o++; + } else if (ch == 'a') { + a++; + } else if (ch == 'k') { + k++; + curr--; + } + maxi = Math.Max(maxi, curr); + if (c < r || r < o || o < a || a < k) { + return -1; + } + } + if (curr == 0 && c == r && r == o && o == a && a == k) { + return maxi; + } else { + return -1; + } + } +} diff --git a/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.dart b/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.dart new file mode 100644 index 00000000..bc89a4b7 --- /dev/null +++ b/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.dart @@ -0,0 +1,31 @@ +class Solution { + int minNumberOfFrogs(String croakOfFrogs) { + int maxi = 0; + int curr = 0; + int c = 0, r = 0, o = 0, a = 0, k = 0; + for (var ch in croakOfFrogs.split('')) { + if (ch == 'c') { + c++; + curr++; + } else if (ch == 'r') { + r++; + } else if (ch == 'o') { + o++; + } else if (ch == 'a') { + a++; + } else if (ch == 'k') { + k++; + curr--; + } + maxi = maxi > curr ? maxi : curr; + if (c < r || r < o || o < a || a < k) { + return -1; + } + } + if (curr == 0 && c == r && r == o && o == a && a == k) { + return maxi; + } else { + return -1; + } + } +} diff --git a/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.go b/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.go new file mode 100644 index 00000000..bfbc7cc6 --- /dev/null +++ b/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.go @@ -0,0 +1,31 @@ +func minNumberOfFrogs(croakOfFrogs string) int { + maxi := 0 + curr := 0 + c, r, o, a, k := 0, 0, 0, 0, 0 + for _, ch := range croakOfFrogs { + if ch == 'c' { + c++ + curr++ + } else if ch == 'r' { + r++ + } else if ch == 'o' { + o++ + } else if ch == 'a' { + a++ + } else if ch == 'k' { + k++ + curr-- + } + if curr > maxi { + maxi = curr + } + if c < r || r < o || o < a || a < k { + return -1 + } + } + if curr == 0 && c == r && r == o && o == a && a == k { + return maxi + } else { + return -1 + } +} diff --git a/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.java b/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.java new file mode 100644 index 00000000..58f32c00 --- /dev/null +++ b/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.java @@ -0,0 +1,31 @@ +class Solution { + public int minNumberOfFrogs(String croakOfFrogs) { + int maxi = 0; + int curr = 0; + int c = 0, r = 0, o = 0, a = 0, k = 0; + for (char ch : croakOfFrogs.toCharArray()) { + if (ch == 'c') { + c++; + curr++; + } else if (ch == 'r') { + r++; + } else if (ch == 'o') { + o++; + } else if (ch == 'a') { + a++; + } else if (ch == 'k') { + k++; + curr--; + } + maxi = Math.max(maxi, curr); + if (c < r || r < o || o < a || a < k) { + return -1; + } + } + if (curr == 0 && c == r && r == o && o == a && a == k) { + return maxi; + } else { + return -1; + } + } +} diff --git a/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.kt b/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.kt new file mode 100644 index 00000000..5d5885b6 --- /dev/null +++ b/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.kt @@ -0,0 +1,35 @@ +class Solution { + fun minNumberOfFrogs(croakOfFrogs: String): Int { + var maxi = 0 + var curr = 0 + var c = 0 + var r = 0 + var o = 0 + var a = 0 + var k = 0 + for (ch in croakOfFrogs) { + when (ch) { + 'c' -> { + c++ + curr++ + } + 'r' -> r++ + 'o' -> o++ + 'a' -> a++ + 'k' -> { + k++ + curr-- + } + } + maxi = maxOf(maxi, curr) + if (c < r || r < o || o < a || a < k) { + return -1 + } + } + if (curr == 0 && c == r && r == o && o == a && a == k) { + return maxi + } else { + return -1 + } + } +} diff --git a/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.py b/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.py new file mode 100644 index 00000000..2cff1f20 --- /dev/null +++ b/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.py @@ -0,0 +1,25 @@ +class Solution: + def minNumberOfFrogs(self, croakOfFrogs: str) -> int: + maxi = 0 + curr = 0 + c = r = o = a = k = 0 + for char in croakOfFrogs: + if char == "c": + c += 1 + curr += 1 + elif char == "r": + r += 1 + elif char == "o": + o += 1 + elif char == "a": + a += 1 + elif char == "k": + k += 1 + curr -= 1 + maxi = max(maxi, curr) + if c < r or r < o or o < a or a < k: + return -1 + if curr == 0 and c == r == o == a == k: + return maxi + else: + return -1 diff --git a/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.py2 b/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.py2 new file mode 100644 index 00000000..2dd4e38f --- /dev/null +++ b/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.py2 @@ -0,0 +1,29 @@ +class Solution(object): + def minNumberOfFrogs(self, croakOfFrogs): + """ + :type croakOfFrogs: str + :rtype: int + """ + maxi = 0 + curr = 0 + c = r = o = a = k = 0 + for char in croakOfFrogs: + if char == "c": + c += 1 + curr += 1 + elif char == "r": + r += 1 + elif char == "o": + o += 1 + elif char == "a": + a += 1 + elif char == "k": + k += 1 + curr -= 1 + maxi = max(maxi, curr) + if c < r or r < o or o < a or a < k: + return -1 + if curr == 0 and c == r == o == a == k: + return maxi + else: + return -1 diff --git a/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.rb b/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.rb new file mode 100644 index 00000000..cfa18bb7 --- /dev/null +++ b/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.rb @@ -0,0 +1,31 @@ +# @param {String} croak_of_frogs +# @return {Integer} +def min_number_of_frogs(croak_of_frogs) + maxi = 0 + curr = 0 + c = r = o = a = k = 0 + croak_of_frogs.each_char do |char| + if char == 'c' + c += 1 + curr += 1 + elsif char == 'r' + r += 1 + elsif char == 'o' + o += 1 + elsif char == 'a' + a += 1 + elsif char == 'k' + k += 1 + curr -= 1 + end + maxi = [maxi, curr].max + if c < r || r < o || o < a || a < k + return -1 + end + end + if curr == 0 && c == r && r == o && o == a && a == k + return maxi + else + return -1 + end +end diff --git a/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.rs b/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.rs new file mode 100644 index 00000000..c6eefc7d --- /dev/null +++ b/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.rs @@ -0,0 +1,35 @@ +impl Solution { + pub fn min_number_of_frogs(croak_of_frogs: String) -> i32 { + let mut maxi = 0; + let mut curr = 0; + let mut c = 0; + let mut r = 0; + let mut o = 0; + let mut a = 0; + let mut k = 0; + for ch in croak_of_frogs.chars() { + if ch == 'c' { + c += 1; + curr += 1; + } else if ch == 'r' { + r += 1; + } else if ch == 'o' { + o += 1; + } else if ch == 'a' { + a += 1; + } else if ch == 'k' { + k += 1; + curr -= 1; + } + maxi = maxi.max(curr); + if c < r || r < o || o < a || a < k { + return -1; + } + } + if curr == 0 && c == r && r == o && o == a && a == k { + return maxi; + } else { + return -1; + } + } +} diff --git a/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.swift b/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.swift new file mode 100644 index 00000000..0c36af6c --- /dev/null +++ b/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.swift @@ -0,0 +1,31 @@ +class Solution { + func minNumberOfFrogs(_ croakOfFrogs: String) -> Int { + var maxi = 0 + var curr = 0 + var c = 0, r = 0, o = 0, a = 0, k = 0 + for char in croakOfFrogs { + if char == "c" { + c += 1 + curr += 1 + } else if char == "r" { + r += 1 + } else if char == "o" { + o += 1 + } else if char == "a" { + a += 1 + } else if char == "k" { + k += 1 + curr -= 1 + } + maxi = max(maxi, curr) + if c < r || r < o || o < a || a < k { + return -1 + } + } + if curr == 0 && c == r && r == o && o == a && a == k { + return maxi + } else { + return -1 + } + } +} diff --git a/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.ts b/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.ts new file mode 100644 index 00000000..ea9f5bdf --- /dev/null +++ b/tests/1001-1500/1419. minimum-number-of-frogs-croaking/sol.ts @@ -0,0 +1,33 @@ +function minNumberOfFrogs(croakOfFrogs: string): number { + let maxi = 0; + let curr = 0; + let c = 0, + r = 0, + o = 0, + a = 0, + k = 0; + for (const char of croakOfFrogs) { + if (char === "c") { + c++; + curr++; + } else if (char === "r") { + r++; + } else if (char === "o") { + o++; + } else if (char === "a") { + a++; + } else if (char === "k") { + k++; + curr--; + } + maxi = Math.max(maxi, curr); + if (c < r || r < o || o < a || a < k) { + return -1; + } + } + if (curr === 0 && c === r && r === o && o === a && a === k) { + return maxi; + } else { + return -1; + } +} diff --git a/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/manifest.yaml b/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/manifest.yaml new file mode 100644 index 00000000..0e66bbbc --- /dev/null +++ b/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/manifest.yaml @@ -0,0 +1,293 @@ +entry: + id: 1420 + title: "build-array-where-you-can-find-the-maximum-exactly-k-comparisons" + params: + n: + type: int + m: + type: int + k: + type: int + call: + cpp: "Solution().numOfArrays({n}, {m}, {k})" + rust: "Solution::num_of_arrays({n}, {m}, {k})" + python3: "Solution().numOfArrays({n}, {m}, {k})" + python2: "Solution().numOfArrays({n}, {m}, {k})" + ruby: "num_of_arrays({n}, {m}, {k})" + java: "new Solution().numOfArrays({n}, {m}, {k})" + csharp: "new Solution().NumOfArrays({n}, {m}, {k})" + kotlin: "Solution().numOfArrays({n}, {m}, {k})" + go: "numOfArrays({n}, {m}, {k})" + dart: "Solution().numOfArrays({n}, {m}, {k})" + swift: "Solution().numOfArrays({n}, {m}, {k})" + typescript: "numOfArrays({n}, {m}, {k})" +judge: + type: "exact" +limits: + time_ms: 10000 + memory_mb: 400 +oracle: + python3: + call: "Checker().numOfArrays(n, m, k, {result})" + checker: | + class Checker: + def numOfArrays(self, n, m, k, result): + if not isinstance(n, int) or not isinstance(m, int) or not isinstance(k, int): + return False + if not (1 <= n <= 50 and 1 <= m <= 100 and 0 <= k <= n): + return False + if not isinstance(result, int) or isinstance(result, bool): + return False + mod = 1000000007 + states = {(0, 0): 1} + for _ in range(n): + next_states = {} + for (cost, maximum), ways in states.items(): + for value in range(1, m + 1): + new_cost = cost + (value > maximum) + if new_cost <= k: + key = (new_cost, max(maximum, value)) + next_states[key] = (next_states.get(key, 0) + ways) % mod + states = next_states + expected = sum(ways for (cost, _), ways in states.items() if cost == k) % mod + return result == expected +seed: 1420 +tests: + - name: "one_one_one" + in: + n: 1 + m: 1 + k: 1 + - name: "one_many" + in: + n: 1 + m: 5 + k: 1 + - name: "one_invalid" + in: + n: 1 + m: 5 + k: 2 + out: 0 + - name: "constant_max" + in: + n: 3 + m: 1 + k: 1 + - name: "two_cost_one" + in: + n: 2 + m: 3 + k: 1 + - name: "two_cost_two" + in: + n: 2 + m: 3 + k: 2 + - name: "two_invalid" + in: + n: 2 + m: 3 + k: 3 + out: 0 + - name: "example_small" + in: + n: 3 + m: 2 + k: 1 + - name: "example_cost_two" + in: + n: 3 + m: 3 + k: 2 + - name: "small_all_costs" + in: + n: 4 + m: 3 + k: 1 + - name: "small_cost_two" + in: + n: 4 + m: 3 + k: 2 + - name: "small_cost_three" + in: + n: 4 + m: 3 + k: 3 + - name: "max_cost" + in: + n: 4 + m: 4 + k: 4 + - name: "max_cost_invalid" + in: + n: 4 + m: 2 + k: 4 + out: 0 + - name: "balanced_a" + in: + n: 5 + m: 3 + k: 2 + - name: "balanced_b" + in: + n: 5 + m: 4 + k: 3 + - name: "balanced_c" + in: + n: 5 + m: 5 + k: 4 + - name: "six_one" + in: + n: 6 + m: 2 + k: 1 + - name: "six_two" + in: + n: 6 + m: 2 + k: 2 + - name: "six_three" + in: + n: 6 + m: 3 + k: 3 + - name: "seven_two" + in: + n: 7 + m: 4 + k: 2 + - name: "seven_four" + in: + n: 7 + m: 4 + k: 4 + - name: "eight_three" + in: + n: 8 + m: 5 + k: 3 + - name: "eight_five" + in: + n: 8 + m: 5 + k: 5 + - name: "nine_four" + in: + n: 9 + m: 6 + k: 4 + - name: "ten_one" + in: + n: 10 + m: 3 + k: 1 + - name: "ten_ten" + in: + n: 10 + m: 10 + k: 10 + - name: "boundary_m" + in: + n: 6 + m: 100 + k: 1 + - name: "boundary_k" + in: + n: 6 + m: 100 + k: 6 + - name: "modulo_case" + in: + n: 15 + m: 15 + k: 7 + - name: "single_max_m" + in: + n: 1 + m: 100 + k: 1 + - name: "maximum_length_constant" + in: + n: 50 + m: 1 + k: 1 + - name: "maximum_length_cost_one" + in: + n: 50 + m: 100 + k: 1 + - name: "maximum_length_max_cost" + in: + n: 50 + m: 100 + k: 50 + - name: "maximum_length_mid_cost" + in: + n: 50 + m: 100 + k: 25 + - name: "generated_max_length_high_m_low_k" + seed: 142001 + in: + n: 50 + m: + gen: "int" + min: 80 + max: 100 + k: + gen: "int" + min: 1 + max: 10 + - name: "generated_max_length_high_m_mid_k" + seed: 142002 + in: + n: 50 + m: + gen: "int" + min: 80 + max: 100 + k: + gen: "int" + min: 11 + max: 25 + - name: "generated_max_length_high_m_high_k" + seed: 142003 + in: + n: 50 + m: + gen: "int" + min: 80 + max: 100 + k: + gen: "int" + min: 26 + max: 50 + - name: "generated_max_length_full_m_low_k" + seed: 142004 + in: + n: 50 + m: + gen: "int" + min: 1 + max: 100 + k: + gen: "int" + min: 1 + max: 10 + - name: "generated_max_length_full_m_mid_k" + seed: 142005 + in: + n: 50 + m: + gen: "int" + min: 1 + max: 100 + k: + gen: "int" + min: 11 + max: 50 diff --git a/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.cpp b/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.cpp new file mode 100644 index 00000000..9d0b8c8a --- /dev/null +++ b/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.cpp @@ -0,0 +1,39 @@ +class Solution { +private: + static const int MOD = 1'000'000'007; + vector>> dp; + int n, m, k; + + int solve(int idx, int searchCost, int maxValue) { + if (idx == n) { + return searchCost == k ? 1 : 0; + } + if (searchCost > k) { + return 0; + } + if (dp[idx][searchCost][maxValue] != -1) { + return dp[idx][searchCost][maxValue]; + } + + int result = 0; + for (int i = 1; i <= m; ++i) { + if (i > maxValue) { + result = (result + solve(idx + 1, searchCost + 1, i)) % MOD; + } else { + result = (result + solve(idx + 1, searchCost, maxValue)) % MOD; + } + } + + dp[idx][searchCost][maxValue] = result; + return result; + } + +public: + int numOfArrays(int n, int m, int k) { + this->n = n; + this->m = m; + this->k = k; + dp = vector>>(n + 1, vector>(k + 1, vector(m + 1, -1))); + return solve(0, 0, 0); + } +}; diff --git a/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.cs b/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.cs new file mode 100644 index 00000000..c7337f2f --- /dev/null +++ b/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.cs @@ -0,0 +1,41 @@ +public class Solution { + private const int MOD = 1_000_000_007; + private int[,,] dp; + private int n, m, k; + + public int NumOfArrays(int n, int m, int k) { + this.n = n; + this.m = m; + this.k = k; + dp = new int[n + 1, k + 1, m + 1]; + for (int i = 0; i <= n; i++) + for (int j = 0; j <= k; j++) + for (int l = 0; l <= m; l++) + dp[i, j, l] = -1; + return Solve(0, 0, 0); + } + + private int Solve(int idx, int searchCost, int maxValue) { + if (idx == n) { + return searchCost == k ? 1 : 0; + } + if (searchCost > k) { + return 0; + } + if (dp[idx, searchCost, maxValue] != -1) { + return dp[idx, searchCost, maxValue]; + } + + int result = 0; + for (int i = 1; i <= m; i++) { + if (i > maxValue) { + result = (result + Solve(idx + 1, searchCost + 1, i)) % MOD; + } else { + result = (result + Solve(idx + 1, searchCost, maxValue)) % MOD; + } + } + + dp[idx, searchCost, maxValue] = result; + return result; + } +} diff --git a/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.dart b/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.dart new file mode 100644 index 00000000..1e962313 --- /dev/null +++ b/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.dart @@ -0,0 +1,31 @@ +class Solution { + static const int MOD = 1000000007; + late List>> dp; + late int n, m, k; + + int numOfArrays(int n, int m, int k) { + this.n = n; + this.m = m; + this.k = k; + dp = List.generate(n + 1, (_) => List.generate(k + 1, (_) => List.filled(m + 1, -1))); + return solve(0, 0, 0); + } + + int solve(int idx, int searchCost, int maxValue) { + if (idx == n) return searchCost == k ? 1 : 0; + if (searchCost > k) return 0; + if (dp[idx][searchCost][maxValue] != -1) return dp[idx][searchCost][maxValue]; + + int result = 0; + for (int i = 1; i <= m; i++) { + if (i > maxValue) { + result = (result + solve(idx + 1, searchCost + 1, i)) % MOD; + } else { + result = (result + solve(idx + 1, searchCost, maxValue)) % MOD; + } + } + + dp[idx][searchCost][maxValue] = result; + return result; + } +} diff --git a/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.go b/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.go new file mode 100644 index 00000000..e434c92e --- /dev/null +++ b/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.go @@ -0,0 +1,44 @@ +func numOfArrays(n int, m int, k int) int { + const MOD = 1_000_000_007 + + dp := make([][][]int, n+1) + for i := range dp { + dp[i] = make([][]int, k+1) + for j := range dp[i] { + dp[i][j] = make([]int, m+1) + for l := range dp[i][j] { + dp[i][j][l] = -1 + } + } + } + + var solve func(idx, searchCost, maxValue int) int + solve = func(idx, searchCost, maxValue int) int { + if idx == n { + if searchCost == k { + return 1 + } + return 0 + } + if searchCost > k { + return 0 + } + if dp[idx][searchCost][maxValue] != -1 { + return dp[idx][searchCost][maxValue] + } + + result := 0 + for i := 1; i <= m; i++ { + if i > maxValue { + result = (result + solve(idx+1, searchCost+1, i)) % MOD + } else { + result = (result + solve(idx+1, searchCost, maxValue)) % MOD + } + } + + dp[idx][searchCost][maxValue] = result + return result + } + + return solve(0, 0, 0) +} diff --git a/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.java b/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.java new file mode 100644 index 00000000..1f2500e1 --- /dev/null +++ b/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.java @@ -0,0 +1,37 @@ +class Solution { + private static final int MOD = 1_000_000_007; + private Integer[][][] dp; + private int n, m, k; + + public int numOfArrays(int n, int m, int k) { + this.n = n; + this.m = m; + this.k = k; + dp = new Integer[n + 1][k + 1][m + 1]; + return solve(0, 0, 0); + } + + private int solve(int idx, int searchCost, int maxValue) { + if (idx == n) { + return searchCost == k ? 1 : 0; + } + if (searchCost > k) { + return 0; + } + if (dp[idx][searchCost][maxValue] != null) { + return dp[idx][searchCost][maxValue]; + } + + int result = 0; + for (int i = 1; i <= m; i++) { + if (i > maxValue) { + result = (result + solve(idx + 1, searchCost + 1, i)) % MOD; + } else { + result = (result + solve(idx + 1, searchCost, maxValue)) % MOD; + } + } + + dp[idx][searchCost][maxValue] = result; + return result; + } +} diff --git a/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.kt b/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.kt new file mode 100644 index 00000000..475aafd3 --- /dev/null +++ b/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.kt @@ -0,0 +1,33 @@ +class Solution { + private val MOD = 1_000_000_007 + private lateinit var dp: Array> + private var n = 0 + private var m = 0 + private var k = 0 + + fun numOfArrays(n: Int, m: Int, k: Int): Int { + this.n = n + this.m = m + this.k = k + dp = Array(n + 1) { Array(k + 1) { IntArray(m + 1) { -1 } } } + return solve(0, 0, 0) + } + + private fun solve(idx: Int, searchCost: Int, maxValue: Int): Int { + if (idx == n) return if (searchCost == k) 1 else 0 + if (searchCost > k) return 0 + if (dp[idx][searchCost][maxValue] != -1) return dp[idx][searchCost][maxValue] + + var result = 0 + for (i in 1..m) { + if (i > maxValue) { + result = (result + solve(idx + 1, searchCost + 1, i)) % MOD + } else { + result = (result + solve(idx + 1, searchCost, maxValue)) % MOD + } + } + + dp[idx][searchCost][maxValue] = result + return result + } +} diff --git a/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.py b/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.py new file mode 100644 index 00000000..fe133527 --- /dev/null +++ b/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.py @@ -0,0 +1,33 @@ +class Solution: + def numOfArrays(self, n: int, m: int, k: int) -> int: + MOD = 10**9 + 7 + # 3D DP table: dp[idx][search_cost][max_value] + dp = [[[-1 for _ in range(m + 1)] for _ in range(k + 1)] for _ in range(n + 1)] + + def solve(idx, search_cost, max_value): + # Base Case: Array is full + if idx == n: + return 1 if search_cost == k else 0 + + # Optimization: If cost already exceeds k, stop + if search_cost > k: + return 0 + + # Return cached result if available + if dp[idx][search_cost][max_value] != -1: + return dp[idx][search_cost][max_value] + + result = 0 + # Try every number from 1 to m for the current position + for i in range(1, m + 1): + if i > max_value: + # New maximum found: increment search_cost and update max_value + result = (result + solve(idx + 1, search_cost + 1, i)) % MOD + else: + # Not a new maximum: search_cost and max_value stay the same + result = (result + solve(idx + 1, search_cost, max_value)) % MOD + + dp[idx][search_cost][max_value] = result + return result + + return solve(0, 0, 0) diff --git a/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.py2 b/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.py2 new file mode 100644 index 00000000..692f2a5d --- /dev/null +++ b/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.py2 @@ -0,0 +1,30 @@ +class Solution(object): + def numOfArrays(self, n, m, k): + """ + :type n: int + :type m: int + :type k: int + :rtype: int + """ + MOD = 10**9 + 7 + dp = [[[-1 for _ in range(m + 1)] for _ in range(k + 1)] for _ in range(n + 1)] + + def solve(idx, search_cost, max_value): + if idx == n: + return 1 if search_cost == k else 0 + if search_cost > k: + return 0 + if dp[idx][search_cost][max_value] != -1: + return dp[idx][search_cost][max_value] + + result = 0 + for i in range(1, m + 1): + if i > max_value: + result = (result + solve(idx + 1, search_cost + 1, i)) % MOD + else: + result = (result + solve(idx + 1, search_cost, max_value)) % MOD + + dp[idx][search_cost][max_value] = result + return result + + return solve(0, 0, 0) diff --git a/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.rb b/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.rb new file mode 100644 index 00000000..f6d86d80 --- /dev/null +++ b/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.rb @@ -0,0 +1,34 @@ +# @param {Integer} n +# @param {Integer} m +# @param {Integer} k +# @return {Integer} +def num_of_arrays(n, m, k) + mod = 10**9 + 7 + dp = Array.new(n + 1) { Array.new(k + 1) { Array.new(m + 1, -1) } } + + solve = lambda do |idx, search_cost, max_value| + if idx == n + return search_cost == k ? 1 : 0 + end + if search_cost > k + return 0 + end + if dp[idx][search_cost][max_value] != -1 + return dp[idx][search_cost][max_value] + end + + result = 0 + (1..m).each do |i| + if i > max_value + result = (result + solve.call(idx + 1, search_cost + 1, i)) % mod + else + result = (result + solve.call(idx + 1, search_cost, max_value)) % mod + end + end + + dp[idx][search_cost][max_value] = result + result + end + + solve.call(0, 0, 0) +end diff --git a/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.rs b/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.rs new file mode 100644 index 00000000..dfd9be21 --- /dev/null +++ b/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.rs @@ -0,0 +1,35 @@ +impl Solution { + pub fn num_of_arrays(n: i32, m: i32, k: i32) -> i32 { + const MOD: i32 = 1_000_000_007; + let n = n as usize; + let m = m as usize; + let k = k as usize; + let mut dp = vec![vec![vec![-1; m + 1]; k + 1]; n + 1]; + + fn solve(idx: usize, search_cost: usize, max_value: usize, n: usize, m: usize, k: usize, dp: &mut Vec>>, modulo: i32) -> i32 { + if idx == n { + return if search_cost == k { 1 } else { 0 }; + } + if search_cost > k { + return 0; + } + if dp[idx][search_cost][max_value] != -1 { + return dp[idx][search_cost][max_value]; + } + + let mut result = 0; + for i in 1..=m { + if i > max_value { + result = (result + solve(idx + 1, search_cost + 1, i, n, m, k, dp, modulo)) % modulo; + } else { + result = (result + solve(idx + 1, search_cost, max_value, n, m, k, dp, modulo)) % modulo; + } + } + + dp[idx][search_cost][max_value] = result; + result + } + + solve(0, 0, 0, n, m, k, &mut dp, MOD) + } +} diff --git a/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.swift b/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.swift new file mode 100644 index 00000000..4005e91b --- /dev/null +++ b/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.swift @@ -0,0 +1,39 @@ +class Solution { + private let MOD = 1_000_000_007 + private var dp: [[[Int]]] = [] + private var n = 0 + private var m = 0 + private var k = 0 + + func numOfArrays(_ n: Int, _ m: Int, _ k: Int) -> Int { + self.n = n + self.m = m + self.k = k + dp = Array(repeating: Array(repeating: Array(repeating: -1, count: m + 1), count: k + 1), count: n + 1) + return solve(0, 0, 0) + } + + private func solve(_ idx: Int, _ searchCost: Int, _ maxValue: Int) -> Int { + if idx == n { + return searchCost == k ? 1 : 0 + } + if searchCost > k { + return 0 + } + if dp[idx][searchCost][maxValue] != -1 { + return dp[idx][searchCost][maxValue] + } + + var result = 0 + for i in 1...m { + if i > maxValue { + result = (result + solve(idx + 1, searchCost + 1, i)) % MOD + } else { + result = (result + solve(idx + 1, searchCost, maxValue)) % MOD + } + } + + dp[idx][searchCost][maxValue] = result + return result + } +} diff --git a/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.ts b/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.ts new file mode 100644 index 00000000..02a9e7fd --- /dev/null +++ b/tests/1001-1500/1420. build-array-where-you-can-find-the-maximum-exactly-k-comparisons/sol.ts @@ -0,0 +1,27 @@ +function numOfArrays(n: number, m: number, k: number): number { + const MOD = 1_000_000_007; + const dp: number[][][] = Array.from({ length: n + 1 }, () => + Array.from({ length: k + 1 }, () => Array(m + 1).fill(-1)), + ); + + function solve(idx: number, searchCost: number, maxValue: number): number { + if (idx === n) return searchCost === k ? 1 : 0; + if (searchCost > k) return 0; + if (dp[idx][searchCost][maxValue] !== -1) + return dp[idx][searchCost][maxValue]; + + let result = 0; + for (let i = 1; i <= m; i++) { + if (i > maxValue) { + result = (result + solve(idx + 1, searchCost + 1, i)) % MOD; + } else { + result = (result + solve(idx + 1, searchCost, maxValue)) % MOD; + } + } + + dp[idx][searchCost][maxValue] = result; + return result; + } + + return solve(0, 0, 0); +} diff --git a/tests/1001-1500/1422. maximum-score-after-splitting-a-string/manifest.yaml b/tests/1001-1500/1422. maximum-score-after-splitting-a-string/manifest.yaml new file mode 100644 index 00000000..862e606d --- /dev/null +++ b/tests/1001-1500/1422. maximum-score-after-splitting-a-string/manifest.yaml @@ -0,0 +1,181 @@ +entry: + id: 1422 + title: maximum-score-after-splitting-a-string + params: + s: + type: string + call: + cpp: "Solution().maxScore({s})" + rust: "Solution::max_score({s})" + python3: "Solution().maxScore({s})" + python2: "Solution().maxScore({s})" + ruby: "max_score({s})" + java: "new Solution().maxScore({s})" + csharp: "new Solution().MaxScore({s})" + kotlin: "Solution().maxScore({s})" + go: "maxScore({s})" + dart: "Solution().maxScore({s})" + swift: "Solution().maxScore({s})" + typescript: "maxScore({s})" +judge: + type: "exact" +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().maxScore(s, {result})" + checker: | + class Checker: + def maxScore(self, s, result): + if type(result) is not int: + return False + best = 0 + for split in range(1, len(s)): + score = 0 + for char in s[:split]: + score += char == '0' + for char in s[split:]: + score += char == '1' + best = max(best, score) + return result == best +seed: 1422 +tests: + - name: example-one + in: + s: "011101" + out: 5 + - name: example-two + in: + s: "00111" + out: 5 + - name: example-three + in: + s: "1111" + out: 3 + - name: minimum-zero-zero + in: + s: "00" + - name: minimum-zero-one + in: + s: "01" + - name: minimum-one-zero + in: + s: "10" + - name: minimum-one-one + in: + s: "11" + - name: all-zero-short + in: + s: "00000" + - name: all-one-short + in: + s: "11111" + - name: all-zero-limit + in: + s: "00000000000000000000000000000000000000000000000000" + - name: all-one-limit + in: + s: "11111111111111111111111111111111111111111111111111" + - name: alternating-start-zero + in: + s: "010101" + - name: alternating-start-one + in: + s: "101010" + - name: alternating-even-long + in: + s: "0101010101010101" + - name: alternating-odd-long + in: + s: "101010101010101" + - name: zero-block-then-one-block + in: + s: "0000111111" + - name: one-block-then-zero-block + in: + s: "1111110000" + - name: zero-prefix-single-one + in: + s: "00000001" + - name: one-prefix-single-zero + in: + s: "11111110" + - name: single-zero-middle + in: + s: "11101111" + - name: single-one-middle + in: + s: "00010000" + - name: zero-split-optimum-early + in: + s: "01111111" + - name: zero-split-optimum-late + in: + s: "00000010" + - name: repeated-triple + in: + s: "0010010010" + - name: repeated-pair + in: + s: "1100110011" + - name: three-runs + in: + s: "0011100111" + - name: four-runs + in: + s: "111000111000" + - name: balanced-mixed + in: + s: "01001101" + - name: dense-mixed + in: + s: "10111000101" + - name: boundary-change-at-start + in: + s: "0110" + - name: boundary-change-at-end + in: + s: "1001" + - name: long-zero-prefix + in: + s: "00000000000000001111" + - name: long-one-prefix + in: + s: "11111111111111110000" + - name: mixed-twenty + in: + s: "00111010101110001011" + - name: explicit-limit-mixed + in: + s: "0100111010011101010011101001110101001110100111010100111010011101" + - name: generated-balanced + in: + s: + gen: "str" + len: 500 + alphabet: "01" + - name: generated-all-zero + in: + s: + gen: "str" + len: 500 + alphabet: "0" + - name: generated-all-one + in: + s: + gen: "str" + len: 500 + alphabet: "1" + - name: generated-zero-heavy + in: + s: + gen: "str" + len: 500 + alphabet: "0001" + - name: generated-one-heavy + in: + s: + gen: "str" + len: 500 + alphabet: "0111" diff --git a/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.cpp b/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.cpp new file mode 100644 index 00000000..9f07ccf0 --- /dev/null +++ b/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int maxScore(string s) { + int totalOnes = 0; + for (char c : s) { + if (c == '1') totalOnes++; + } + + int zerosCount = 0; + int onesCount = 0; + int bestScore = INT_MIN; + + for (int i = 0; i < s.length() - 1; i++) { + if (s[i] == '0') { + zerosCount++; + } else { + onesCount++; + } + + int currentScore = zerosCount + (totalOnes - onesCount); + bestScore = max(bestScore, currentScore); + } + + return bestScore; + } +}; diff --git a/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.cs b/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.cs new file mode 100644 index 00000000..56333b22 --- /dev/null +++ b/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.cs @@ -0,0 +1,25 @@ +public class Solution { + public int MaxScore(string s) { + int totalOnes = 0; + foreach (char c in s) { + if (c == '1') totalOnes++; + } + + int zerosCount = 0; + int onesCount = 0; + int bestScore = int.MinValue; + + for (int i = 0; i < s.Length - 1; i++) { + if (s[i] == '0') { + zerosCount++; + } else { + onesCount++; + } + + int currentScore = zerosCount + (totalOnes - onesCount); + bestScore = Math.Max(bestScore, currentScore); + } + + return bestScore; + } +} diff --git a/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.dart b/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.dart new file mode 100644 index 00000000..6bf200ac --- /dev/null +++ b/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.dart @@ -0,0 +1,23 @@ +class Solution { + int maxScore(String s) { + int totalOnes = s.split('').where((c) => c == '1').length; + int zerosCount = 0; + int onesCount = 0; + int bestScore = -9223372036854775808; // minimum int + + for (int i = 0; i < s.length - 1; i++) { + if (s[i] == '0') { + zerosCount++; + } else { + onesCount++; + } + + int currentScore = zerosCount + (totalOnes - onesCount); + if (currentScore > bestScore) { + bestScore = currentScore; + } + } + + return bestScore; + } +} diff --git a/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.go b/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.go new file mode 100644 index 00000000..b215769e --- /dev/null +++ b/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.go @@ -0,0 +1,27 @@ +func maxScore(s string) int { + totalOnes := 0 + for _, c := range s { + if c == '1' { + totalOnes++ + } + } + + zerosCount := 0 + onesCount := 0 + bestScore := -1 << 31 // minimum int + + for i := 0; i < len(s)-1; i++ { + if s[i] == '0' { + zerosCount++ + } else { + onesCount++ + } + + currentScore := zerosCount + (totalOnes - onesCount) + if currentScore > bestScore { + bestScore = currentScore + } + } + + return bestScore +} diff --git a/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.java b/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.java new file mode 100644 index 00000000..2fe05d73 --- /dev/null +++ b/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.java @@ -0,0 +1,25 @@ +class Solution { + public int maxScore(String s) { + int totalOnes = 0; + for (char c : s.toCharArray()) { + if (c == '1') totalOnes++; + } + + int zerosCount = 0; + int onesCount = 0; + int bestScore = Integer.MIN_VALUE; + + for (int i = 0; i < s.length() - 1; i++) { + if (s.charAt(i) == '0') { + zerosCount++; + } else { + onesCount++; + } + + int currentScore = zerosCount + (totalOnes - onesCount); + bestScore = Math.max(bestScore, currentScore); + } + + return bestScore; + } +} diff --git a/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.kt b/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.kt new file mode 100644 index 00000000..e682d195 --- /dev/null +++ b/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.kt @@ -0,0 +1,21 @@ +class Solution { + fun maxScore(s: String): Int { + val totalOnes = s.count { it == '1' } + var zerosCount = 0 + var onesCount = 0 + var bestScore = Int.MIN_VALUE + + for (i in 0 until s.length - 1) { + if (s[i] == '0') { + zerosCount++ + } else { + onesCount++ + } + + val currentScore = zerosCount + (totalOnes - onesCount) + bestScore = maxOf(bestScore, currentScore) + } + + return bestScore + } +} diff --git a/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.py b/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.py new file mode 100644 index 00000000..e46a305e --- /dev/null +++ b/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.py @@ -0,0 +1,19 @@ +class Solution(object): + def maxScore(self, s): + totalOnes = s.count("1") # Count total ones + zerosCount = 0 + onesCount = 0 + bestScore = float("-inf") + + # Traverse the string and calculate scores + for i in range(len(s) - 1): # Stop before the last character + if s[i] == "0": + zerosCount += 1 + else: + onesCount += 1 + + # Calculate score + currentScore = zerosCount + (totalOnes - onesCount) + bestScore = max(bestScore, currentScore) + + return bestScore diff --git a/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.py2 b/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.py2 new file mode 100644 index 00000000..43744f71 --- /dev/null +++ b/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.py2 @@ -0,0 +1,19 @@ +class Solution(object): + def maxScore(self, s): + totalOnes = s.count('1') # Count total ones + zerosCount = 0 + onesCount = 0 + bestScore = float('-inf') + + # Traverse the string and calculate scores + for i in range(len(s) - 1): # Stop before the last character + if s[i] == '0': + zerosCount += 1 + else: + onesCount += 1 + + # Calculate score + currentScore = zerosCount + (totalOnes - onesCount) + bestScore = max(bestScore, currentScore) + + return bestScore diff --git a/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.rb b/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.rb new file mode 100644 index 00000000..b64af727 --- /dev/null +++ b/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.rb @@ -0,0 +1,21 @@ +# @param {String} s +# @return {Integer} +def max_score(s) + total_ones = s.count('1') + zeros_count = 0 + ones_count = 0 + best_score = -Float::INFINITY + + (0...(s.length - 1)).each do |i| + if s[i] == '0' + zeros_count += 1 + else + ones_count += 1 + end + + current_score = zeros_count + (total_ones - ones_count) + best_score = [best_score, current_score].max + end + + best_score +end diff --git a/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.rs b/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.rs new file mode 100644 index 00000000..2926e9ce --- /dev/null +++ b/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.rs @@ -0,0 +1,22 @@ +impl Solution { + pub fn max_score(s: String) -> i32 { + let total_ones = s.chars().filter(|&c| c == '1').count() as i32; + let mut zeros_count = 0i32; + let mut ones_count = 0i32; + let mut best_score = i32::MIN; + let chars: Vec = s.chars().collect(); + + for i in 0..(chars.len() - 1) { + if chars[i] == '0' { + zeros_count += 1; + } else { + ones_count += 1; + } + + let current_score = zeros_count + (total_ones - ones_count); + best_score = best_score.max(current_score); + } + + best_score + } +} diff --git a/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.swift b/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.swift new file mode 100644 index 00000000..6aedf594 --- /dev/null +++ b/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.swift @@ -0,0 +1,22 @@ +class Solution { + func maxScore(_ s: String) -> Int { + let totalOnes = s.filter { $0 == "1" }.count + var zerosCount = 0 + var onesCount = 0 + var bestScore = Int.min + let chars = Array(s) + + for i in 0..<(chars.count - 1) { + if chars[i] == "0" { + zerosCount += 1 + } else { + onesCount += 1 + } + + let currentScore = zerosCount + (totalOnes - onesCount) + bestScore = max(bestScore, currentScore) + } + + return bestScore + } +} diff --git a/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.ts b/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.ts new file mode 100644 index 00000000..ce0a6a1c --- /dev/null +++ b/tests/1001-1500/1422. maximum-score-after-splitting-a-string/sol.ts @@ -0,0 +1,23 @@ +function maxScore(s: string): number { + let totalOnes = 0; + for (const c of s) { + if (c === "1") totalOnes++; + } + + let zerosCount = 0; + let onesCount = 0; + let bestScore = -Infinity; + + for (let i = 0; i < s.length - 1; i++) { + if (s[i] === "0") { + zerosCount++; + } else { + onesCount++; + } + + const currentScore = zerosCount + (totalOnes - onesCount); + bestScore = Math.max(bestScore, currentScore); + } + + return bestScore; +} diff --git a/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/manifest.yaml b/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/manifest.yaml new file mode 100644 index 00000000..45e0fb53 --- /dev/null +++ b/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/manifest.yaml @@ -0,0 +1,250 @@ +entry: + id: 1423 + title: "maximum-points-you-can-obtain-from-cards" + params: + cardPoints: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().maxScore({cardPoints}, {k})" + rust: "Solution::max_score({cardPoints}, {k})" + python3: "Solution().maxScore({cardPoints}, {k})" + python2: "Solution().maxScore({cardPoints}, {k})" + ruby: "max_score({cardPoints}, {k})" + java: "new Solution().maxScore({cardPoints}, {k})" + csharp: "new Solution().MaxScore({cardPoints}, {k})" + kotlin: "Solution().maxScore({cardPoints}, {k})" + go: "maxScore({cardPoints}, {k})" + dart: "Solution().maxScore({cardPoints}, {k})" + swift: "Solution().maxScore({cardPoints}, {k})" + typescript: "maxScore({cardPoints}, {k})" +judge: + type: exact +limits: + time_ms: 500 + memory_mb: 300 +oracle: + python3: + call: "Checker().maxScore(cardPoints, k, {result})" + checker: | + class Checker: + def maxScore(self, cards, k, result): + if not isinstance(cards, list) or not isinstance(k, int): + return False + if not cards or not (1 <= k <= len(cards)): + return False + if any(not isinstance(x, int) or isinstance(x, bool) or x < 1 or x > 10000 for x in cards): + return False + if not isinstance(result, int) or isinstance(result, bool): + return False + prefix = [0] + for value in cards: + prefix.append(prefix[-1] + value) + n = len(cards) + best = 0 + for left_count in range(k + 1): + right_count = k - left_count + left_sum = prefix[left_count] + right_start = n - right_count + right_sum = prefix[n] - prefix[right_start] + best = max(best, left_sum + right_sum) + return result == best +seed: 1423 +tests: + - name: ex1 + in: + cardPoints: [1, 2, 3, 4, 5, 6, 1] + k: 3 + out: 12 + - name: ex2 + in: + cardPoints: [2, 2, 2] + k: 2 + out: 4 + - name: ex3 + in: + cardPoints: [9, 7, 7, 9, 7, 7, 9] + k: 7 + out: 55 + - name: one + in: + cardPoints: [5] + k: 1 + out: 5 + - name: take_all + in: + cardPoints: [1, 3, 5, 7] + k: 4 + - name: take_left + in: + cardPoints: [10, 1, 1, 1] + k: 1 + out: 10 + - name: take_right + in: + cardPoints: [1, 1, 1, 10] + k: 1 + out: 10 + - name: equal + in: + cardPoints: [4, 4, 4, 4, 4] + k: 3 + - name: alternating + in: + cardPoints: [1, 100, 1, 100, 1, 100] + k: 3 + - name: increasing + in: + cardPoints: [1, 2, 3, 4, 5, 6] + k: 2 + - name: decreasing + in: + cardPoints: [6, 5, 4, 3, 2, 1] + k: 2 + - name: k_one + in: + cardPoints: [7, 2, 9, 1, 8] + k: 1 + - name: k_two + in: + cardPoints: [7, 2, 9, 1, 8] + k: 2 + - name: k_four + in: + cardPoints: [7, 2, 9, 1, 8] + k: 4 + - name: zeros_not_allowed + in: + cardPoints: [1, 2, 1, 2, 1] + k: 3 + - name: high_values + in: + cardPoints: [10000, 9999, 9998] + k: 2 + - name: low_values + in: + cardPoints: [1, 1, 1, 1, 1, 1] + k: 4 + - name: mixed_a + in: + cardPoints: [8, 1, 9, 2, 7, 3] + k: 3 + - name: mixed_b + in: + cardPoints: [5, 10, 2, 8, 1, 9] + k: 2 + - name: mixed_c + in: + cardPoints: [4, 4, 10, 1, 1, 10] + k: 4 + - name: mixed_d + in: + cardPoints: [2, 20, 3, 19, 4, 18] + k: 3 + - name: mixed_e + in: + cardPoints: [11, 2, 13, 4, 15, 6, 17] + k: 5 + - name: seven_cards + in: + cardPoints: [3, 8, 2, 9, 4, 7, 1] + k: 4 + - name: eight_cards + in: + cardPoints: [10, 1, 10, 1, 10, 1, 10, 1] + k: 5 + - name: nine_cards + in: + cardPoints: [1, 2, 3, 4, 5, 6, 7, 8, 9] + k: 6 + - name: ten_cards + in: + cardPoints: [9, 1, 8, 2, 7, 3, 6, 4, 5, 10] + k: 5 + - name: eleven_cards + in: + cardPoints: [5, 5, 5, 1, 1, 1, 9, 9, 9, 2, 2] + k: 7 + - name: twelve_cards + in: + cardPoints: [12, 1, 11, 2, 10, 3, 9, 4, 8, 5, 7, 6] + k: 6 + - name: large_uniform + in: + cardPoints: [100, 100, 100, 100, 100, 100, 100, 100] + k: 3 + - name: large_edges + in: + cardPoints: [1000, 1, 1, 1, 1, 1, 1000] + k: 2 + - name: boundary_max + in: + cardPoints: [10000, 10000, 10000, 10000, 10000] + k: 5 + - name: boundary_min + in: + cardPoints: [1, 2] + k: 1 + - name: patterned_a + in: + cardPoints: [6, 4, 2, 8, 10, 1, 3, 5] + k: 4 + - name: patterned_b + in: + cardPoints: [13, 1, 12, 2, 11, 3, 10, 4, 9] + k: 5 + - name: patterned_c + in: + cardPoints: [20, 1, 19, 2, 18, 3, 17, 4, 16, 5] + k: 7 + - name: final_case + in: + cardPoints: [14, 7, 21, 3, 18, 5, 12] + k: 3 + - name: generated_small_boundary + in: + cardPoints: + gen: "array" + len: 17 + of: + gen: "int" + min: 1 + max: 10000 + elemType: "int" + k: 9 + - name: generated_medium_window + in: + cardPoints: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 10000 + elemType: "int" + k: 1 + - name: generated_max_take_all + in: + cardPoints: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 10000 + elemType: "int" + k: 100000 + - name: generated_max_small_take + in: + cardPoints: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 10000 + elemType: "int" + k: 50000 diff --git a/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.cpp b/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.cpp new file mode 100644 index 00000000..8a6a3adb --- /dev/null +++ b/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int maxScore(vector& cardPoints, int k) { + int l = 0; + int n = cardPoints.size(); + int total = 0; + for (int i = n - k; i < n; i++) { + total += cardPoints[i]; + } + int res = total; + for (int r = n - k; r < n; r++) { + total += cardPoints[l] - cardPoints[r]; + res = max(res, total); + l++; + } + return res; + } +}; diff --git a/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.cs b/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.cs new file mode 100644 index 00000000..ff4bf2d2 --- /dev/null +++ b/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.cs @@ -0,0 +1,14 @@ +public class Solution { + public int MaxScore(int[] cardPoints, int k) { + int l = 0; + int n = cardPoints.Length; + int total = cardPoints[(n - k)..].Sum(); + int res = total; + for (int r = n - k; r < n; r++) { + total += cardPoints[l] - cardPoints[r]; + res = Math.Max(res, total); + l++; + } + return res; + } +} diff --git a/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.dart b/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.dart new file mode 100644 index 00000000..24d90631 --- /dev/null +++ b/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.dart @@ -0,0 +1,14 @@ +class Solution { + int maxScore(List cardPoints, int k) { + int l = 0; + int n = cardPoints.length; + int total = cardPoints.sublist(n - k).fold(0, (a, b) => a + b); + int res = total; + for (int r = n - k; r < n; r++) { + total += cardPoints[l] - cardPoints[r]; + if (total > res) res = total; + l++; + } + return res; + } +} diff --git a/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.go b/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.go new file mode 100644 index 00000000..1c3b8649 --- /dev/null +++ b/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.go @@ -0,0 +1,17 @@ +func maxScore(cardPoints []int, k int) int { + l := 0 + n := len(cardPoints) + total := 0 + for i := n - k; i < n; i++ { + total += cardPoints[i] + } + res := total + for r := n - k; r < n; r++ { + total += cardPoints[l] - cardPoints[r] + if total > res { + res = total + } + l++ + } + return res +} diff --git a/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.java b/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.java new file mode 100644 index 00000000..66b450e7 --- /dev/null +++ b/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.java @@ -0,0 +1,17 @@ +class Solution { + public int maxScore(int[] cardPoints, int k) { + int l = 0; + int total = 0; + int n = cardPoints.length; + for (int i = n - k; i < n; i++) { + total += cardPoints[i]; + } + int res = total; + for (int r = n - k; r < n; r++) { + total += cardPoints[l] - cardPoints[r]; + res = Math.max(res, total); + l++; + } + return res; + } +} diff --git a/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.kt b/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.kt new file mode 100644 index 00000000..a4819371 --- /dev/null +++ b/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.kt @@ -0,0 +1,14 @@ +class Solution { + fun maxScore(cardPoints: IntArray, k: Int): Int { + var l = 0 + val n = cardPoints.size + var total = (n - k until n).sumOf { cardPoints[it] } + var res = total + for (r in n - k until n) { + total += cardPoints[l] - cardPoints[r] + res = maxOf(res, total) + l++ + } + return res + } +} diff --git a/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.py b/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.py new file mode 100644 index 00000000..3fc7ede1 --- /dev/null +++ b/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.py @@ -0,0 +1,10 @@ +class Solution(object): + def maxScore(self, cp, k): + l = 0 + total = sum(cp[len(cp) - k :]) + res = total + for r in range(len(cp) - k, len(cp)): + total += cp[l] - cp[r] + res = max(res, total) + l += 1 + return res diff --git a/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.py2 b/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.py2 new file mode 100644 index 00000000..1bfebe73 --- /dev/null +++ b/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.py2 @@ -0,0 +1,10 @@ +class Solution(object): + def maxScore(self, cp, k): + l = 0 + total = sum(cp[len(cp)-k:]) + res = total + for r in range(len(cp) - k, len(cp)): + total += cp[l] - cp[r] + res = max(res, total) + l += 1 + return res diff --git a/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.rb b/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.rb new file mode 100644 index 00000000..84abe299 --- /dev/null +++ b/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.rb @@ -0,0 +1,14 @@ +# @param {Integer[]} card_points +# @param {Integer} k +# @return {Integer} +def max_score(card_points, k) + l = 0 + total = card_points[card_points.length - k..-1].sum + res = total + (card_points.length - k...card_points.length).each do |r| + total += card_points[l] - card_points[r] + res = [res, total].max + l += 1 + end + res +end diff --git a/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.rs b/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.rs new file mode 100644 index 00000000..ab998047 --- /dev/null +++ b/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn max_score(card_points: Vec, k: i32) -> i32 { + let k = k as usize; + let n = card_points.len(); + let mut l = 0; + let mut total: i32 = card_points[n - k..].iter().sum(); + let mut res = total; + for r in n - k..n { + total += card_points[l] - card_points[r]; + res = res.max(total); + l += 1; + } + res + } +} diff --git a/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.swift b/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.swift new file mode 100644 index 00000000..67896b58 --- /dev/null +++ b/tests/1001-1500/1423. maximum-points-you-can-obtain-from-cards/sol.swift @@ -0,0 +1,14 @@ +class Solution { + func maxScore(_ cardPoints: [Int], _ k: Int) -> Int { + var l = 0 + let n = cardPoints.count + var total = cardPoints[(n - k)...].reduce(0, +) + var res = total + for r in (n - k).. a + b, 0); + let res = total; + for (let r = n - k; r < n; r++) { + total += cardPoints[l] - cardPoints[r]; + res = Math.max(res, total); + l++; + } + return res; +} diff --git a/tests/1001-1500/1424. diagonal-traverse-ii/manifest.yaml b/tests/1001-1500/1424. diagonal-traverse-ii/manifest.yaml new file mode 100644 index 00000000..4f4e0fdb --- /dev/null +++ b/tests/1001-1500/1424. diagonal-traverse-ii/manifest.yaml @@ -0,0 +1,340 @@ +entry: + id: 1424 + title: "diagonal-traverse-ii" + params: + nums: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().findDiagonalOrder({nums})" + rust: "Solution::find_diagonal_order({nums})" + python3: "Solution().findDiagonalOrder({nums})" + python2: "Solution().findDiagonalOrder({nums})" + ruby: "find_diagonal_order({nums})" + java: "new Solution().findDiagonalOrder({nums})" + csharp: "new Solution().FindDiagonalOrder({nums})" + kotlin: "Solution().findDiagonalOrder({nums})" + go: "findDiagonalOrder({nums})" + dart: "Solution().findDiagonalOrder({nums})" + swift: "Solution().findDiagonalOrder({nums})" + typescript: "findDiagonalOrder({nums})" +judge: + type: "exact" +limits: + time_ms: 700 + memory_mb: 300 +oracle: + python3: + call: "Checker().findDiagonalOrder(nums, {result})" + checker: | + class Checker: + def findDiagonalOrder(self, nums, result): + groups = {} + for row_index, row in enumerate(nums): + for column_index, value in enumerate(row): + groups.setdefault(row_index + column_index, []).append((row_index, value)) + expected = [] + for diagonal in sorted(groups): + expected.extend(value for _, value in reversed(groups[diagonal])) + return result == expected +seed: 1424 +tests: + - name: "official-square" + in: + nums: + elemType: "int" + value: + - [1, 2, 3] + - [4, 5, 6] + - [7, 8, 9] + out: [1, 4, 2, 7, 5, 3, 8, 6, 9] + - name: "official-ragged" + in: + nums: + elemType: "int" + value: + - [1, 2, 3, 4, 5] + - [6, 7] + - [8] + - [9, 10, 11] + - [12, 13, 14, 15, 16] + out: [1, 6, 2, 8, 7, 3, 9, 4, 12, 10, 5, 13, 11, 14, 15, 16] + - name: "single-cell" + in: + nums: + elemType: "int" + value: + - [42] + - name: "two-by-two" + in: + nums: + elemType: "int" + value: + - [1, 2] + - [3, 4] + - name: "wide-rectangle" + in: + nums: + elemType: "int" + value: + - [1, 2, 3, 4, 5] + - [6, 7, 8, 9, 10] + - name: "tall-rectangle" + in: + nums: + elemType: "int" + value: + - [1, 2] + - [3, 4] + - [5, 6] + - [7, 8] + - [9, 10] + - name: "increasing-triangle" + in: + nums: + elemType: "int" + value: + - [1] + - [2, 3] + - [4, 5, 6] + - [7, 8, 9, 10] + - name: "decreasing-triangle" + in: + nums: + elemType: "int" + value: + - [1, 2, 3, 4] + - [5, 6, 7] + - [8, 9] + - [10] + - name: "front-loaded" + in: + nums: + elemType: "int" + value: + - [10, 20, 30, 40, 50, 60] + - [70] + - [80] + - [90] + - name: "back-loaded" + in: + nums: + elemType: "int" + value: + - [1] + - [2] + - [3] + - [4, 5, 6, 7, 8] + - name: "alternating-lengths" + in: + nums: + elemType: "int" + value: + - [1, 2, 3] + - [4] + - [5, 6, 7, 8] + - [9] + - [10, 11] + - name: "duplicate-values" + in: + nums: + elemType: "int" + value: + - [5, 5, 5] + - [5, 5] + - [5] + - name: "large-values" + in: + nums: + elemType: "int" + value: + - [100000, 99999] + - [99998, 99997, 99996] + - name: "sparse-diagonal-one" + in: + nums: + elemType: "int" + value: + - [11, 12, 13, 14] + - [21, 22] + - [31, 32, 33] + - name: "sparse-diagonal-two" + in: + nums: + elemType: "int" + value: + - [2] + - [4, 6, 8, 10] + - [12, 14] + - [16, 18, 20] + - name: "rows-length-one-and-four" + in: + nums: + elemType: "int" + value: + - [1, 2, 3, 4] + - [5] + - [6, 7, 8, 9] + - [10] + - name: "nonmonotonic-values" + in: + nums: + elemType: "int" + value: + - [9, 1, 8] + - [2, 7, 3, 6] + - [5, 4] + - name: "zero-not-allowed-replaced" + in: + nums: + elemType: "int" + value: + - [1, 100] + - [99, 2] + - name: "long-first-row" + in: + nums: + elemType: "int" + value: + - [1, 2, 3, 4, 5, 6, 7, 8] + - [9, 10] + - name: "long-last-row" + in: + nums: + elemType: "int" + value: + - [1] + - [2, 3] + - [4, 5, 6, 7, 8, 9, 10] + - name: "four-by-three" + in: + nums: + elemType: "int" + value: + - [1, 2, 3] + - [4, 5, 6] + - [7, 8, 9] + - [10, 11, 12] + - name: "four-by-four" + in: + nums: + elemType: "int" + value: + - [16, 15, 14, 13] + - [12, 11, 10, 9] + - [8, 7, 6, 5] + - [4, 3, 2, 1] + - name: "prime-values" + in: + nums: + elemType: "int" + value: + - [2, 3, 5] + - [7, 11] + - [13, 17, 19, 23] + - name: "powers-of-two" + in: + nums: + elemType: "int" + value: + - [1, 2, 4, 8] + - [16, 32] + - [64, 128, 256] + - name: "two-long-rows" + in: + nums: + elemType: "int" + value: + - [1, 2, 3, 4, 5, 6, 7] + - [8, 9, 10, 11, 12, 13, 14] + - name: "three-uneven-rows" + in: + nums: + elemType: "int" + value: + - [20, 19] + - [18, 17, 16, 15, 14] + - [13, 12, 11] + - name: "near-limit-values" + in: + nums: + elemType: "int" + value: + - [99991, 99992, 99993] + - [99994] + - [99995, 99996] + - name: "five-irregular-rows" + in: + nums: + elemType: "int" + value: + - [31, 32] + - [41, 42, 43] + - [51] + - [61, 62, 63, 64] + - [71, 72] + - name: "repeated-patterns" + in: + nums: + elemType: "int" + value: + - [1, 2, 1, 2] + - [2, 1, 2] + - [1, 2] + - name: "descending-rows" + in: + nums: + elemType: "int" + value: + - [9, 8, 7, 6] + - [5, 4] + - [3, 2, 1] + - name: "six-row-ragged" + in: + nums: + elemType: "int" + value: + - [1, 2] + - [3, 4, 5] + - [6] + - [7, 8, 9, 10] + - [11, 12] + - [13, 14, 15] + - name: "mixed-small-values" + in: + nums: + elemType: "int" + value: + - [1, 7, 2] + - [6, 3, 5, 4] + - [8, 9] + - name: "last-diagonal-long" + in: + nums: + elemType: "int" + value: + - [1, 2, 3, 4, 5] + - [6, 7, 8] + - [9, 10, 11, 12] + - name: "all-equal-rows" + in: + nums: + elemType: "int" + value: + - [10, 10] + - [20, 20] + - [30, 30] + - [40, 40] + - name: "alternating-extreme-ragged" + in: + nums: + elemType: "int" + value: + - [1, 100000, 2] + - [99999] + - [3, 99998, 4, 99997] + - [5] + - [99996, 6] diff --git a/tests/1001-1500/1424. diagonal-traverse-ii/sol.cpp b/tests/1001-1500/1424. diagonal-traverse-ii/sol.cpp new file mode 100644 index 00000000..f3310d0c --- /dev/null +++ b/tests/1001-1500/1424. diagonal-traverse-ii/sol.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + vector findDiagonalOrder(vector>& nums) { + vector> l; + for (int i = 0; i < nums.size(); i++) { + for (int j = 0; j < nums[i].size(); j++) { + l.push_back({i + j, i, j}); + } + } + + map> h; + for (auto& triple : l) { + int sum = triple[0], i = triple[1], j = triple[2]; + h[sum].push_back(nums[i][j]); + } + + vector result; + for (auto& [key, diag] : h) { + for (int k = diag.size() - 1; k >= 0; k--) { + result.push_back(diag[k]); + } + } + return result; + } +}; diff --git a/tests/1001-1500/1424. diagonal-traverse-ii/sol.cs b/tests/1001-1500/1424. diagonal-traverse-ii/sol.cs new file mode 100644 index 00000000..785e4423 --- /dev/null +++ b/tests/1001-1500/1424. diagonal-traverse-ii/sol.cs @@ -0,0 +1,26 @@ +public class Solution { + public int[] FindDiagonalOrder(IList> nums) { + List l = new List(); + for (int i = 0; i < nums.Count; i++) { + for (int j = 0; j < nums[i].Count; j++) { + l.Add(new int[]{i + j, i, j}); + } + } + + SortedDictionary> h = new SortedDictionary>(); + foreach (var triple in l) { + int sum = triple[0], i = triple[1], j = triple[2]; + if (!h.ContainsKey(sum)) h[sum] = new List(); + h[sum].Add(nums[i][j]); + } + + List result = new List(); + foreach (var kvp in h) { + var diag = kvp.Value; + for (int k = diag.Count - 1; k >= 0; k--) { + result.Add(diag[k]); + } + } + return result.ToArray(); + } +} diff --git a/tests/1001-1500/1424. diagonal-traverse-ii/sol.dart b/tests/1001-1500/1424. diagonal-traverse-ii/sol.dart new file mode 100644 index 00000000..823e467b --- /dev/null +++ b/tests/1001-1500/1424. diagonal-traverse-ii/sol.dart @@ -0,0 +1,24 @@ +class Solution { + List findDiagonalOrder(List> nums) { + List> l = []; + for (int i = 0; i < nums.length; i++) { + for (int j = 0; j < nums[i].length; j++) { + l.add([i + j, i, j]); + } + } + + Map> h = {}; + for (var triple in l) { + int sum = triple[0], i = triple[1], j = triple[2]; + h.putIfAbsent(sum, () => []); + h[sum]!.add(nums[i][j]); + } + + List keys = h.keys.toList()..sort(); + List result = []; + for (int key in keys) { + result.addAll(h[key]!.reversed); + } + return result; + } +} diff --git a/tests/1001-1500/1424. diagonal-traverse-ii/sol.go b/tests/1001-1500/1424. diagonal-traverse-ii/sol.go new file mode 100644 index 00000000..1630eaf5 --- /dev/null +++ b/tests/1001-1500/1424. diagonal-traverse-ii/sol.go @@ -0,0 +1,29 @@ +func findDiagonalOrder(nums [][]int) []int { + l := [][]int{} + for i, row := range nums { + for j := range row { + l = append(l, []int{i + j, i, j}) + } + } + + h := map[int][]int{} + for _, triple := range l { + sum, i, j := triple[0], triple[1], triple[2] + h[sum] = append(h[sum], nums[i][j]) + } + + keys := []int{} + for k := range h { + keys = append(keys, k) + } + sort.Ints(keys) + + result := []int{} + for _, k := range keys { + diag := h[k] + for i := len(diag) - 1; i >= 0; i-- { + result = append(result, diag[i]) + } + } + return result +} diff --git a/tests/1001-1500/1424. diagonal-traverse-ii/sol.java b/tests/1001-1500/1424. diagonal-traverse-ii/sol.java new file mode 100644 index 00000000..44e21058 --- /dev/null +++ b/tests/1001-1500/1424. diagonal-traverse-ii/sol.java @@ -0,0 +1,47 @@ +class Solution { + public int[] findDiagonalOrder(int[][] nums) { + List> rows = new ArrayList<>(); + for (int[] row : nums) { + List values = new ArrayList<>(row.length); + for (int value : row) { + values.add(value); + } + rows.add(values); + } + return findDiagonalOrder(rows); + } + + public int[] findDiagonalOrder(List> nums) { + List l = new ArrayList<>(); + for (int i = 0; i < nums.size(); i++) { + List row = nums.get(i); + for (int j = 0; j < row.size(); j++) { + l.add(new int[]{i + j, i, j}); + } + } + + Map> h = new HashMap<>(); + for (int[] triple : l) { + int key = triple[0]; + int val = nums.get(triple[1]).get(triple[2]); + h.computeIfAbsent(key, k -> new ArrayList<>()).add(val); + } + + List sortedKeys = new ArrayList<>(h.keySet()); + Collections.sort(sortedKeys); + + List resultList = new ArrayList<>(); + for (int key : sortedKeys) { + List diag = h.get(key); + for (int k = diag.size() - 1; k >= 0; k--) { + resultList.add(diag.get(k)); + } + } + + int[] res = new int[resultList.size()]; + for (int i = 0; i < resultList.size(); i++) { + res[i] = resultList.get(i); + } + return res; + } +} diff --git a/tests/1001-1500/1424. diagonal-traverse-ii/sol.kt b/tests/1001-1500/1424. diagonal-traverse-ii/sol.kt new file mode 100644 index 00000000..9c43bd8f --- /dev/null +++ b/tests/1001-1500/1424. diagonal-traverse-ii/sol.kt @@ -0,0 +1,26 @@ +class Solution { + fun findDiagonalOrder(nums: Array): IntArray { + return findDiagonalOrder(nums.map { it.toList() }) + } + + fun findDiagonalOrder(nums: List>): IntArray { + val l = mutableListOf>() + for (i in nums.indices) { + for (j in nums[i].indices) { + l.add(Triple(i + j, i, j)) + } + } + + val h = mutableMapOf>() + for ((sum, i, j) in l) { + h.getOrPut(sum) { mutableListOf() }.add(nums[i][j]) + } + + val sortedKeys = h.keys.sorted() + val result = mutableListOf() + for (key in sortedKeys) { + result.addAll(h[key]!!.reversed()) + } + return result.toIntArray() + } +} diff --git a/tests/1001-1500/1424. diagonal-traverse-ii/sol.py b/tests/1001-1500/1424. diagonal-traverse-ii/sol.py new file mode 100644 index 00000000..a412752b --- /dev/null +++ b/tests/1001-1500/1424. diagonal-traverse-ii/sol.py @@ -0,0 +1,17 @@ +class Solution: + def findDiagonalOrder(self, n): + l = [] + for i in range(len(n)): + for j in range(len(n[i])): + l.append([i + j, i, j]) + + h = {} + for i in l: + if i[0] not in h: + h[i[0]] = [] + h[i[0]].append(n[i[1]][i[2]]) + + heap = [] + for i in sorted(h): + heap.extend(h[i][::-1]) + return heap diff --git a/tests/1001-1500/1424. diagonal-traverse-ii/sol.py2 b/tests/1001-1500/1424. diagonal-traverse-ii/sol.py2 new file mode 100644 index 00000000..e16b2c79 --- /dev/null +++ b/tests/1001-1500/1424. diagonal-traverse-ii/sol.py2 @@ -0,0 +1,17 @@ +class Solution(object): + def findDiagonalOrder(self, n): + l=[] + for i in range(len(n)): + for j in range(len(n[i])): + l.append([i+j,i,j]) + + h={} + for i in l: + if i[0] not in h: + h[i[0]] = [] + h[i[0]].append(n[i[1]][i[2]]) + + heap=[] + for i in sorted(h): + heap.extend(h[i][::-1]) + return heap diff --git a/tests/1001-1500/1424. diagonal-traverse-ii/sol.rb b/tests/1001-1500/1424. diagonal-traverse-ii/sol.rb new file mode 100644 index 00000000..20a4726d --- /dev/null +++ b/tests/1001-1500/1424. diagonal-traverse-ii/sol.rb @@ -0,0 +1,22 @@ +# @param {Integer[][]} nums +# @return {Integer[]} +def find_diagonal_order(nums) + l = [] + nums.each_with_index do |row, i| + row.each_with_index do |val, j| + l << [i + j, i, j] + end + end + + h = {} + l.each do |sum, i, j| + h[sum] ||= [] + h[sum] << nums[i][j] + end + + result = [] + h.keys.sort.each do |key| + result.concat(h[key].reverse) + end + result +end diff --git a/tests/1001-1500/1424. diagonal-traverse-ii/sol.rs b/tests/1001-1500/1424. diagonal-traverse-ii/sol.rs new file mode 100644 index 00000000..92df16d9 --- /dev/null +++ b/tests/1001-1500/1424. diagonal-traverse-ii/sol.rs @@ -0,0 +1,25 @@ +impl Solution { + pub fn find_diagonal_order(nums: Vec>) -> Vec { + use std::collections::BTreeMap; + + let mut l: Vec<(usize, usize, usize)> = Vec::new(); + for i in 0..nums.len() { + for j in 0..nums[i].len() { + l.push((i + j, i, j)); + } + } + + let mut h: BTreeMap> = BTreeMap::new(); + for (sum, i, j) in l { + h.entry(sum).or_default().push(nums[i][j]); + } + + let mut result = Vec::new(); + for (_key, diag) in h.iter() { + for &val in diag.iter().rev() { + result.push(val); + } + } + result + } +} diff --git a/tests/1001-1500/1424. diagonal-traverse-ii/sol.swift b/tests/1001-1500/1424. diagonal-traverse-ii/sol.swift new file mode 100644 index 00000000..8115bc35 --- /dev/null +++ b/tests/1001-1500/1424. diagonal-traverse-ii/sol.swift @@ -0,0 +1,21 @@ +class Solution { + func findDiagonalOrder(_ nums: [[Int]]) -> [Int] { + var l: [(Int, Int, Int)] = [] + for i in 0.. a - b); + for (const key of sortedKeys) { + result.push(...h[key].reverse()); + } + return result; +} diff --git a/tests/1001-1500/1425. constrained-subsequence-sum/manifest.yaml b/tests/1001-1500/1425. constrained-subsequence-sum/manifest.yaml new file mode 100644 index 00000000..cd90c4ff --- /dev/null +++ b/tests/1001-1500/1425. constrained-subsequence-sum/manifest.yaml @@ -0,0 +1,280 @@ +entry: + id: 1425 + title: constrained-subsequence-sum + params: + nums: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().constrainedSubsetSum({nums}, {k})" + rust: "Solution::constrained_subset_sum({nums}, {k})" + python3: "Solution().constrainedSubsetSum({nums}, {k})" + python2: "Solution().constrainedSubsetSum({nums}, {k})" + ruby: "constrained_subset_sum({nums}, {k})" + java: "new Solution().constrainedSubsetSum({nums}, {k})" + csharp: "new Solution().ConstrainedSubsetSum({nums}, {k})" + kotlin: "Solution().constrainedSubsetSum({nums}, {k})" + go: "constrainedSubsetSum({nums}, {k})" + dart: "Solution().constrainedSubsetSum({nums}, {k})" + swift: "Solution().constrainedSubsetSum({nums}, {k})" + typescript: "constrainedSubsetSum({nums}, {k})" + +judge: + type: exact + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().constrainedSubsetSum(nums, k, {result})" + checker: | + class Checker: + def constrainedSubsetSum(self, nums, k, result): + if type(result) is not int or not nums or not (1 <= k <= len(nums)): + return False + n = len(nums) + size = 1 + while size < n: + size <<= 1 + tree = [-10**18] * (2 * size) + answer = -10**18 + for i, value in enumerate(nums): + left = max(0, i - k) + right = i + best = 0 + l = left + size + r = right + size + while l < r: + if l & 1: + best = max(best, tree[l]) + l += 1 + if r & 1: + r -= 1 + best = max(best, tree[r]) + l >>= 1 + r >>= 1 + current = value + max(0, best) + answer = max(answer, current) + p = i + size + tree[p] = current + p >>= 1 + while p: + tree[p] = max(tree[2 * p], tree[2 * p + 1]) + p >>= 1 + return result == answer + +seed: 1425 + +tests: + - name: single_positive + in: + nums: [5] + k: 1 + - name: single_minimum + in: + nums: [-10000] + k: 1 + - name: single_zero + in: + nums: [0] + k: 1 + - name: examples_one + in: + nums: [10, 2, -10, 5, 20] + k: 2 + - name: examples_two + in: + nums: [-1, -2, -3] + k: 1 + - name: examples_three + in: + nums: [10, -2, -10, -5, 20] + k: 2 + - name: all_negative + in: + nums: [-1, -2, -3, -4, -5] + k: 5 + - name: all_positive_k_one + in: + nums: [1, 2, 3, 4, 5] + k: 1 + - name: all_positive_wide + in: + nums: [10000, 9999, 9998, 9997] + k: 4 + - name: skip_harmful_values + in: + nums: [5, -10000, 5] + k: 2 + - name: forced_adjacent + in: + nums: [5, -10000, 6] + k: 1 + - name: bridge_negative + in: + nums: [10, -2, -2, 10] + k: 3 + - name: exact_window_boundary + in: + nums: [8, -100, -100, 8] + k: 3 + - name: beyond_window_boundary + in: + nums: [8, -100, -100, 8] + k: 2 + - name: alternating + in: + nums: [5, -1, 5, -1, 5, -1, 5] + k: 2 + - name: zeros + in: + nums: [0, 0, 0, 0, 0] + k: 2 + - name: zero_and_gain + in: + nums: [5, 0, -5, 10] + k: 2 + - name: duplicate_peaks + in: + nums: [2, -1, 2, -1, 2, -1, 2] + k: 2 + - name: descending_mixed + in: + nums: [9, 7, 5, 3, 1, -1, -3] + k: 3 + - name: ascending_with_drop + in: + nums: [-5, 1, 2, 3, -10000, 4, 5] + k: 3 + - name: negative_start + in: + nums: [-10, 20, -10, 20, -10] + k: 3 + - name: maximum_values + in: + nums: [10000, 10000, 10000, 10000, 10000] + k: 1 + - name: minimum_values + in: + nums: [-10000, -10000, -10000, -10000] + k: 1 + - name: max_min_mix + in: + nums: [10000, -10000, 10000, -10000, 10000] + k: 2 + - name: late_best + in: + nums: [-10000, -9999, -9998, 9999, -10000] + k: 2 + - name: k_equals_length + in: + nums: [-8, 3, -2, 9, -7, 4, 1] + k: 7 + - name: k_equals_one + in: + nums: [1, -2, 3, 4, -1, 6] + k: 1 + - name: k_two + in: + nums: [4, -3, 5, -2, 6, -10, 7] + k: 2 + - name: k_three + in: + nums: [4, -3, -3, 5, -2, 6, -20, 7] + k: 3 + - name: dense_small_values + in: + nums: [-2, 1, -1, 2, -2, 3, -3, 2, 1, -1] + k: 4 + - name: repeated_zero_gaps + in: + nums: [7, -7, 0, -7, 7, -7, 0, 7] + k: 3 + - name: generated_single + seed: 101 + in: + nums: + gen: array + len: 1 + of: + gen: int + min: -10000 + max: 10000 + k: 1 + - name: generated_small + seed: 102 + in: + nums: + gen: array + len: 12 + of: + gen: int + min: -10000 + max: 10000 + k: 5 + - name: generated_medium + seed: 103 + in: + nums: + gen: array + len: 100 + of: + gen: int + min: -10000 + max: 10000 + k: 17 + - name: generated_large + seed: 104 + in: + nums: + gen: array + len: 50000 + of: + gen: int + min: -10000 + max: 10000 + k: 257 + - name: generated_maximum + seed: 105 + in: + nums: + gen: array + len: 100000 + of: + gen: int + min: -10000 + max: 10000 + k: 100000 + - name: long_constant_positive + in: + nums: + gen: array + len: 64 + of: + gen: int + min: 37 + max: 37 + k: 8 + - name: long_constant_negative + in: + nums: + gen: array + len: 64 + of: + gen: int + min: -37 + max: -37 + k: 8 + - name: end_window_shift + in: + nums: [9, -8, -8, 1, -8, -8, 10] + k: 3 + - name: mixed_extremes + in: + nums: [-10000, 9999, -10000, 9998, -10000, 9997, -10000] + k: 2 diff --git a/tests/1001-1500/1425. constrained-subsequence-sum/sol.cpp b/tests/1001-1500/1425. constrained-subsequence-sum/sol.cpp new file mode 100644 index 00000000..9d4a3138 --- /dev/null +++ b/tests/1001-1500/1425. constrained-subsequence-sum/sol.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int constrainedSubsetSum(vector& nums, int k) { + deque> q; + int res = INT_MIN; + for (int i = 0; i < nums.size(); i++) { + int num = nums[i]; + int total = q.empty() ? num : num + q.front().second; + res = max(res, total); + while (!q.empty() && total >= q.back().second) { + q.pop_back(); + } + if (total > 0) { + q.push_back({i, total}); + } + if (!q.empty() && q.front().first == i - k) { + q.pop_front(); + } + } + return res; + } +}; diff --git a/tests/1001-1500/1425. constrained-subsequence-sum/sol.cs b/tests/1001-1500/1425. constrained-subsequence-sum/sol.cs new file mode 100644 index 00000000..c1860a53 --- /dev/null +++ b/tests/1001-1500/1425. constrained-subsequence-sum/sol.cs @@ -0,0 +1,21 @@ +public class Solution { + public int ConstrainedSubsetSum(int[] nums, int k) { + var q = new LinkedList<(int, int)>(); + int res = int.MinValue; + for (int i = 0; i < nums.Length; i++) { + int num = nums[i]; + int total = q.Count == 0 ? num : num + q.First.Value.Item2; + res = Math.Max(res, total); + while (q.Count > 0 && total >= q.Last.Value.Item2) { + q.RemoveLast(); + } + if (total > 0) { + q.AddLast((i, total)); + } + if (q.Count > 0 && q.First.Value.Item1 == i - k) { + q.RemoveFirst(); + } + } + return res; + } +} diff --git a/tests/1001-1500/1425. constrained-subsequence-sum/sol.dart b/tests/1001-1500/1425. constrained-subsequence-sum/sol.dart new file mode 100644 index 00000000..661d1516 --- /dev/null +++ b/tests/1001-1500/1425. constrained-subsequence-sum/sol.dart @@ -0,0 +1,21 @@ +class Solution { + int constrainedSubsetSum(List nums, int k) { + var q = >[]; + var res = -1 << 63; + for (var i = 0; i < nums.length; i++) { + var num = nums[i]; + var total = q.isEmpty ? num : num + q.first[1]; + if (total > res) res = total; + while (q.isNotEmpty && total >= q.last[1]) { + q.removeLast(); + } + if (total > 0) { + q.add([i, total]); + } + if (q.isNotEmpty && q.first[0] == i - k) { + q.removeAt(0); + } + } + return res; + } +} diff --git a/tests/1001-1500/1425. constrained-subsequence-sum/sol.go b/tests/1001-1500/1425. constrained-subsequence-sum/sol.go new file mode 100644 index 00000000..907c1a86 --- /dev/null +++ b/tests/1001-1500/1425. constrained-subsequence-sum/sol.go @@ -0,0 +1,27 @@ +func constrainedSubsetSum(nums []int, k int) int { + type pair struct { + idx int + val int + } + q := []pair{} + res := -1 << 31 + for i, num := range nums { + total := num + if len(q) > 0 { + total += q[0].val + } + if total > res { + res = total + } + for len(q) > 0 && total >= q[len(q)-1].val { + q = q[:len(q)-1] + } + if total > 0 { + q = append(q, pair{i, total}) + } + if len(q) > 0 && q[0].idx == i - k { + q = q[1:] + } + } + return res +} diff --git a/tests/1001-1500/1425. constrained-subsequence-sum/sol.java b/tests/1001-1500/1425. constrained-subsequence-sum/sol.java new file mode 100644 index 00000000..7727a6fe --- /dev/null +++ b/tests/1001-1500/1425. constrained-subsequence-sum/sol.java @@ -0,0 +1,21 @@ +class Solution { + public int constrainedSubsetSum(int[] nums, int k) { + java.util.Deque q = new java.util.ArrayDeque<>(); + int res = Integer.MIN_VALUE; + for (int i = 0; i < nums.length; i++) { + int num = nums[i]; + int total = q.isEmpty() ? num : num + q.peekFirst()[1]; + res = Math.max(res, total); + while (!q.isEmpty() && total >= q.peekLast()[1]) { + q.pollLast(); + } + if (total > 0) { + q.offerLast(new int[]{i, total}); + } + if (!q.isEmpty() && q.peekFirst()[0] == i - k) { + q.pollFirst(); + } + } + return res; + } +} diff --git a/tests/1001-1500/1425. constrained-subsequence-sum/sol.kt b/tests/1001-1500/1425. constrained-subsequence-sum/sol.kt new file mode 100644 index 00000000..b7a82664 --- /dev/null +++ b/tests/1001-1500/1425. constrained-subsequence-sum/sol.kt @@ -0,0 +1,21 @@ +class Solution { + fun constrainedSubsetSum(nums: IntArray, k: Int): Int { + val q = java.util.ArrayDeque>() + var res = Int.MIN_VALUE + for (i in nums.indices) { + val num = nums[i] + val total = if (q.isEmpty()) num else num + q.first().second + res = maxOf(res, total) + while (q.isNotEmpty() && total >= q.last().second) { + q.removeLast() + } + if (total > 0) { + q.addLast(Pair(i, total)) + } + if (q.isNotEmpty() && q.first().first == i - k) { + q.removeFirst() + } + } + return res + } +} diff --git a/tests/1001-1500/1425. constrained-subsequence-sum/sol.py b/tests/1001-1500/1425. constrained-subsequence-sum/sol.py new file mode 100644 index 00000000..b3728df8 --- /dev/null +++ b/tests/1001-1500/1425. constrained-subsequence-sum/sol.py @@ -0,0 +1,24 @@ +from collections import deque +from typing import List + + +class Solution: + def constrainedSubsetSum(self, nums: List[int], k: int) -> int: + + q = deque() + res = float("-inf") + + for i, num in enumerate(nums): + total = num + q[0][1] if q else num + res = max(res, total) + + while q and total >= q[-1][1]: + q.pop() + + if total > 0: + q.append((i, total)) + + if q and q[0][0] == i - k: + q.popleft() + + return res diff --git a/tests/1001-1500/1425. constrained-subsequence-sum/sol.py2 b/tests/1001-1500/1425. constrained-subsequence-sum/sol.py2 new file mode 100644 index 00000000..8856f3c7 --- /dev/null +++ b/tests/1001-1500/1425. constrained-subsequence-sum/sol.py2 @@ -0,0 +1,20 @@ +class Solution(object): + def constrainedSubsetSum(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: int + """ + from collections import deque + q = deque() + res = float('-inf') + for i, num in enumerate(nums): + total = num + q[0][1] if q else num + res = max(res, total) + while q and total >= q[-1][1]: + q.pop() + if total > 0: + q.append((i, total)) + if q and q[0][0] == i - k: + q.popleft() + return res diff --git a/tests/1001-1500/1425. constrained-subsequence-sum/sol.rb b/tests/1001-1500/1425. constrained-subsequence-sum/sol.rb new file mode 100644 index 00000000..584b8365 --- /dev/null +++ b/tests/1001-1500/1425. constrained-subsequence-sum/sol.rb @@ -0,0 +1,21 @@ +# @param {Integer[]} nums +# @param {Integer} k +# @return {Integer} +def constrained_subset_sum(nums, k) + q = [] + res = -Float::INFINITY + nums.each_with_index do |num, i| + total = q.empty? ? num : num + q[0][1] + res = total if total > res + while !q.empty? && total >= q[-1][1] + q.pop + end + if total > 0 + q << [i, total] + end + if !q.empty? && q[0][0] == i - k + q.shift + end + end + res +end diff --git a/tests/1001-1500/1425. constrained-subsequence-sum/sol.rs b/tests/1001-1500/1425. constrained-subsequence-sum/sol.rs new file mode 100644 index 00000000..d9e083fe --- /dev/null +++ b/tests/1001-1500/1425. constrained-subsequence-sum/sol.rs @@ -0,0 +1,28 @@ +impl Solution { + pub fn constrained_subset_sum(nums: Vec, k: i32) -> i32 { + use std::collections::VecDeque; + let mut q: VecDeque<(i32, i32)> = VecDeque::new(); + let mut res = i32::MIN; + for (i, &num) in nums.iter().enumerate() { + let i = i as i32; + let total = if q.is_empty() { num } else { num + q.front().unwrap().1 }; + res = res.max(total); + while let Some(&back) = q.back() { + if total >= back.1 { + q.pop_back(); + } else { + break; + } + } + if total > 0 { + q.push_back((i, total)); + } + if let Some(&front) = q.front() { + if front.0 == i - k { + q.pop_front(); + } + } + } + res + } +} diff --git a/tests/1001-1500/1425. constrained-subsequence-sum/sol.swift b/tests/1001-1500/1425. constrained-subsequence-sum/sol.swift new file mode 100644 index 00000000..30711924 --- /dev/null +++ b/tests/1001-1500/1425. constrained-subsequence-sum/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func constrainedSubsetSum(_ nums: [Int], _ k: Int) -> Int { + var q = [(Int, Int)]() + var res = Int.min + for (i, num) in nums.enumerated() { + let total = q.isEmpty ? num : num + q[0].1 + res = max(res, total) + while !q.isEmpty && total >= q.last!.1 { + q.removeLast() + } + if total > 0 { + q.append((i, total)) + } + if !q.isEmpty && q[0].0 == i - k { + q.removeFirst() + } + } + return res + } +} diff --git a/tests/1001-1500/1425. constrained-subsequence-sum/sol.ts b/tests/1001-1500/1425. constrained-subsequence-sum/sol.ts new file mode 100644 index 00000000..81da923f --- /dev/null +++ b/tests/1001-1500/1425. constrained-subsequence-sum/sol.ts @@ -0,0 +1,19 @@ +function constrainedSubsetSum(nums: number[], k: number): number { + const q: [number, number][] = []; + let res = -Infinity; + for (let i = 0; i < nums.length; i++) { + const num = nums[i]; + const total = q.length === 0 ? num : num + q[0][1]; + res = Math.max(res, total); + while (q.length > 0 && total >= q[q.length - 1][1]) { + q.pop(); + } + if (total > 0) { + q.push([i, total]); + } + if (q.length > 0 && q[0][0] === i - k) { + q.shift(); + } + } + return res; +} diff --git a/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/manifest.yaml b/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/manifest.yaml new file mode 100644 index 00000000..3bf90b8f --- /dev/null +++ b/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/manifest.yaml @@ -0,0 +1,383 @@ +entry: + id: 1431 + title: "kids-with-the-greatest-number-of-candies" + params: + candies: + type: array + items: + type: int + extraCandies: + type: int + call: + cpp: "Solution().kidsWithCandies({candies}, {extraCandies})" + rust: "Solution::kids_with_candies({candies}, {extraCandies})" + python3: "Solution().kidsWithCandies({candies}, {extraCandies})" + python2: "Solution().kidsWithCandies({candies}, {extraCandies})" + ruby: "kids_with_candies({candies}, {extraCandies})" + java: "new Solution().kidsWithCandies({candies}, {extraCandies})" + csharp: "new Solution().KidsWithCandies({candies}, {extraCandies})" + kotlin: "Solution().kidsWithCandies({candies}, {extraCandies})" + go: "kidsWithCandies({candies}, {extraCandies})" + dart: "Solution().kidsWithCandies({candies}, {extraCandies})" + swift: "Solution().kidsWithCandies({candies}, {extraCandies})" + typescript: "kidsWithCandies({candies}, {extraCandies})" +judge: + type: exact +limits: + time_ms: 300 + memory_mb: 300 +oracle: + python3: + call: "Checker().kidsWithCandies(candies, extraCandies, {result})" + checker: | + class Checker: + def kidsWithCandies(self, candies, extra, result): + if not isinstance(result, list) or len(result) != len(candies): + return False + if any(type(item) is not bool for item in result): + return False + highest = max(candies) + return result == [count + extra >= highest for count in candies] +seed: 1431 +tests: + - name: "example_one" + in: + candies: [2, 3, 5, 1, 3] + extraCandies: 3 + out: [true, true, true, false, true] + - name: "example_two" + in: + candies: [4, 2, 1, 1, 2] + extraCandies: 1 + out: [true, false, false, false, false] + - name: "example_three" + in: + candies: [12, 1, 12] + extraCandies: 10 + out: [true, false, true] + - name: "minimum_equal" + in: + candies: [1, 1] + extraCandies: 1 + out: [true, true] + - name: "minimum_gap" + in: + candies: [1, 100] + extraCandies: 1 + - name: "all_equal" + in: + candies: [7, 7, 7, 7, 7] + extraCandies: 1 + - name: "one_reaches" + in: + candies: [1, 1, 10, 1] + extraCandies: 1 + - name: "all_reach" + in: + candies: [1, 2, 3, 4] + extraCandies: 3 + - name: "maximum_extra" + in: + candies: [1, 50, 100, 2] + extraCandies: 50 + - name: "minimum_extra" + in: + candies: [1, 2, 3, 4, 5] + extraCandies: 1 + - name: "ascending" + in: + candies: [1, 2, 3, 4, 5, 6] + extraCandies: 2 + - name: "descending" + in: + candies: [6, 5, 4, 3, 2, 1] + extraCandies: 2 + - name: "repeated_max" + in: + candies: [3, 8, 8, 2, 8] + extraCandies: 1 + - name: "repeated_min" + in: + candies: [1, 1, 1, 2, 2] + extraCandies: 1 + - name: "high_low_ties" + in: + candies: [100, 1, 100, 1, 100, 1] + extraCandies: 1 + - name: "near_upper" + in: + candies: [99, 98, 97, 96, 95] + extraCandies: 1 + - name: "all_upper" + in: + candies: [100, 100, 100, 100, 100] + extraCandies: 50 + - name: "balanced_ties" + in: + candies: [20, 20, 10, 10, 20, 10] + extraCandies: 10 + - name: "small_gap" + in: + candies: [15, 14, 13, 12, 11, 10] + extraCandies: 2 + - name: "two_maxima" + in: + candies: [30, 1, 30, 1, 29, 2] + extraCandies: 1 + - name: "alternating_ties" + in: + candies: [4, 9, 4, 9, 4, 9] + extraCandies: 3 + - name: "arithmetic" + in: + candies: [13, 26, 39, 52, 65] + extraCandies: 13 + - name: "permuted" + in: + candies: [18, 3, 27, 12, 21, 6] + extraCandies: 9 + - name: "low_max_extra" + in: + candies: [1, 2, 1, 3, 2, 1] + extraCandies: 50 + - name: "max_min_extra" + in: + candies: [100, 99, 100, 98, 97] + extraCandies: 1 + - name: "alternating_ramp" + in: + candies: [2, 9, 3, 8, 4, 7, 5, 6] + extraCandies: 2 + - name: "many_ties" + in: + candies: [1, 1, 2, 1, 2, 1, 2] + extraCandies: 1 + - name: "middle_reaches" + in: + candies: [5, 11, 6, 7, 8] + extraCandies: 4 + - name: "only_maxima" + in: + candies: [10, 20, 30, 40, 50] + extraCandies: 1 + - name: "wide_small" + in: + candies: [1, 100, 50, 2, 99, 3, 98, 4] + extraCandies: 2 + - name: "length_twenty" + in: + candies: + [1, 20, 2, 19, 3, 18, 4, 17, 5, 16, 6, 15, 7, 14, 8, 13, 9, 12, 10, 11] + extraCandies: 5 + - name: "length_hundred_ramp" + in: + candies: + [ + 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, + ] + extraCandies: 1 + - name: "near_tie_mixed" + in: + candies: [42, 7, 41, 6, 40, 5, 39, 4] + extraCandies: 2 + - name: "minimum_max_extra" + in: + candies: [1, 1, 1, 2, 1, 2] + extraCandies: 50 + - name: "single_peak_center" + in: + candies: [1, 3, 5, 7, 5, 3, 1] + extraCandies: 2 + - name: "generated_small" + seed: 201 + in: + candies: + gen: "array" + len: + gen: "int" + min: 2 + max: 8 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + sorted: false + elemType: "int" + extraCandies: + gen: "int" + min: 1 + max: 50 + - name: "generated_medium" + seed: 202 + in: + candies: + gen: "array" + len: + gen: "int" + min: 25 + max: 50 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + sorted: false + elemType: "int" + extraCandies: + gen: "int" + min: 1 + max: 50 + - name: "generated_maximum" + seed: 203 + in: + candies: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + sorted: false + elemType: "int" + extraCandies: + gen: "int" + min: 1 + max: 50 + - name: "generated_maximum_min_extra" + seed: 204 + in: + candies: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + sorted: false + elemType: "int" + extraCandies: + gen: "int" + min: 1 + max: 1 + - name: "generated_longer" + seed: 205 + in: + candies: + gen: "array" + len: + gen: "int" + min: 70 + max: 99 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + sorted: false + elemType: "int" + extraCandies: + gen: "int" + min: 1 + max: 50 diff --git a/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.cpp b/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.cpp new file mode 100644 index 00000000..038fc6bf --- /dev/null +++ b/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + vector kidsWithCandies(vector& candies, int extraCandies) { + int currentMax = *max_element(candies.begin(), candies.end()); + vector result; + for (int candyCount : candies) { + if (candyCount + extraCandies >= currentMax) { + result.push_back(true); + } else { + result.push_back(false); + } + } + return result; + } +}; diff --git a/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.cs b/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.cs new file mode 100644 index 00000000..af3b9a25 --- /dev/null +++ b/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.cs @@ -0,0 +1,14 @@ +public class Solution { + public IList KidsWithCandies(int[] candies, int extraCandies) { + int currentMax = candies.Max(); + IList result = new List(); + foreach (int candyCount in candies) { + if (candyCount + extraCandies >= currentMax) { + result.Add(true); + } else { + result.Add(false); + } + } + return result; + } +} diff --git a/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.dart b/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.dart new file mode 100644 index 00000000..aa97afdb --- /dev/null +++ b/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.dart @@ -0,0 +1,14 @@ +class Solution { + List kidsWithCandies(List candies, int extraCandies) { + int currentMax = candies.reduce((a, b) => a > b ? a : b); + List result = []; + for (int candyCount in candies) { + if (candyCount + extraCandies >= currentMax) { + result.add(true); + } else { + result.add(false); + } + } + return result; + } +} diff --git a/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.go b/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.go new file mode 100644 index 00000000..b0410b72 --- /dev/null +++ b/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.go @@ -0,0 +1,17 @@ +func kidsWithCandies(candies []int, extraCandies int) []bool { + currentMax := candies[0] + for _, candy := range candies { + if candy > currentMax { + currentMax = candy + } + } + result := make([]bool, len(candies)) + for i, candyCount := range candies { + if candyCount+extraCandies >= currentMax { + result[i] = true + } else { + result[i] = false + } + } + return result +} diff --git a/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.java b/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.java new file mode 100644 index 00000000..414b373c --- /dev/null +++ b/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.java @@ -0,0 +1,19 @@ +class Solution { + public List kidsWithCandies(int[] candies, int extraCandies) { + int currentMax = 0; + for (int candy : candies) { + if (candy > currentMax) { + currentMax = candy; + } + } + List result = new ArrayList<>(); + for (int candyCount : candies) { + if (candyCount + extraCandies >= currentMax) { + result.add(true); + } else { + result.add(false); + } + } + return result; + } +} diff --git a/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.kt b/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.kt new file mode 100644 index 00000000..fe7af722 --- /dev/null +++ b/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.kt @@ -0,0 +1,14 @@ +class Solution { + fun kidsWithCandies(candies: IntArray, extraCandies: Int): List { + val currentMax = candies.max() + val result = mutableListOf() + for (candyCount in candies) { + if (candyCount + extraCandies >= currentMax) { + result.add(true) + } else { + result.add(false) + } + } + return result + } +} diff --git a/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.py b/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.py new file mode 100644 index 00000000..b857e734 --- /dev/null +++ b/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.py @@ -0,0 +1,12 @@ +class Solution: + def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]: + current_max = max(candies) + result = [] + + for candy_count in candies: + if candy_count + extraCandies >= current_max: + result.append(True) + else: + result.append(False) + + return result diff --git a/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.py2 b/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.py2 new file mode 100644 index 00000000..3ebf8d57 --- /dev/null +++ b/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.py2 @@ -0,0 +1,15 @@ +class Solution(object): + def kidsWithCandies(self, candies, extraCandies): + """ + :type candies: List[int] + :type extraCandies: int + :rtype: List[bool] + """ + current_max = max(candies) + result = [] + for candy_count in candies: + if candy_count + extraCandies >= current_max: + result.append(True) + else: + result.append(False) + return result diff --git a/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.rb b/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.rb new file mode 100644 index 00000000..93af9f6a --- /dev/null +++ b/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.rb @@ -0,0 +1,15 @@ +# @param {Integer[]} candies +# @param {Integer} extra_candies +# @return {Boolean[]} +def kids_with_candies(candies, extra_candies) + current_max = candies.max + result = [] + candies.each do |candy_count| + if candy_count + extra_candies >= current_max + result << true + else + result << false + end + end + result +end diff --git a/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.rs b/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.rs new file mode 100644 index 00000000..4ad79178 --- /dev/null +++ b/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.rs @@ -0,0 +1,14 @@ +impl Solution { + pub fn kids_with_candies(candies: Vec, extra_candies: i32) -> Vec { + let current_max = *candies.iter().max().unwrap(); + let mut result = Vec::with_capacity(candies.len()); + for candy_count in candies { + if candy_count + extra_candies >= current_max { + result.push(true); + } else { + result.push(false); + } + } + result + } +} diff --git a/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.swift b/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.swift new file mode 100644 index 00000000..d80ac2d2 --- /dev/null +++ b/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.swift @@ -0,0 +1,14 @@ +class Solution { + func kidsWithCandies(_ candies: [Int], _ extraCandies: Int) -> [Bool] { + let currentMax = candies.max()! + var result: [Bool] = [] + for candyCount in candies { + if candyCount + extraCandies >= currentMax { + result.append(true) + } else { + result.append(false) + } + } + return result + } +} diff --git a/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.ts b/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.ts new file mode 100644 index 00000000..b821cc1c --- /dev/null +++ b/tests/1001-1500/1431. kids-with-the-greatest-number-of-candies/sol.ts @@ -0,0 +1,12 @@ +function kidsWithCandies(candies: number[], extraCandies: number): boolean[] { + const currentMax = Math.max(...candies); + const result: boolean[] = []; + for (const candyCount of candies) { + if (candyCount + extraCandies >= currentMax) { + result.push(true); + } else { + result.push(false); + } + } + return result; +} diff --git a/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/manifest.yaml b/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/manifest.yaml new file mode 100644 index 00000000..97661366 --- /dev/null +++ b/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/manifest.yaml @@ -0,0 +1,202 @@ +entry: + id: 1432 + title: "max-difference-you-can-get-from-changing-an-integer" + params: + num: + type: int + call: + cpp: "Solution().maxDiff({num})" + rust: "Solution::max_diff({num})" + python3: "Solution().maxDiff({num})" + python2: "Solution().maxDiff({num})" + ruby: "max_diff({num})" + java: "new Solution().maxDiff({num})" + csharp: "new Solution().MaxDiff({num})" + kotlin: "Solution().maxDiff({num})" + go: "maxDiff({num})" + dart: "Solution().maxDiff({num})" + swift: "Solution().maxDiff({num})" + typescript: "maxDiff({num})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().maxDiff(num, {result})" + checker: | + class Checker: + def maxDiff(self, num, result): + if not isinstance(num, int) or isinstance(num, bool) or not 1 <= num <= 100000000: + return False + if isinstance(result, bool): + return False + try: + result = int(result) + except (TypeError, ValueError): + return False + + text = str(num) + high_digit = next((digit for digit in text if digit != "9"), None) + if high_digit is None: + high_text = text + else: + high_text = text.replace(high_digit, "9") + + if text[0] != "1": + low_text = text.replace(text[0], "1") + else: + low_digit = next((digit for digit in text[1:] if digit not in "01"), None) + low_text = text if low_digit is None else text.replace(low_digit, "0") + + return result == int(high_text) - int(low_text) + +seed: 1432 + +tests: + - name: "example-555" + in: + num: 555 + out: 888 + - name: "example-nine" + in: + num: 9 + out: 8 + - name: "minimum-one" + in: + num: 1 + - name: "single-zero-internal" + in: + num: 10 + - name: "two-distinct" + in: + num: 12 + - name: "two-nines" + in: + num: 99 + - name: "two-zeros" + in: + num: 100 + - name: "leading-one" + in: + num: 123 + - name: "leading-nine" + in: + num: 987 + - name: "mixed-repeated" + in: + num: 121 + - name: "zero-middle" + in: + num: 101 + - name: "zero-ending" + in: + num: 120 + - name: "ascending-digits" + in: + num: 1234 + - name: "descending-digits" + in: + num: 9876 + - name: "alternating-one-two" + in: + num: 1212 + - name: "alternating-nine-zero" + in: + num: 9090 + - name: "palindrome" + in: + num: 1221 + - name: "many-zeroes" + in: + num: 10001 + - name: "five-digit-mixed" + in: + num: 31415 + - name: "five-digit-boundary" + in: + num: 99999 + - name: "six-digit-repeated" + in: + num: 777777 + - name: "six-digit-mixed" + in: + num: 102938 + - name: "six-digit-palindrome" + in: + num: 123321 + - name: "seven-digit-small-leading" + in: + num: 1000001 + - name: "seven-digit-max-pattern" + in: + num: 9876543 + - name: "eight-digit-min-bound" + in: + num: 10000000 + - name: "eight-digit-max-bound" + in: + num: 100000000 + - name: "eight-digit-repeated" + in: + num: 88888888 + - name: "eight-digit-mixed" + in: + num: 90817263 + - name: "seven-digit-zero-heavy" + in: + num: 9090909 + - name: "eight-digit-zero-pattern" + in: + num: 10909090 + - name: "eight-digit-descending-zero" + in: + num: 76543210 + - name: "eight-digit-repeated-one-zero" + in: + num: 11001111 + - name: "eight-digit-leading-two" + in: + num: 20000000 + - name: "near-eight-digit-nine" + in: + num: 99999998 + - name: "generated-large-midrange" + seed: 143201 + in: + num: + gen: "int" + min: 10000000 + max: 99999999 + - name: "generated-large-leading-one" + seed: 143202 + in: + num: + gen: "int" + min: 10000000 + max: 19999999 + - name: "generated-large-leading-nine" + seed: 143203 + in: + num: + gen: "int" + min: 90000000 + max: 99999999 + - name: "generated-large-upper-bound" + seed: 143204 + in: + num: + gen: "int" + min: 80000000 + max: 100000000 + - name: "generated-large-lower-bound" + seed: 143205 + in: + num: + gen: "int" + min: 10000000 + max: 10000001 diff --git a/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.cpp b/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.cpp new file mode 100644 index 00000000..957bd8b2 --- /dev/null +++ b/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int maxDiff(int num) { + string numStr = to_string(num); + set uniqueDigits(numStr.begin(), numStr.end()); + int maxVal = num; + int minVal = num; + + for (char digit : uniqueDigits) { + for (char newDigit = '0'; newDigit <= '9'; newDigit++) { + if (numStr[0] == digit && newDigit == '0') { + continue; + } + string newNumStr = numStr; + replace(newNumStr.begin(), newNumStr.end(), digit, newDigit); + int newNum = stoi(newNumStr); + maxVal = max(maxVal, newNum); + minVal = min(minVal, newNum); + } + } + + return maxVal - minVal; + } +}; diff --git a/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.cs b/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.cs new file mode 100644 index 00000000..1e273cf6 --- /dev/null +++ b/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.cs @@ -0,0 +1,22 @@ +public class Solution { + public int MaxDiff(int num) { + string numStr = num.ToString(); + var uniqueDigits = new HashSet(numStr); + int maxVal = num; + int minVal = num; + + foreach (char digit in uniqueDigits) { + for (char newDigit = '0'; newDigit <= '9'; newDigit++) { + if (numStr[0] == digit && newDigit == '0') { + continue; + } + string newNumStr = numStr.Replace(digit, newDigit); + int newNum = int.Parse(newNumStr); + maxVal = Math.Max(maxVal, newNum); + minVal = Math.Min(minVal, newNum); + } + } + + return maxVal - minVal; + } +} diff --git a/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.dart b/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.dart new file mode 100644 index 00000000..9cf4a3e3 --- /dev/null +++ b/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.dart @@ -0,0 +1,23 @@ +class Solution { + int maxDiff(int num) { + String numStr = num.toString(); + var uniqueDigits = numStr.split('').toSet(); + int maxVal = num; + int minVal = num; + + for (var digit in uniqueDigits) { + for (var newDigitCode = 48; newDigitCode <= 57; newDigitCode++) { + String newDigit = String.fromCharCode(newDigitCode); + if (numStr[0] == digit && newDigit == '0') { + continue; + } + String newNumStr = numStr.replaceAll(digit, newDigit); + int newNum = int.parse(newNumStr); + if (newNum > maxVal) maxVal = newNum; + if (newNum < minVal) minVal = newNum; + } + } + + return maxVal - minVal; + } +} diff --git a/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.go b/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.go new file mode 100644 index 00000000..ace33edc --- /dev/null +++ b/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.go @@ -0,0 +1,27 @@ +func maxDiff(num int) int { + numStr := strconv.Itoa(num) + uniqueDigits := make(map[rune]bool) + for _, ch := range numStr { + uniqueDigits[ch] = true + } + maxVal := num + minVal := num + + for digit := range uniqueDigits { + for newDigit := '0'; newDigit <= '9'; newDigit++ { + if rune(numStr[0]) == digit && newDigit == '0' { + continue + } + newNumStr := strings.ReplaceAll(numStr, string(digit), string(newDigit)) + newNum, _ := strconv.Atoi(newNumStr) + if newNum > maxVal { + maxVal = newNum + } + if newNum < minVal { + minVal = newNum + } + } + } + + return maxVal - minVal +} diff --git a/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.java b/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.java new file mode 100644 index 00000000..60ef1ec1 --- /dev/null +++ b/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.java @@ -0,0 +1,31 @@ +class Solution { + public int maxDiff(int num) { + String text = Integer.toString(num); + + char maxDigit = 0; + for (int i = 0; i < text.length(); i++) { + if (text.charAt(i) != '9') { + maxDigit = text.charAt(i); + break; + } + } + String high = maxDigit == 0 ? text : text.replace(maxDigit, '9'); + + String low; + if (text.charAt(0) != '1') { + low = text.replace(text.charAt(0), '1'); + } else { + char lowDigit = 0; + for (int i = 1; i < text.length(); i++) { + char digit = text.charAt(i); + if (digit != '0' && digit != '1') { + lowDigit = digit; + break; + } + } + low = lowDigit == 0 ? text : text.replace(lowDigit, '0'); + } + + return Integer.parseInt(high) - Integer.parseInt(low); + } +} diff --git a/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.kt b/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.kt new file mode 100644 index 00000000..782443aa --- /dev/null +++ b/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.kt @@ -0,0 +1,22 @@ +class Solution { + fun maxDiff(num: Int): Int { + val numStr = num.toString() + val uniqueDigits = numStr.toSet() + var maxVal = num + var minVal = num + + for (digit in uniqueDigits) { + for (newDigit in '0'..'9') { + if (numStr[0] == digit && newDigit == '0') { + continue + } + val newNumStr = numStr.replace(digit, newDigit) + val newNum = newNumStr.toInt() + maxVal = maxOf(maxVal, newNum) + minVal = minOf(minVal, newNum) + } + } + + return maxVal - minVal + } +} diff --git a/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.py b/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.py new file mode 100644 index 00000000..0aa0201f --- /dev/null +++ b/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.py @@ -0,0 +1,17 @@ +class Solution: + def maxDiff(self, num: int) -> int: + numStr = str(num) + uniqueDigits = set(numStr) + maxVal = num + minVal = num + + for digit in uniqueDigits: + for newDigit in "0123456789": + if numStr[0] == digit and newDigit == "0": + continue + newNumStr = numStr.replace(digit, newDigit) + newNum = int(newNumStr) + maxVal = max(maxVal, newNum) + minVal = min(minVal, newNum) + + return maxVal - minVal diff --git a/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.py2 b/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.py2 new file mode 100644 index 00000000..346eb191 --- /dev/null +++ b/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.py2 @@ -0,0 +1,21 @@ +class Solution(object): + def maxDiff(self, num): + """ + :type num: int + :rtype: int + """ + numStr = str(num) + uniqueDigits = set(numStr) + maxVal = num + minVal = num + + for digit in uniqueDigits: + for newDigit in '0123456789': + if numStr[0] == digit and newDigit == '0': + continue + newNumStr = numStr.replace(digit, newDigit) + newNum = int(newNumStr) + maxVal = max(maxVal, newNum) + minVal = min(minVal, newNum) + + return maxVal - minVal diff --git a/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.rb b/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.rb new file mode 100644 index 00000000..706c874e --- /dev/null +++ b/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.rb @@ -0,0 +1,20 @@ +# @param {Integer} num +# @return {Integer} +def max_diff(num) + num_str = num.to_s + unique_digits = num_str.chars.uniq + max_val = num + min_val = num + + unique_digits.each do |digit| + ('0'..'9').each do |new_digit| + next if num_str[0] == digit && new_digit == '0' + new_num_str = num_str.gsub(digit, new_digit) + new_num = new_num_str.to_i + max_val = [max_val, new_num].max + min_val = [min_val, new_num].min + end + end + + max_val - min_val +end diff --git a/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.rs b/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.rs new file mode 100644 index 00000000..5a0bdab3 --- /dev/null +++ b/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.rs @@ -0,0 +1,29 @@ +impl Solution { + pub fn max_diff(num: i32) -> i32 { + let text = num.to_string(); + + let max_digit = text.chars().find(|&digit| digit != '9'); + let high = replace_digit(&text, max_digit, '9'); + + let first = text.chars().next().unwrap(); + let low_digit = if first != '1' { + Some(first) + } else { + text.chars().skip(1).find(|&digit| digit != '0' && digit != '1') + }; + let low_replacement = if first != '1' { '1' } else { '0' }; + let low = replace_digit(&text, low_digit, low_replacement); + + high.parse::().unwrap() - low.parse::().unwrap() + } +} + +fn replace_digit(text: &str, digit: Option, replacement: char) -> String { + match digit { + Some(target) => text + .chars() + .map(|current| if current == target { replacement } else { current }) + .collect(), + None => text.to_string(), + } +} diff --git a/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.swift b/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.swift new file mode 100644 index 00000000..9c474239 --- /dev/null +++ b/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.swift @@ -0,0 +1,23 @@ +class Solution { + func maxDiff(_ num: Int) -> Int { + let numStr = String(num) + let uniqueDigits = Set(numStr) + var maxVal = num + var minVal = num + + for digit in uniqueDigits { + for newDigit in "0123456789" { + if numStr.first == digit && newDigit == "0" { + continue + } + let newNumStr = numStr.replacingOccurrences(of: String(digit), with: String(newDigit)) + if let newNum = Int(newNumStr) { + maxVal = max(maxVal, newNum) + minVal = min(minVal, newNum) + } + } + } + + return maxVal - minVal + } +} diff --git a/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.ts b/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.ts new file mode 100644 index 00000000..56347fc0 --- /dev/null +++ b/tests/1001-1500/1432. max-difference-you-can-get-from-changing-an-integer/sol.ts @@ -0,0 +1,21 @@ +function maxDiff(num: number): number { + const numStr = num.toString(); + const uniqueDigits = new Set(numStr.split("")); + let maxVal = num; + let minVal = num; + + for (const digit of uniqueDigits) { + for (let newDigitCode = 48; newDigitCode <= 57; newDigitCode++) { + const newDigit = String.fromCharCode(newDigitCode); + if (numStr[0] === digit && newDigit === "0") { + continue; + } + const newNumStr = numStr.split(digit).join(newDigit); + const newNum = parseInt(newNumStr, 10); + maxVal = Math.max(maxVal, newNum); + minVal = Math.min(minVal, newNum); + } + } + + return maxVal - minVal; +} diff --git a/tests/1001-1500/1433. check-if-a-string-can-break-another-string/manifest.yaml b/tests/1001-1500/1433. check-if-a-string-can-break-another-string/manifest.yaml new file mode 100644 index 00000000..9c4bce74 --- /dev/null +++ b/tests/1001-1500/1433. check-if-a-string-can-break-another-string/manifest.yaml @@ -0,0 +1,260 @@ +entry: + id: 1433 + title: check-if-a-string-can-break-another-string + params: + s1: + type: string + s2: + type: string + call: + cpp: "Solution().checkIfCanBreak({s1}, {s2})" + rust: "Solution::check_if_can_break({s1}, {s2})" + python3: "Solution().checkIfCanBreak({s1}, {s2})" + python2: "Solution().checkIfCanBreak({s1}, {s2})" + ruby: "check_if_can_break({s1}, {s2})" + java: "new Solution().checkIfCanBreak({s1}, {s2})" + csharp: "new Solution().CheckIfCanBreak({s1}, {s2})" + kotlin: "Solution().checkIfCanBreak({s1}, {s2})" + go: "checkIfCanBreak({s1}, {s2})" + dart: "Solution().checkIfCanBreak({s1}, {s2})" + swift: "Solution().checkIfCanBreak({s1}, {s2})" + typescript: "checkIfCanBreak({s1}, {s2})" +judge: + type: exact +limits: + time_ms: 500 + memory_mb: 256 +oracle: + python3: + call: "Checker().checkIfCanBreak(s1, s2, {result})" + checker: | + class Checker: + def checkIfCanBreak(self, s1, s2, result): + if not isinstance(s1, str) or not isinstance(s2, str): + return False + if len(s1) != len(s2) or not 1 <= len(s1) <= 100000: + return False + if any(ch < 'a' or ch > 'z' for ch in s1 + s2): + return False + if not isinstance(result, bool): + return False + + def can_break(first, second): + left = [0] * 26 + right = [0] * 26 + for ch in first: + left[ord(ch) - 97] += 1 + for ch in second: + right[ord(ch) - 97] += 1 + i = 0 + j = 0 + for _ in range(len(first)): + while left[i] == 0: + i += 1 + while right[j] == 0: + j += 1 + if i < j: + return False + left[i] -= 1 + right[j] -= 1 + return True + + expected = can_break(s1, s2) or can_break(s2, s1) + return result == expected +seed: 1433 +tests: + - name: example_one + in: + s1: abc + s2: xya + - name: example_two + in: + s1: abe + s2: acd + - name: example_three + in: + s1: leetcodee + s2: interview + - name: single_equal + in: + s1: m + s2: m + - name: single_low_high + in: + s1: a + s2: z + - name: single_high_low + in: + s1: z + s2: a + - name: identical_unsorted_multiset + in: + s1: dcba + s2: abcd + - name: all_low_vs_all_high + in: + s1: aaaa + s2: zzzz + - name: repeated_boundary_letters + in: + s1: aaaz + s2: aazz + - name: one_coordinate_fails + in: + s1: abcd + s2: abce + - name: strict_nonbreak + in: + s1: ace + s2: bdf + - name: duplicate_counts_make_true + in: + s1: aabb + s2: abba + - name: crossing_histograms + in: + s1: aaazzz + s2: bbbccc + - name: alternating_input + in: + s1: abab + s2: baba + - name: reverse_alphabet + in: + s1: zyxwv + s2: abcde + - name: narrow_middle_overlap + in: + s1: mnopqr + s2: nopqrs + - name: one_low_outlier + in: + s1: bbbbbc + s2: aaabbb + - name: one_high_outlier + in: + s1: aaabbb + s2: bbbbbc + - name: equal_extreme_mix + in: + s1: azazaz + s2: zazaza + - name: adjacent_ranges + in: + s1: abcxyz + s2: defuvw + - name: separated_ranges + in: + s1: aaaabbbb + s2: ccccdddd + - name: interleaved_ranges + in: + s1: azby + s2: cxdw + - name: repeated_middle + in: + s1: mmnn + s2: lmno + - name: all_a_against_mixed + in: + s1: aaaaaa + s2: aaaaaz + - name: all_z_against_mixed + in: + s1: zzzzzz + s2: wxyzzy + - name: full_alphabet_same + in: + s1: abcdefghijklmnopqrstuvwxyz + s2: zyxwvutsrqponmlkjihgfedcba + - name: repeated_full_alphabet + in: + s1: abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz + s2: zyxwvutsrqponmlkjihgfedcbazyxwvutsrqponmlkjihgfedcba + - name: length_twenty_true + in: + s1: abcdefghijabcdefghij + s2: klmnopqrstklmnopqrst + - name: length_twenty_false + in: + s1: aeiouaeiouaeiouaeiou + s2: bcdfgbcdfgbcdfgbcdfg + - name: long_runs_touching + in: + s1: aaaaaabbbbbbcccccc + s2: bbbbbbaaaaaacccccc + - name: balanced_triplets + in: + s1: aaabbbccc + s2: abcbacabc + - name: sparse_extremes + in: + s1: aaaaaaaaaz + s2: aaaaaaaayz + - name: late_extreme_mismatch + in: + s1: azzz + s2: byyy + - name: two_low_two_middle + in: + s1: aaczz + s2: bbyyy + - name: strict_every_position + in: + s1: bcz + s2: aby + - name: generated_minimum_length + seed: 143301 + in: + s1: + gen: str + len: 1 + alphabet: az + s2: + gen: str + len: 1 + alphabet: az + - name: generated_short_strings + seed: 143302 + in: + s1: + gen: str + len: 17 + alphabet: abcxyz + s2: + gen: str + len: 17 + alphabet: abcxyz + - name: generated_full_alphabet + seed: 143303 + in: + s1: + gen: str + len: 1000 + alphabet: abcdefghijklmnopqrstuvwxyz + s2: + gen: str + len: 1000 + alphabet: abcdefghijklmnopqrstuvwxyz + - name: generated_large_bounded + seed: 143304 + in: + s1: + gen: str + len: 50000 + alphabet: abcdefghijklmnopqrstuvwxyz + s2: + gen: str + len: 50000 + alphabet: abcdefghijklmnopqrstuvwxyz + - name: generated_maximum_length + seed: 143305 + in: + s1: + gen: str + len: 100000 + alphabet: abcdefghijklmnopqrstuvwxyz + s2: + gen: str + len: 100000 + alphabet: abcdefghijklmnopqrstuvwxyz diff --git a/tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.cpp b/tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.cpp new file mode 100644 index 00000000..e5843d25 --- /dev/null +++ b/tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.cpp @@ -0,0 +1,49 @@ +class Solution { +public: + bool checkIfCanBreak(string s1, string s2) { + vector freq(26, 0); + int n = s1.length(); + + for (char ch : s1) { + freq[ch - 'a']++; + } + + string temp1 = ""; + + for (int i = 25; i >= 0; i--) { + while (freq[i] > 0) { + temp1 += ('a' + i); + freq[i]--; + } + } + + freq = vector(26, 0); + + for (char ch : s2) { + freq[ch - 'a']++; + } + + string temp2 = ""; + + for (int i = 25; i >= 0; i--) { + while (freq[i] > 0) { + temp2 += ('a' + i); + freq[i]--; + } + } + + bool all1 = true; + bool all2 = true; + + for (int i = 0; i < n; i++) { + if (temp1[i] < temp2[i]) { + all1 = false; + } + if (temp2[i] < temp1[i]) { + all2 = false; + } + } + + return all1 || all2; + } +}; diff --git a/tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.cs b/tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.cs new file mode 100644 index 00000000..108b4974 --- /dev/null +++ b/tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.cs @@ -0,0 +1,51 @@ +public class Solution { + public bool CheckIfCanBreak(string s1, string s2) { + int[] freq = new int[26]; + int n = s1.Length; + + foreach (char ch in s1) { + freq[ch - 'a']++; + } + + System.Text.StringBuilder temp1 = new System.Text.StringBuilder(); + + for (int i = 25; i >= 0; i--) { + while (freq[i] > 0) { + temp1.Append((char)('a' + i)); + freq[i]--; + } + } + + freq = new int[26]; + + foreach (char ch in s2) { + freq[ch - 'a']++; + } + + System.Text.StringBuilder temp2 = new System.Text.StringBuilder(); + + for (int i = 25; i >= 0; i--) { + while (freq[i] > 0) { + temp2.Append((char)('a' + i)); + freq[i]--; + } + } + + string sorted1 = temp1.ToString(); + string sorted2 = temp2.ToString(); + + bool all1 = true; + bool all2 = true; + + for (int i = 0; i < n; i++) { + if (sorted1[i] < sorted2[i]) { + all1 = false; + } + if (sorted2[i] < sorted1[i]) { + all2 = false; + } + } + + return all1 || all2; + } +} diff --git a/tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.dart b/tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.dart new file mode 100644 index 00000000..0f88fd10 --- /dev/null +++ b/tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.dart @@ -0,0 +1,51 @@ +class Solution { + bool checkIfCanBreak(String s1, String s2) { + List freq = List.filled(26, 0); + int n = s1.length; + + for (int i = 0; i < n; i++) { + freq[s1.codeUnitAt(i) - 'a'.codeUnitAt(0)]++; + } + + StringBuffer temp1 = StringBuffer(); + + for (int i = 25; i >= 0; i--) { + while (freq[i] > 0) { + temp1.write(String.fromCharCode('a'.codeUnitAt(0) + i)); + freq[i]--; + } + } + + freq = List.filled(26, 0); + + for (int i = 0; i < n; i++) { + freq[s2.codeUnitAt(i) - 'a'.codeUnitAt(0)]++; + } + + StringBuffer temp2 = StringBuffer(); + + for (int i = 25; i >= 0; i--) { + while (freq[i] > 0) { + temp2.write(String.fromCharCode('a'.codeUnitAt(0) + i)); + freq[i]--; + } + } + + String sorted1 = temp1.toString(); + String sorted2 = temp2.toString(); + + bool all1 = true; + bool all2 = true; + + for (int i = 0; i < n; i++) { + if (sorted1.codeUnitAt(i) < sorted2.codeUnitAt(i)) { + all1 = false; + } + if (sorted2.codeUnitAt(i) < sorted1.codeUnitAt(i)) { + all2 = false; + } + } + + return all1 || all2; + } +} diff --git a/tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.go b/tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.go new file mode 100644 index 00000000..6d9b1839 --- /dev/null +++ b/tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.go @@ -0,0 +1,49 @@ +func checkIfCanBreak(s1 string, s2 string) bool { + freq := make([]int, 26) + n := len(s1) + + for _, ch := range s1 { + freq[ch - 'a']++ + } + + temp1 := make([]byte, 0, n) + + for i := 25; i >= 0; i-- { + for freq[i] > 0 { + temp1 = append(temp1, byte('a' + i)) + freq[i]-- + } + } + + freq = make([]int, 26) + + for _, ch := range s2 { + freq[ch - 'a']++ + } + + temp2 := make([]byte, 0, n) + + for i := 25; i >= 0; i-- { + for freq[i] > 0 { + temp2 = append(temp2, byte('a' + i)) + freq[i]-- + } + } + + sorted1 := string(temp1) + sorted2 := string(temp2) + + all1 := true + all2 := true + + for i := 0; i < n; i++ { + if sorted1[i] < sorted2[i] { + all1 = false + } + if sorted2[i] < sorted1[i] { + all2 = false + } + } + + return all1 || all2 +} diff --git a/tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.java b/tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.java new file mode 100644 index 00000000..07c04812 --- /dev/null +++ b/tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.java @@ -0,0 +1,51 @@ +class Solution { + public boolean checkIfCanBreak(String s1, String s2) { + int[] freq = new int[26]; + int n = s1.length(); + + for (char ch : s1.toCharArray()) { + freq[ch - 'a']++; + } + + StringBuilder temp1 = new StringBuilder(); + + for (int i = 25; i >= 0; i--) { + while (freq[i] > 0) { + temp1.append((char)('a' + i)); + freq[i]--; + } + } + + freq = new int[26]; + + for (char ch : s2.toCharArray()) { + freq[ch - 'a']++; + } + + StringBuilder temp2 = new StringBuilder(); + + for (int i = 25; i >= 0; i--) { + while (freq[i] > 0) { + temp2.append((char)('a' + i)); + freq[i]--; + } + } + + String sorted1 = temp1.toString(); + String sorted2 = temp2.toString(); + + boolean all1 = true; + boolean all2 = true; + + for (int i = 0; i < n; i++) { + if (sorted1.charAt(i) < sorted2.charAt(i)) { + all1 = false; + } + if (sorted2.charAt(i) < sorted1.charAt(i)) { + all2 = false; + } + } + + return all1 || all2; + } +} diff --git a/tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.kt b/tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.kt new file mode 100644 index 00000000..089e4dd2 --- /dev/null +++ b/tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.kt @@ -0,0 +1,51 @@ +class Solution { + fun checkIfCanBreak(s1: String, s2: String): Boolean { + var freq = IntArray(26) + val n = s1.length + + for (ch in s1) { + freq[ch - 'a']++ + } + + val temp1 = StringBuilder() + + for (i in 25 downTo 0) { + while (freq[i] > 0) { + temp1.append(('a' + i)) + freq[i]-- + } + } + + freq = IntArray(26) + + for (ch in s2) { + freq[ch - 'a']++ + } + + val temp2 = StringBuilder() + + for (i in 25 downTo 0) { + while (freq[i] > 0) { + temp2.append(('a' + i)) + freq[i]-- + } + } + + val sorted1 = temp1.toString() + val sorted2 = temp2.toString() + + var all1 = true + var all2 = true + + for (i in 0 until n) { + if (sorted1[i] < sorted2[i]) { + all1 = false + } + if (sorted2[i] < sorted1[i]) { + all2 = false + } + } + + return all1 || all2 + } +} diff --git a/tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.py b/tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.py new file mode 100644 index 00000000..574bccd2 --- /dev/null +++ b/tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.py @@ -0,0 +1,38 @@ +class Solution: + def checkIfCanBreak(self, s1, s2): + + freq = [0] * 26 + n = len(s1) + + for ch in s1: + freq[ord(ch) - ord("a")] += 1 + + temp1 = [] + + for i in range(25, -1, -1): + while freq[i] > 0: + temp1.append(chr(ord("a") + i)) + freq[i] -= 1 + + freq = [0] * 26 + + for ch in s2: + freq[ord(ch) - ord("a")] += 1 + + temp2 = [] + + for i in range(25, -1, -1): + while freq[i] > 0: + temp2.append(chr(ord("a") + i)) + freq[i] -= 1 + + s1 = "".join(temp1) + s2 = "".join(temp2) + + if all(s1[i] >= s2[i] for i in range(n)): + return True + + if all(s2[i] >= s1[i] for i in range(n)): + return True + + return False diff --git a/tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.py2 b/tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.py2 new file mode 100644 index 00000000..676fea68 --- /dev/null +++ b/tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.py2 @@ -0,0 +1,42 @@ +class Solution(object): + def checkIfCanBreak(self, s1, s2): + """ + :type s1: str + :type s2: str + :rtype: bool + """ + freq = [0] * 26 + n = len(s1) + + for ch in s1: + freq[ord(ch) - ord('a')] += 1 + + temp1 = [] + + for i in range(25, -1, -1): + while freq[i] > 0: + temp1.append(chr(ord('a') + i)) + freq[i] -= 1 + + freq = [0] * 26 + + for ch in s2: + freq[ord(ch) - ord('a')] += 1 + + temp2 = [] + + for i in range(25, -1, -1): + while freq[i] > 0: + temp2.append(chr(ord('a') + i)) + freq[i] -= 1 + + s1 = "".join(temp1) + s2 = "".join(temp2) + + if all(s1[i] >= s2[i] for i in range(n)): + return True + + if all(s2[i] >= s1[i] for i in range(n)): + return True + + return False diff --git a/tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.rb b/tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.rb new file mode 100644 index 00000000..615959d0 --- /dev/null +++ b/tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.rb @@ -0,0 +1,43 @@ +# @param {String} s1 +# @param {String} s2 +# @return {Boolean} +def check_if_can_break(s1, s2) + freq = Array.new(26, 0) + n = s1.length + + s1.each_char do |ch| + freq[ch.ord - 'a'.ord] += 1 + end + + temp1 = [] + + 25.downto(0) do |i| + while freq[i] > 0 + temp1 << ('a'.ord + i).chr + freq[i] -= 1 + end + end + + freq = Array.new(26, 0) + + s2.each_char do |ch| + freq[ch.ord - 'a'.ord] += 1 + end + + temp2 = [] + + 25.downto(0) do |i| + while freq[i] > 0 + temp2 << ('a'.ord + i).chr + freq[i] -= 1 + end + end + + s1 = temp1.join + s2 = temp2.join + + return true if (0...n).all? { |i| s1[i] >= s2[i] } + return true if (0...n).all? { |i| s2[i] >= s1[i] } + + false +end diff --git a/tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.rs b/tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.rs new file mode 100644 index 00000000..f4a4784e --- /dev/null +++ b/tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.rs @@ -0,0 +1,51 @@ +impl Solution { + pub fn check_if_can_break(s1: String, s2: String) -> bool { + let mut freq = vec![0; 26]; + let n = s1.len(); + + for ch in s1.chars() { + freq[(ch as u8 - 'a' as u8) as usize] += 1; + } + + let mut temp1 = String::with_capacity(n); + + for i in (0..26).rev() { + while freq[i] > 0 { + temp1.push(('a' as u8 + i as u8) as char); + freq[i] -= 1; + } + } + + freq = vec![0; 26]; + + for ch in s2.chars() { + freq[(ch as u8 - 'a' as u8) as usize] += 1; + } + + let mut temp2 = String::with_capacity(n); + + for i in (0..26).rev() { + while freq[i] > 0 { + temp2.push(('a' as u8 + i as u8) as char); + freq[i] -= 1; + } + } + + let sorted1: Vec = temp1.chars().collect(); + let sorted2: Vec = temp2.chars().collect(); + + let mut all1 = true; + let mut all2 = true; + + for i in 0..n { + if sorted1[i] < sorted2[i] { + all1 = false; + } + if sorted2[i] < sorted1[i] { + all2 = false; + } + } + + all1 || all2 + } +} diff --git a/tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.swift b/tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.swift new file mode 100644 index 00000000..49bb2491 --- /dev/null +++ b/tests/1001-1500/1433. check-if-a-string-can-break-another-string/sol.swift @@ -0,0 +1,51 @@ +class Solution { + func checkIfCanBreak(_ s1: String, _ s2: String) -> Bool { + var freq = Array(repeating: 0, count: 26) + let n = s1.count + + for ch in s1 { + freq[Int(ch.asciiValue! - Character("a").asciiValue!)] += 1 + } + + var temp1 = "" + + for i in stride(from: 25, through: 0, by: -1) { + while freq[i] > 0 { + temp1.append(Character(UnicodeScalar(Character("a").asciiValue! + UInt8(i)))) + freq[i] -= 1 + } + } + + freq = Array(repeating: 0, count: 26) + + for ch in s2 { + freq[Int(ch.asciiValue! - Character("a").asciiValue!)] += 1 + } + + var temp2 = "" + + for i in stride(from: 25, through: 0, by: -1) { + while freq[i] > 0 { + temp2.append(Character(UnicodeScalar(Character("a").asciiValue! + UInt8(i)))) + freq[i] -= 1 + } + } + + let sorted1 = Array(temp1) + let sorted2 = Array(temp2) + + var all1 = true + var all2 = true + + for i in 0..= 0; i--) { + while (freq[i] > 0) { + temp1.push(String.fromCharCode("a".charCodeAt(0) + i)); + freq[i]--; + } + } + + freq = new Array(26).fill(0); + + for (let ch of s2) { + freq[ch.charCodeAt(0) - "a".charCodeAt(0)]++; + } + + let temp2: string[] = []; + + for (let i = 25; i >= 0; i--) { + while (freq[i] > 0) { + temp2.push(String.fromCharCode("a".charCodeAt(0) + i)); + freq[i]--; + } + } + + const sorted1 = temp1.join(""); + const sorted2 = temp2.join(""); + + let all1 = true; + let all2 = true; + + for (let i = 0; i < n; i++) { + if (sorted1[i] < sorted2[i]) { + all1 = false; + } + if (sorted2[i] < sorted1[i]) { + all2 = false; + } + } + + return all1 || all2; +} diff --git a/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/manifest.yaml b/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/manifest.yaml new file mode 100644 index 00000000..cd3c2b06 --- /dev/null +++ b/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/manifest.yaml @@ -0,0 +1,1061 @@ +entry: + id: 1434 + title: number-of-ways-to-wear-different-hats-to-each-other + params: + hats: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().numberWays({hats})" + rust: "Solution::number_ways({hats})" + python3: "Solution().numberWays({hats})" + python2: "Solution().numberWays({hats})" + ruby: "number_ways({hats})" + java: "new Solution().numberWays({hats})" + csharp: "new Solution().NumberWays({hats})" + kotlin: "Solution().numberWays({hats})" + go: "numberWays({hats})" + dart: "Solution().numberWays({hats})" + swift: "Solution().numberWays({hats})" + typescript: "numberWays({hats})" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().numberWays(hats, {result})" + checker: | + class Checker: + def numberWays(self, hats, result): + if type(result) is not int: + return False + n = len(hats) + if not 1 <= n <= 10: + return False + for choices in hats: + if not 1 <= len(choices) <= 40 or len(set(choices)) != len(choices): + return False + if any(hat < 1 or hat > 40 for hat in choices): + return False + mod = 1000000007 + liked_by_hat = [[] for _ in range(41)] + for person, choices in enumerate(hats): + for hat in choices: + liked_by_hat[hat].append(person) + dp = [0] * (1 << n) + dp[0] = 1 + for hat in range(1, 41): + updated = dp[:] + for mask, count in enumerate(dp): + if count: + for person in liked_by_hat[hat]: + bit = 1 << person + if not mask & bit: + updated[mask | bit] = (updated[mask | bit] + count) % mod + dp = updated + expected = dp[(1 << n) - 1] + return 0 <= result < mod and result == expected +seed: 1434 +tests: + - name: example-one + in: + hats: + - [3, 4] + - [4, 5] + - [5] + - name: example-two + in: + hats: + - [3, 5, 1] + - [3, 5] + - name: example-three + in: + hats: + - [1, 2, 3, 4] + - [1, 2, 3, 4] + - [1, 2, 3, 4] + - [1, 2, 3, 4] + - name: one-person-low + in: + hats: + - [1] + - name: one-person-high + in: + hats: + - [40] + - name: two-disjoint + in: + hats: + - [1] + - [2] + - name: two-impossible + in: + hats: + - [7] + - [7] + - name: two-all-pairs + in: + hats: + - [1, 2] + - [1, 2] + - name: two-separated + in: + hats: + - [2, 20, 40] + - [1, 20, 39] + - name: three-forced + in: + hats: + - [1] + - [2] + - [3] + - name: three-no-solution + in: + hats: + - [1] + - [1, 2] + - [1, 2] + - name: three-chain + in: + hats: + - [1, 2] + - [2, 3] + - [3, 4] + - name: three-high-chain + in: + hats: + - [38, 39] + - [39, 40] + - [37, 40] + - name: three-wide + seed: 143402 + in: + hats: + gen: "array" + len: 10 + of: + gen: "array" + len: + gen: "int" + min: 30 + max: 40 + of: + gen: "int" + min: 1 + max: 40 + distinct: true + - name: three-overlap + in: + hats: + - [1, 4, 7] + - [2, 4, 8] + - [3, 7, 8] + - name: four-disjoint + in: + hats: + - [1] + - [2] + - [3] + - [4] + - name: four-permutations + in: + hats: + - [1, 2, 3, 4] + - [1, 2, 3, 4] + - [1, 2, 3, 4] + - [1, 2, 3, 4] + - name: four-staggered + in: + hats: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - name: four-sparse + seed: 143401 + in: + hats: + gen: "array" + len: 10 + of: + gen: "array" + len: + gen: "int" + min: 30 + max: 40 + of: + gen: "int" + min: 1 + max: 40 + distinct: true + - name: four-forced-choice + in: + hats: + - [40] + - [39, 40] + - [38, 39] + - [37, 38] + - name: five-disjoint + in: + hats: + - [1] + - [2] + - [3] + - [4] + - [5] + - name: five-permutations + in: + hats: + - [1, 2, 3, 4, 5] + - [1, 2, 3, 4, 5] + - [1, 2, 3, 4, 5] + - [1, 2, 3, 4, 5] + - [1, 2, 3, 4, 5] + - name: five-chain + in: + hats: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - name: five-alternating + in: + hats: + - [1, 3, 5, 7] + - [2, 4, 6, 8] + - [1, 2, 5, 6] + - [3, 4, 7, 8] + - [1, 4, 8, 9] + - name: five-high + seed: 143403 + in: + hats: + gen: "array" + len: 10 + of: + gen: "array" + len: + gen: "int" + min: 30 + max: 40 + of: + gen: "int" + min: 1 + max: 40 + distinct: true + - name: six-disjoint + in: + hats: + - [1] + - [2] + - [3] + - [4] + - [5] + - [6] + - name: six-pairs + in: + hats: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - name: six-wide + seed: 143404 + in: + hats: + gen: "array" + len: 10 + of: + gen: "array" + len: + gen: "int" + min: 30 + max: 40 + of: + gen: "int" + min: 1 + max: 40 + distinct: true + - name: seven-disjoint + in: + hats: + - [1] + - [2] + - [3] + - [4] + - [5] + - [6] + - [7] + - name: seven-overlap + seed: 143405 + in: + hats: + gen: "array" + len: 10 + of: + gen: "array" + len: + gen: "int" + min: 30 + max: 40 + of: + gen: "int" + min: 1 + max: 40 + distinct: true + - name: eight-disjoint + in: + hats: + - [1] + - [2] + - [3] + - [4] + - [5] + - [6] + - [7] + - [8] + - name: eight-blocks + in: + hats: + - [1, 2, 3, 4] + - [1, 2, 3, 4] + - [5, 6, 7, 8] + - [5, 6, 7, 8] + - [9, 10, 11, 12] + - [9, 10, 11, 12] + - [13, 14, 15, 16] + - [13, 14, 15, 16] + - name: eight-sparse + seed: 143406 + in: + hats: + gen: "array" + len: 10 + of: + gen: "array" + len: + gen: "int" + min: 30 + max: 40 + of: + gen: "int" + min: 1 + max: 40 + distinct: true + - name: nine-disjoint + in: + hats: + - [1] + - [2] + - [3] + - [4] + - [5] + - [6] + - [7] + - [8] + - [9] + - name: nine-overlapping + in: + hats: + - [1, 2, 10] + - [2, 3, 11] + - [3, 4, 12] + - [4, 5, 13] + - [5, 6, 14] + - [6, 7, 15] + - [7, 8, 16] + - [8, 9, 17] + - [9, 10, 18] + - name: ten-disjoint + in: + hats: + - [1] + - [2] + - [3] + - [4] + - [5] + - [6] + - [7] + - [8] + - [9] + - [10] + - name: ten-permutations + in: + hats: + - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + - name: ten-wide-20 + in: + hats: + - [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + ] + - [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + ] + - [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + ] + - [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + ] + - [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + ] + - [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + ] + - [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + ] + - [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + ] + - [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + ] + - [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + ] + - name: ten-wide-40 + in: + hats: + - [ + 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, + ] + - [ + 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, + ] + - [ + 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, + ] + - [ + 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, + ] + - [ + 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, + ] + - [ + 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, + ] + - [ + 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, + ] + - [ + 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, + ] + - [ + 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, + ] + - [ + 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, + ] + - name: ten-shifted-boundary + in: + hats: + - [1, 11, 21, 31, 40] + - [2, 12, 22, 32, 40] + - [3, 13, 23, 33, 39] + - [4, 14, 24, 34, 39] + - [5, 15, 25, 35, 38] + - [6, 16, 26, 36, 38] + - [7, 17, 27, 37, 40] + - [8, 18, 28, 38, 39] + - [9, 19, 29, 39, 40] + - [10, 20, 30, 40] diff --git a/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.cpp b/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.cpp new file mode 100644 index 00000000..e9f2bd17 --- /dev/null +++ b/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + int numberWays(vector>& hats) { + const int MOD = 1'000'000'007; + int n = hats.size(); + vector> likedByHat(41); + for (int person = 0; person < n; person++) { + for (int hat : hats[person]) { + likedByHat[hat].push_back(person); + } + } + + vector dp(1 << n, 0); + dp[0] = 1; + for (int hat = 1; hat <= 40; hat++) { + vector updated = dp; + for (int mask = 0; mask < (1 << n); mask++) { + if (dp[mask] == 0) continue; + for (int person : likedByHat[hat]) { + int personBit = 1 << person; + if ((mask & personBit) == 0) { + int target = mask | personBit; + updated[target] = (updated[target] + dp[mask]) % MOD; + } + } + } + dp = updated; + } + return dp[(1 << n) - 1]; + } +}; diff --git a/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.cs b/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.cs new file mode 100644 index 00000000..7f01e712 --- /dev/null +++ b/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.cs @@ -0,0 +1,33 @@ +public class Solution { + public int NumberWays(IList> hats) { + const int MOD = 1_000_000_007; + int n = hats.Count; + List[] likedByHat = new List[41]; + for (int i = 1; i <= 40; i++) { + likedByHat[i] = new List(); + } + for (int person = 0; person < n; person++) { + foreach (int hat in hats[person]) { + likedByHat[hat].Add(person); + } + } + + int[] dp = new int[1 << n]; + dp[0] = 1; + for (int hat = 1; hat <= 40; hat++) { + int[] updated = (int[])dp.Clone(); + for (int mask = 0; mask < (1 << n); mask++) { + if (dp[mask] == 0) continue; + foreach (int person in likedByHat[hat]) { + int personBit = 1 << person; + if ((mask & personBit) == 0) { + int target = mask | personBit; + updated[target] = (updated[target] + dp[mask]) % MOD; + } + } + } + dp = updated; + } + return dp[(1 << n) - 1]; + } +} diff --git a/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.dart b/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.dart new file mode 100644 index 00000000..22f66760 --- /dev/null +++ b/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.dart @@ -0,0 +1,31 @@ +class Solution { + int numberWays(List> hats) { + const int mod = 1000000007; + int n = hats.length; + List> likedByHat = List.generate(41, (_) => []); + for (int person = 0; person < n; person++) { + for (int hat in hats[person]) { + likedByHat[hat].add(person); + } + } + + List dp = List.filled(1 << n, 0); + dp[0] = 1; + for (int hat = 1; hat <= 40; hat++) { + List updated = List.from(dp); + for (int mask = 0; mask < (1 << n); mask++) { + int count = dp[mask]; + if (count == 0) continue; + for (int person in likedByHat[hat]) { + int personBit = 1 << person; + if ((mask & personBit) == 0) { + int target = mask | personBit; + updated[target] = (updated[target] + count) % mod; + } + } + } + dp = updated; + } + return dp.last; + } +} diff --git a/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.go b/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.go new file mode 100644 index 00000000..e32a5eb6 --- /dev/null +++ b/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.go @@ -0,0 +1,34 @@ +func numberWays(hats [][]int) int { + const mod = 1_000_000_007 + n := len(hats) + likedByHat := make([][]int, 41) + for i := range likedByHat { + likedByHat[i] = []int{} + } + for person, choices := range hats { + for _, hat := range choices { + likedByHat[hat] = append(likedByHat[hat], person) + } + } + + dp := make([]int, 1<> people = new ArrayList<>(); + for (int[] choices : hats) { + List row = new ArrayList<>(choices.length); + for (int hat : choices) { + row.add(hat); + } + people.add(row); + } + return numberWays(people); + } + + public int numberWays(List> hats) { + final int MOD = 1_000_000_007; + int n = hats.size(); + List> likedByHat = new ArrayList<>(); + likedByHat.add(new ArrayList<>()); + for (int i = 1; i <= 40; i++) { + likedByHat.add(new ArrayList<>()); + } + for (int person = 0; person < n; person++) { + for (int hat : hats.get(person)) { + likedByHat.get(hat).add(person); + } + } + + int[] dp = new int[1 << n]; + dp[0] = 1; + for (int hat = 1; hat <= 40; hat++) { + int[] updated = dp.clone(); + for (int mask = 0; mask < (1 << n); mask++) { + if (dp[mask] == 0) continue; + for (int person : likedByHat.get(hat)) { + int personBit = 1 << person; + if ((mask & personBit) == 0) { + int target = mask | personBit; + updated[target] = (updated[target] + dp[mask]) % MOD; + } + } + } + dp = updated; + } + return dp[(1 << n) - 1]; + } +} diff --git a/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.kt b/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.kt new file mode 100644 index 00000000..185be788 --- /dev/null +++ b/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.kt @@ -0,0 +1,35 @@ +class Solution { + fun numberWays(hats: Array): Int { + return numberWays(hats.map { it.toList() }) + } + + fun numberWays(hats: List>): Int { + val mod = 1_000_000_007 + val n = hats.size + val likedByHat = Array(41) { mutableListOf() } + for (person in hats.indices) { + for (hat in hats[person]) { + likedByHat[hat].add(person) + } + } + + var dp = IntArray(1 shl n) + dp[0] = 1 + for (hat in 1..40) { + val updated = dp.clone() + for (mask in dp.indices) { + val count = dp[mask] + if (count == 0) continue + for (person in likedByHat[hat]) { + val personBit = 1 shl person + if (mask and personBit == 0) { + val target = mask or personBit + updated[target] = (updated[target] + count) % mod + } + } + } + dp = updated + } + return dp.last() + } +} diff --git a/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.py b/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.py new file mode 100644 index 00000000..4fb81dba --- /dev/null +++ b/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.py @@ -0,0 +1,26 @@ +from typing import List + + +class Solution: + def numberWays(self, hats: List[List[int]]) -> int: + mod = 10**9 + 7 + n = len(hats) + liked_by_hat = [[] for _ in range(41)] + for person, choices in enumerate(hats): + for hat in choices: + liked_by_hat[hat].append(person) + + dp = [0] * (1 << n) + dp[0] = 1 + for hat in range(1, 41): + updated = dp[:] + for mask, count in enumerate(dp): + if count == 0: + continue + for person in liked_by_hat[hat]: + person_bit = 1 << person + if mask & person_bit == 0: + target = mask | person_bit + updated[target] = (updated[target] + count) % mod + dp = updated + return dp[-1] diff --git a/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.py2 b/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.py2 new file mode 100644 index 00000000..307c4db3 --- /dev/null +++ b/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.py2 @@ -0,0 +1,27 @@ +class Solution(object): + def numberWays(self, hats): + """ + :type hats: List[List[int]] + :rtype: int + """ + mod = 10**9 + 7 + n = len(hats) + liked_by_hat = [[] for _ in range(41)] + for person, choices in enumerate(hats): + for hat in choices: + liked_by_hat[hat].append(person) + + dp = [0] * (1 << n) + dp[0] = 1 + for hat in range(1, 41): + updated = dp[:] + for mask, count in enumerate(dp): + if count == 0: + continue + for person in liked_by_hat[hat]: + person_bit = 1 << person + if mask & person_bit == 0: + target = mask | person_bit + updated[target] = (updated[target] + count) % mod + dp = updated + return dp[-1] diff --git a/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.rb b/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.rb new file mode 100644 index 00000000..59489f83 --- /dev/null +++ b/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.rb @@ -0,0 +1,30 @@ +# @param {Integer[][]} hats +# @return {Integer} +def number_ways(hats) + mod = 10**9 + 7 + n = hats.length + liked_by_hat = Array.new(41) { [] } + hats.each_with_index do |choices, person| + choices.each do |hat| + liked_by_hat[hat] << person + end + end + + dp = Array.new(1 << n, 0) + dp[0] = 1 + (1..40).each do |hat| + updated = dp.dup + dp.each_with_index do |count, mask| + next if count == 0 + liked_by_hat[hat].each do |person| + person_bit = 1 << person + if mask & person_bit == 0 + target = mask | person_bit + updated[target] = (updated[target] + count) % mod + end + end + end + dp = updated + end + dp[-1] +end diff --git a/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.rs b/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.rs new file mode 100644 index 00000000..010db77f --- /dev/null +++ b/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.rs @@ -0,0 +1,33 @@ +impl Solution { + pub fn number_ways(hats: Vec>) -> i32 { + const MOD: i32 = 1_000_000_007; + let n = hats.len(); + let mut liked_by_hat: Vec> = vec![vec![]; 41]; + for (person, choices) in hats.iter().enumerate() { + for &hat in choices { + liked_by_hat[hat as usize].push(person); + } + } + + let mut dp = vec![0; 1 << n]; + dp[0] = 1; + for hat in 1..=40 { + let mut updated = dp.clone(); + for mask in 0..(1 << n) { + let count = dp[mask]; + if count == 0 { + continue; + } + for &person in &liked_by_hat[hat] { + let person_bit = 1 << person; + if mask & person_bit == 0 { + let target = mask | person_bit; + updated[target] = (updated[target] + count) % MOD; + } + } + } + dp = updated; + } + dp[(1 << n) - 1] + } +} diff --git a/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.swift b/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.swift new file mode 100644 index 00000000..413fa9a7 --- /dev/null +++ b/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.swift @@ -0,0 +1,31 @@ +class Solution { + func numberWays(_ hats: [[Int]]) -> Int { + let mod = 1_000_000_007 + let n = hats.count + var likedByHat = [[Int]](repeating: [], count: 41) + for (person, choices) in hats.enumerated() { + for hat in choices { + likedByHat[hat].append(person) + } + } + + var dp = [Int](repeating: 0, count: 1 << n) + dp[0] = 1 + for hat in 1...40 { + var updated = dp + for mask in 0..<(1 << n) { + let count = dp[mask] + if count == 0 { continue } + for person in likedByHat[hat] { + let personBit = 1 << person + if mask & personBit == 0 { + let target = mask | personBit + updated[target] = (updated[target] + count) % mod + } + } + } + dp = updated + } + return dp[(1 << n) - 1] + } +} diff --git a/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.ts b/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.ts new file mode 100644 index 00000000..e02ccda7 --- /dev/null +++ b/tests/1001-1500/1434. number-of-ways-to-wear-different-hats-to-each-other/sol.ts @@ -0,0 +1,29 @@ +function numberWays(hats: number[][]): number { + const mod = 1_000_000_007; + const n = hats.length; + const likedByHat: number[][] = Array.from({ length: 41 }, () => []); + for (let person = 0; person < n; person++) { + for (const hat of hats[person]) { + likedByHat[hat].push(person); + } + } + + let dp: number[] = new Array(1 << n).fill(0); + dp[0] = 1; + for (let hat = 1; hat <= 40; hat++) { + const updated: number[] = [...dp]; + for (let mask = 0; mask < 1 << n; mask++) { + const count = dp[mask]; + if (count === 0) continue; + for (const person of likedByHat[hat]) { + const personBit = 1 << person; + if ((mask & personBit) === 0) { + const target = mask | personBit; + updated[target] = (updated[target] + count) % mod; + } + } + } + dp = updated; + } + return dp[(1 << n) - 1]; +} diff --git a/tests/1001-1500/1436. destination-city/manifest.yaml b/tests/1001-1500/1436. destination-city/manifest.yaml new file mode 100644 index 00000000..7f125b89 --- /dev/null +++ b/tests/1001-1500/1436. destination-city/manifest.yaml @@ -0,0 +1,527 @@ +entry: + id: 1436 + title: "destination-city" + params: + paths: + type: array + items: + type: array + items: + type: string + call: + cpp: "Solution().destCity({paths})" + rust: "Solution::dest_city({paths})" + python3: "Solution().destCity({paths})" + python2: "Solution().destCity({paths})" + ruby: "dest_city({paths})" + java: "new Solution().destCity({paths})" + csharp: "new Solution().DestCity({paths})" + kotlin: "Solution().destCity({paths})" + go: "destCity({paths})" + dart: "Solution().destCity({paths})" + swift: "Solution().destCity({paths})" + typescript: "destCity({paths})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().destCity(paths, {result})" + checker: | + class Checker: + def destCity(self, paths, result): + if not isinstance(result, str) or not isinstance(paths, list) or not paths: + return False + departures = set() + arrivals = set() + for path in paths: + if not isinstance(path, list) or len(path) != 2: + return False + source, target = path + if not isinstance(source, str) or not isinstance(target, str): + return False + departures.add(source) + arrivals.add(target) + candidates = arrivals - departures + return len(candidates) == 1 and result in candidates + +seed: 1436 + +tests: + - name: "example-one" + in: + paths: + elemType: "string" + value: + - ["London", "New York"] + - ["New York", "Lima"] + - ["Lima", "Sao Paulo"] + - name: "example-two" + in: + paths: + elemType: "string" + value: + - ["B", "C"] + - ["D", "B"] + - ["C", "A"] + - name: "example-three-single-edge" + in: + paths: + elemType: "string" + value: + - ["A", "Z"] + - name: "two-edge-chain" + in: + paths: + elemType: "string" + value: + - ["A", "B"] + - ["B", "C"] + - name: "three-edge-chain" + in: + paths: + elemType: "string" + value: + - ["A", "B"] + - ["B", "C"] + - ["C", "D"] + - name: "reverse-input-order" + in: + paths: + elemType: "string" + value: + - ["C", "D"] + - ["B", "C"] + - ["A", "B"] + - name: "destination-first-input" + in: + paths: + elemType: "string" + value: + - ["C", "D"] + - ["A", "B"] + - ["B", "C"] + - name: "middle-edge-first" + in: + paths: + elemType: "string" + value: + - ["B", "C"] + - ["C", "D"] + - ["A", "B"] + - name: "lowercase-preservation" + in: + paths: + elemType: "string" + value: + - ["east", "west"] + - ["west", "north"] + - name: "uppercase-preservation" + in: + paths: + elemType: "string" + value: + - ["NORTH", "SOUTH"] + - ["SOUTH", "EAST"] + - name: "mixed-case-labels" + in: + paths: + elemType: "string" + value: + - ["alpha", "Beta"] + - ["Beta", "GAMMA"] + - ["GAMMA", "delta"] + - name: "single-character-labels" + in: + paths: + elemType: "string" + value: + - ["x", "y"] + - ["y", "z"] + - ["z", "q"] + - name: "two-character-labels" + in: + paths: + elemType: "string" + value: + - ["AA", "BB"] + - ["BB", "CC"] + - ["CC", "DD"] + - name: "maximum-length-labels" + in: + paths: + elemType: "string" + value: + - ["Abcdefghij", "Klmno pqr"] + - ["Klmno pqr", "Stuvwxyz"] + - name: "leading-space-label" + in: + paths: + elemType: "string" + value: + - ["Old Town", "New Town"] + - ["New Town", "Final City"] + - name: "internal-space-labels" + in: + paths: + elemType: "string" + value: + - ["New York", "Los City"] + - ["Los City", "San Bay"] + - name: "long-space-chain" + in: + paths: + elemType: "string" + value: + - ["North Port", "Center Bay"] + - ["Center Bay", "South Bay"] + - ["South Bay", "Final Stop"] + - name: "destination-a" + in: + paths: + elemType: "string" + value: + - ["C", "A"] + - ["B", "C"] + - name: "destination-z" + in: + paths: + elemType: "string" + value: + - ["X", "Y"] + - ["Y", "Z"] + - name: "destination-with-space" + in: + paths: + elemType: "string" + value: + - ["Start", "The End"] + - name: "thirteen-edge-chain" + in: + paths: + elemType: "string" + value: + - ["A", "B"] + - ["B", "C"] + - ["C", "D"] + - ["D", "E"] + - ["E", "F"] + - ["F", "G"] + - ["G", "H"] + - ["H", "I"] + - ["I", "J"] + - ["J", "K"] + - ["K", "L"] + - ["L", "M"] + - ["M", "N"] + - name: "fourteen-edge-reversed" + in: + paths: + elemType: "string" + value: + - ["O", "N"] + - ["N", "M"] + - ["M", "L"] + - ["L", "K"] + - ["K", "J"] + - ["J", "I"] + - ["I", "H"] + - ["H", "G"] + - ["G", "F"] + - ["F", "E"] + - ["E", "D"] + - ["D", "C"] + - ["C", "B"] + - ["B", "A"] + - name: "four-edge-chain" + in: + paths: + elemType: "string" + value: + - ["P", "Q"] + - ["Q", "R"] + - ["R", "S"] + - ["S", "T"] + - name: "five-edge-shuffled" + in: + paths: + elemType: "string" + value: + - ["C", "D"] + - ["E", "F"] + - ["A", "B"] + - ["D", "E"] + - ["B", "C"] + - name: "six-edge-chain" + in: + paths: + elemType: "string" + value: + - ["A", "B"] + - ["B", "C"] + - ["C", "D"] + - ["D", "E"] + - ["E", "F"] + - ["F", "G"] + - name: "seven-edge-shuffled" + in: + paths: + elemType: "string" + value: + - ["C", "D"] + - ["F", "G"] + - ["A", "B"] + - ["E", "F"] + - ["B", "C"] + - ["D", "E"] + - ["G", "H"] + - name: "eight-edge-chain" + in: + paths: + elemType: "string" + value: + - ["A", "B"] + - ["B", "C"] + - ["C", "D"] + - ["D", "E"] + - ["E", "F"] + - ["F", "G"] + - ["G", "H"] + - ["H", "I"] + - name: "nine-edge-reversed" + in: + paths: + elemType: "string" + value: + - ["J", "I"] + - ["I", "H"] + - ["H", "G"] + - ["G", "F"] + - ["F", "E"] + - ["E", "D"] + - ["D", "C"] + - ["C", "B"] + - ["B", "A"] + - name: "ten-edge-chain" + in: + paths: + elemType: "string" + value: + - ["A", "B"] + - ["B", "C"] + - ["C", "D"] + - ["D", "E"] + - ["E", "F"] + - ["F", "G"] + - ["G", "H"] + - ["H", "I"] + - ["I", "J"] + - ["J", "K"] + - name: "city-name-collision-avoidance" + in: + paths: + elemType: "string" + value: + - ["A", "AA"] + - ["AA", "AAA"] + - name: "case-sensitive-distinctness" + in: + paths: + elemType: "string" + value: + - ["City", "city"] + - ["city", "Final"] + - name: "space-sensitive-distinctness" + in: + paths: + elemType: "string" + value: + - ["New City", "NewCity"] + - ["NewCity", "End City"] + - name: "destination-in-first-row" + in: + paths: + elemType: "string" + value: + - ["A", "Z"] + - ["B", "A"] + - ["C", "B"] + - name: "destination-in-last-row" + in: + paths: + elemType: "string" + value: + - ["A", "B"] + - ["B", "C"] + - ["C", "Z"] + - name: "mixed-order-four-edge" + in: + paths: + elemType: "string" + value: + - ["C", "D"] + - ["A", "B"] + - ["D", "E"] + - ["B", "C"] + - name: "mixed-order-seven-edge" + in: + paths: + elemType: "string" + value: + - ["E", "F"] + - ["A", "B"] + - ["G", "H"] + - ["C", "D"] + - ["F", "G"] + - ["B", "C"] + - ["D", "E"] + - name: "ten-character-spaced-destination" + in: + paths: + elemType: "string" + value: + - ["Start One", "End Point"] + - ["End Point", "Last Stop"] + - name: "eleven-edge-chain" + in: + paths: + elemType: "string" + value: + - ["A", "B"] + - ["B", "C"] + - ["C", "D"] + - ["D", "E"] + - ["E", "F"] + - ["F", "G"] + - ["G", "H"] + - ["H", "I"] + - ["I", "J"] + - ["J", "K"] + - ["K", "L"] + - name: "twelve-edge-shuffled" + in: + paths: + elemType: "string" + value: + - ["G", "H"] + - ["A", "B"] + - ["K", "L"] + - ["D", "E"] + - ["I", "J"] + - ["B", "C"] + - ["F", "G"] + - ["C", "D"] + - ["J", "K"] + - ["E", "F"] + - ["H", "I"] + - ["L", "M"] + - name: "maximal-hundred-edge-chain" + in: + paths: + elemType: "string" + value: + - ["A", "B"] + - ["B", "C"] + - ["C", "D"] + - ["D", "E"] + - ["E", "F"] + - ["F", "G"] + - ["G", "H"] + - ["H", "I"] + - ["I", "J"] + - ["J", "K"] + - ["K", "L"] + - ["L", "M"] + - ["M", "N"] + - ["N", "O"] + - ["O", "P"] + - ["P", "Q"] + - ["Q", "R"] + - ["R", "S"] + - ["S", "T"] + - ["T", "U"] + - ["U", "V"] + - ["V", "W"] + - ["W", "X"] + - ["X", "Y"] + - ["Y", "Z"] + - ["Z", "AA"] + - ["AA", "AB"] + - ["AB", "AC"] + - ["AC", "AD"] + - ["AD", "AE"] + - ["AE", "AF"] + - ["AF", "AG"] + - ["AG", "AH"] + - ["AH", "AI"] + - ["AI", "AJ"] + - ["AJ", "AK"] + - ["AK", "AL"] + - ["AL", "AM"] + - ["AM", "AN"] + - ["AN", "AO"] + - ["AO", "AP"] + - ["AP", "AQ"] + - ["AQ", "AR"] + - ["AR", "AS"] + - ["AS", "AT"] + - ["AT", "AU"] + - ["AU", "AV"] + - ["AV", "AW"] + - ["AW", "AX"] + - ["AX", "AY"] + - ["AY", "AZ"] + - ["AZ", "BA"] + - ["BA", "BB"] + - ["BB", "BC"] + - ["BC", "BD"] + - ["BD", "BE"] + - ["BE", "BF"] + - ["BF", "BG"] + - ["BG", "BH"] + - ["BH", "BI"] + - ["BI", "BJ"] + - ["BJ", "BK"] + - ["BK", "BL"] + - ["BL", "BM"] + - ["BM", "BN"] + - ["BN", "BO"] + - ["BO", "BP"] + - ["BP", "BQ"] + - ["BQ", "BR"] + - ["BR", "BS"] + - ["BS", "BT"] + - ["BT", "BU"] + - ["BU", "BV"] + - ["BV", "BW"] + - ["BW", "BX"] + - ["BX", "BY"] + - ["BY", "BZ"] + - ["BZ", "CA"] + - ["CA", "CB"] + - ["CB", "CC"] + - ["CC", "CD"] + - ["CD", "CE"] + - ["CE", "CF"] + - ["CF", "CG"] + - ["CG", "CH"] + - ["CH", "CI"] + - ["CI", "CJ"] + - ["CJ", "CK"] + - ["CK", "CL"] + - ["CL", "CM"] + - ["CM", "CN"] + - ["CN", "CO"] + - ["CO", "CP"] + - ["CP", "CQ"] + - ["CQ", "CR"] + - ["CR", "CS"] + - ["CS", "CT"] + - ["CT", "CU"] + - ["CU", "CV"] + - ["CV", "CW"] diff --git a/tests/1001-1500/1436. destination-city/sol.cpp b/tests/1001-1500/1436. destination-city/sol.cpp new file mode 100644 index 00000000..1ad1571c --- /dev/null +++ b/tests/1001-1500/1436. destination-city/sol.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + string destCity(vector>& paths) { + unordered_set startCities; + + for (const auto& path : paths) { + startCities.insert(path[0]); + } + + for (const auto& path : paths) { + if (startCities.find(path[1]) == startCities.end()) { + return path[1]; + } + } + + return ""; + } +}; diff --git a/tests/1001-1500/1436. destination-city/sol.cs b/tests/1001-1500/1436. destination-city/sol.cs new file mode 100644 index 00000000..37a61878 --- /dev/null +++ b/tests/1001-1500/1436. destination-city/sol.cs @@ -0,0 +1,17 @@ +public class Solution { + public string DestCity(IList> paths) { + HashSet startCities = new HashSet(); + + foreach (var path in paths) { + startCities.Add(path[0]); + } + + foreach (var path in paths) { + if (!startCities.Contains(path[1])) { + return path[1]; + } + } + + return ""; + } +} diff --git a/tests/1001-1500/1436. destination-city/sol.dart b/tests/1001-1500/1436. destination-city/sol.dart new file mode 100644 index 00000000..47f8020b --- /dev/null +++ b/tests/1001-1500/1436. destination-city/sol.dart @@ -0,0 +1,17 @@ +class Solution { + String destCity(List> paths) { + Set startCities = {}; + + for (var path in paths) { + startCities.add(path[0]); + } + + for (var path in paths) { + if (!startCities.contains(path[1])) { + return path[1]; + } + } + + return ""; + } +} diff --git a/tests/1001-1500/1436. destination-city/sol.go b/tests/1001-1500/1436. destination-city/sol.go new file mode 100644 index 00000000..7423a3be --- /dev/null +++ b/tests/1001-1500/1436. destination-city/sol.go @@ -0,0 +1,15 @@ +func destCity(paths [][]string) string { + startCities := make(map[string]bool) + + for _, path := range paths { + startCities[path[0]] = true + } + + for _, path := range paths { + if !startCities[path[1]] { + return path[1] + } + } + + return "" +} diff --git a/tests/1001-1500/1436. destination-city/sol.java b/tests/1001-1500/1436. destination-city/sol.java new file mode 100644 index 00000000..9ca20fea --- /dev/null +++ b/tests/1001-1500/1436. destination-city/sol.java @@ -0,0 +1,34 @@ +class Solution { + public String destCity(List> paths) { + Set startCities = new HashSet<>(); + + for (List path : paths) { + startCities.add(path.get(0)); + } + + for (List path : paths) { + if (!startCities.contains(path.get(1))) { + return path.get(1); + } + } + + return ""; + } + + // The local harness materializes nested arrays for this parameter. + public String destCity(String[][] paths) { + Set startCities = new HashSet<>(); + + for (String[] path : paths) { + startCities.add(path[0]); + } + + for (String[] path : paths) { + if (!startCities.contains(path[1])) { + return path[1]; + } + } + + return ""; + } +} diff --git a/tests/1001-1500/1436. destination-city/sol.kt b/tests/1001-1500/1436. destination-city/sol.kt new file mode 100644 index 00000000..d05481a7 --- /dev/null +++ b/tests/1001-1500/1436. destination-city/sol.kt @@ -0,0 +1,34 @@ +class Solution { + fun destCity(paths: List>): String { + val startCities = HashSet() + + for (path in paths) { + startCities.add(path[0]) + } + + for (path in paths) { + if (path[1] !in startCities) { + return path[1] + } + } + + return "" + } + + // The local harness materializes nested arrays for this parameter. + fun destCity(paths: Array>): String { + val startCities = HashSet() + + for (path in paths) { + startCities.add(path[0]) + } + + for (path in paths) { + if (path[1] !in startCities) { + return path[1] + } + } + + return "" + } +} diff --git a/tests/1001-1500/1436. destination-city/sol.py b/tests/1001-1500/1436. destination-city/sol.py new file mode 100644 index 00000000..24b74ed4 --- /dev/null +++ b/tests/1001-1500/1436. destination-city/sol.py @@ -0,0 +1,12 @@ +class Solution(object): + def destCity(self, paths): + start_cities = set() + + for path in paths: + start_cities.add(path[0]) + + for path in paths: + if path[1] not in start_cities: + return path[1] + + return "" diff --git a/tests/1001-1500/1436. destination-city/sol.py2 b/tests/1001-1500/1436. destination-city/sol.py2 new file mode 100644 index 00000000..2120f088 --- /dev/null +++ b/tests/1001-1500/1436. destination-city/sol.py2 @@ -0,0 +1,12 @@ +class Solution(object): + def destCity(self, paths): + start_cities = set() + + for path in paths: + start_cities.add(path[0]) + + for path in paths: + if path[1] not in start_cities: + return path[1] + + return "" diff --git a/tests/1001-1500/1436. destination-city/sol.rb b/tests/1001-1500/1436. destination-city/sol.rb new file mode 100644 index 00000000..a54e6f4c --- /dev/null +++ b/tests/1001-1500/1436. destination-city/sol.rb @@ -0,0 +1,15 @@ +# @param {String[][]} paths +# @return {String} +def dest_city(paths) + start_cities = Set.new + + paths.each do |path| + start_cities.add(path[0]) + end + + paths.each do |path| + return path[1] unless start_cities.include?(path[1]) + end + + "" +end diff --git a/tests/1001-1500/1436. destination-city/sol.rs b/tests/1001-1500/1436. destination-city/sol.rs new file mode 100644 index 00000000..433ec162 --- /dev/null +++ b/tests/1001-1500/1436. destination-city/sol.rs @@ -0,0 +1,19 @@ +impl Solution { + pub fn dest_city(paths: Vec>) -> String { + use std::collections::HashSet; + + let mut start_cities = HashSet::new(); + + for path in &paths { + start_cities.insert(&path[0]); + } + + for path in &paths { + if !start_cities.contains(&path[1]) { + return path[1].clone(); + } + } + + String::new() + } +} diff --git a/tests/1001-1500/1436. destination-city/sol.swift b/tests/1001-1500/1436. destination-city/sol.swift new file mode 100644 index 00000000..9b513d34 --- /dev/null +++ b/tests/1001-1500/1436. destination-city/sol.swift @@ -0,0 +1,17 @@ +class Solution { + func destCity(_ paths: [[String]]) -> String { + var startCities = Set() + + for path in paths { + startCities.insert(path[0]) + } + + for path in paths { + if !startCities.contains(path[1]) { + return path[1] + } + } + + return "" + } +} diff --git a/tests/1001-1500/1436. destination-city/sol.ts b/tests/1001-1500/1436. destination-city/sol.ts new file mode 100644 index 00000000..befbf34a --- /dev/null +++ b/tests/1001-1500/1436. destination-city/sol.ts @@ -0,0 +1,15 @@ +function destCity(paths: string[][]): string { + const startCities = new Set(); + + for (const path of paths) { + startCities.add(path[0]); + } + + for (const path of paths) { + if (!startCities.has(path[1])) { + return path[1]; + } + } + + return ""; +} diff --git a/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/manifest.yaml b/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/manifest.yaml new file mode 100644 index 00000000..9096e79d --- /dev/null +++ b/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/manifest.yaml @@ -0,0 +1,271 @@ +entry: + id: 1437 + title: "check-if-all-1s-are-at-least-length-k-places-away" + params: + nums: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().kLengthApart({nums}, {k})" + rust: "Solution::k_length_apart({nums}, {k})" + python3: "Solution().kLengthApart({nums}, {k})" + python2: "Solution().kLengthApart({nums}, {k})" + ruby: "k_length_apart({nums}, {k})" + java: "new Solution().kLengthApart({nums}, {k})" + csharp: "new Solution().KLengthApart({nums}, {k})" + kotlin: "Solution().kLengthApart({nums}, {k})" + go: "kLengthApart({nums}, {k})" + dart: "Solution().kLengthApart({nums}, {k})" + swift: "Solution().kLengthApart({nums}, {k})" + typescript: "kLengthApart({nums}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 700 + memory_mb: 256 + +oracle: + python3: + call: "Checker().kLengthApart(nums, k, {result})" + checker: | + class Checker: + def kLengthApart(self, nums, k, result): + one_positions = [i for i, value in enumerate(nums) if value == 1] + distances = [b - a for a, b in zip(one_positions, one_positions[1:])] + expected = not distances or min(distances) > k + return isinstance(result, bool) and result == expected + +seed: 1437 + +tests: + - name: "official-valid" + in: + nums: [1, 0, 0, 0, 1, 0, 0, 1] + k: 2 + - name: "official-invalid" + in: + nums: [1, 0, 0, 1, 0, 1] + k: 2 + - name: "single-one-zero-k" + in: + nums: [1] + k: 0 + - name: "single-one-maximum-k" + in: + nums: [1] + k: 1 + - name: "all-zeros-maximum-k" + in: + nums: [0, 0, 0, 0, 0] + k: 5 + - name: "adjacent-ones-k-zero" + in: + nums: [1, 1, 1, 1] + k: 0 + - name: "adjacent-ones-k-one" + in: + nums: [1, 1] + k: 1 + - name: "two-ones-exact-distance" + in: + nums: [1, 0, 1] + k: 2 + - name: "two-ones-one-beyond" + in: + nums: [1, 0, 0, 1] + k: 2 + - name: "two-ones-at-extremes" + in: + nums: [1, 0, 0, 0, 1] + k: 3 + - name: "alternating-k-one" + in: + nums: [1, 0, 1, 0, 1, 0, 1] + k: 1 + - name: "alternating-k-two" + in: + nums: [1, 0, 1, 0, 1, 0, 1] + k: 2 + - name: "early-violation" + in: + nums: [1, 0, 1, 0, 0, 0, 1] + k: 2 + - name: "late-violation" + in: + nums: [1, 0, 0, 0, 1, 0, 1] + k: 2 + - name: "three-evenly-spaced" + in: + nums: [1, 0, 0, 1, 0, 0, 1] + k: 2 + - name: "three-middle-violation" + in: + nums: [1, 0, 0, 1, 0, 1, 0, 0] + k: 2 + - name: "k-greater-than-all-distances" + in: + nums: [0, 1, 0, 0] + k: 4 + - name: "first-two-close-third-far" + in: + nums: [1, 0, 1, 0, 0, 0, 0, 1] + k: 2 + - name: "three-valid-with-leading-zero" + in: + nums: [0, 1, 0, 0, 1, 0, 0, 1] + k: 2 + - name: "zero-k-single-run" + in: + nums: [1, 1, 0, 0, 1] + k: 0 + - name: "positive-k-single-run" + in: + nums: [1, 1, 0, 0, 1] + k: 1 + - name: "six-zero-gap-boundary" + in: + nums: [1, 0, 0, 0, 0, 0, 0, 1] + k: 6 + - name: "six-zero-gap-extra" + in: + nums: [1, 0, 0, 0, 0, 0, 0, 1] + k: 5 + - name: "cluster-at-start" + in: + nums: [1, 1, 1, 0, 0, 0, 0] + k: 2 + - name: "cluster-at-end" + in: + nums: [0, 0, 0, 0, 1, 1, 1] + k: 1 + - name: "only-last-one" + in: + nums: [0, 0, 0, 0, 0, 1] + k: 6 + - name: "four-valid-spacing" + in: + nums: [1, 0, 0, 1, 0, 0, 1, 0, 0, 1] + k: 2 + - name: "four-invalid-final" + in: + nums: [1, 0, 0, 1, 0, 0, 1, 0, 1, 0] + k: 2 + - name: "mixed-valid-spacing" + in: + nums: [0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0] + k: 3 + - name: "mixed-invalid-spacing" + in: + nums: [0, 1, 0, 0, 1, 0, 0, 0, 1, 0] + k: 3 + - name: "large-k-invalid" + in: + nums: [1, 0, 0, 0, 0, 0, 0, 0, 0, 1] + k: 9 + - name: "large-k-valid" + in: + nums: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1] + k: 9 + - name: "alternating-long-one-k" + in: + nums: [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1] + k: 1 + - name: "alternating-long-two-k" + in: + nums: [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1] + k: 2 + - name: "boundary-single-zero" + in: + nums: [1, 0, 1] + k: 1 + - name: "generated-small-binary" + seed: 143701 + in: + nums: + gen: "array" + len: + gen: "int" + min: 1 + max: 40 + of: + gen: "int" + min: 0 + max: 1 + distinct: false + sorted: false + k: + gen: "int" + min: 0 + max: 1 + - name: "generated-medium-binary" + seed: 143702 + in: + nums: + gen: "array" + len: + gen: "int" + min: 50 + max: 300 + of: + gen: "int" + min: 0 + max: 1 + distinct: false + sorted: false + k: + gen: "int" + min: 0 + max: 50 + - name: "generated-large-binary" + seed: 143703 + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 0 + max: 1 + distinct: false + sorted: false + k: + gen: "int" + min: 0 + max: 100000 + - name: "generated-large-sparse-domain" + seed: 143704 + in: + nums: + gen: "array" + len: 99999 + of: + gen: "int" + min: 0 + max: 1 + distinct: false + sorted: false + k: + gen: "int" + min: 0 + max: 99999 + - name: "generated-singleton" + seed: 143705 + in: + nums: + gen: "array" + len: 1 + of: + gen: "int" + min: 0 + max: 1 + distinct: false + sorted: false + k: + gen: "int" + min: 0 + max: 1 diff --git a/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.cpp b/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.cpp new file mode 100644 index 00000000..1e96166b --- /dev/null +++ b/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + bool kLengthApart(vector& nums, int k) { + if (k == 0) { + return true; + } + int prev = -1; + for (int i = 0; i < nums.size(); i++) { + if (nums[i] == 1) { + if (prev != -1 && i - prev <= k) { + return false; + } + prev = i; + } + } + return true; + } +}; diff --git a/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.cs b/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.cs new file mode 100644 index 00000000..b1cbcd57 --- /dev/null +++ b/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.cs @@ -0,0 +1,17 @@ +public class Solution { + public bool KLengthApart(int[] nums, int k) { + if (k == 0) { + return true; + } + int? prev = null; + for (int i = 0; i < nums.Length; i++) { + if (nums[i] == 1) { + if (prev != null && i - prev.Value <= k) { + return false; + } + prev = i; + } + } + return true; + } +} diff --git a/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.dart b/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.dart new file mode 100644 index 00000000..5667ccbf --- /dev/null +++ b/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.dart @@ -0,0 +1,17 @@ +class Solution { + bool kLengthApart(List nums, int k) { + if (k == 0) { + return true; + } + int? prev; + for (int i = 0; i < nums.length; i++) { + if (nums[i] == 1) { + if (prev != null && i - prev <= k) { + return false; + } + prev = i; + } + } + return true; + } +} diff --git a/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.go b/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.go new file mode 100644 index 00000000..c2b91fbd --- /dev/null +++ b/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.go @@ -0,0 +1,15 @@ +func kLengthApart(nums []int, k int) bool { + if k == 0 { + return true + } + prev := -1 + for i, num := range nums { + if num == 1 { + if prev != -1 && i-prev <= k { + return false + } + prev = i + } + } + return true +} diff --git a/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.java b/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.java new file mode 100644 index 00000000..42fd9f7f --- /dev/null +++ b/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.java @@ -0,0 +1,17 @@ +class Solution { + public boolean kLengthApart(int[] nums, int k) { + if (k == 0) { + return true; + } + Integer prev = null; + for (int i = 0; i < nums.length; i++) { + if (nums[i] == 1) { + if (prev != null && i - prev <= k) { + return false; + } + prev = i; + } + } + return true; + } +} diff --git a/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.kt b/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.kt new file mode 100644 index 00000000..db185f20 --- /dev/null +++ b/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.kt @@ -0,0 +1,17 @@ +class Solution { + fun kLengthApart(nums: IntArray, k: Int): Boolean { + if (k == 0) { + return true + } + var prev: Int? = null + for (i in nums.indices) { + if (nums[i] == 1) { + if (prev != null && i - prev!! <= k) { + return false + } + prev = i + } + } + return true + } +} diff --git a/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.py b/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.py new file mode 100644 index 00000000..607f083f --- /dev/null +++ b/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.py @@ -0,0 +1,14 @@ +from typing import List + + +class Solution: + def kLengthApart(self, nums: List[int], k: int) -> bool: + if k == 0: + return True + prev = None + for i, num in enumerate(nums): + if num == 1: + if prev is not None and i - prev <= k: + return False + prev = i + return True diff --git a/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.py2 b/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.py2 new file mode 100644 index 00000000..07fa4af7 --- /dev/null +++ b/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def kLengthApart(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: bool + """ + if k == 0: + return True + prev = None + for i, num in enumerate(nums): + if num == 1: + if prev is not None and i - prev <= k: + return False + prev = i + return True diff --git a/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.rb b/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.rb new file mode 100644 index 00000000..f6ca7e0c --- /dev/null +++ b/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.rb @@ -0,0 +1,16 @@ +# @param {Integer[]} nums +# @param {Integer} k +# @return {Boolean} +def k_length_apart(nums, k) + return true if k == 0 + prev = nil + nums.each_with_index do |num, i| + if num == 1 + if prev != nil && i - prev <= k + return false + end + prev = i + end + end + true +end diff --git a/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.rs b/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.rs new file mode 100644 index 00000000..e3e7af86 --- /dev/null +++ b/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.rs @@ -0,0 +1,19 @@ +impl Solution { + pub fn k_length_apart(nums: Vec, k: i32) -> bool { + if k == 0 { + return true; + } + let mut prev: Option = None; + for (i, &num) in nums.iter().enumerate() { + if num == 1 { + if let Some(p) = prev { + if (i - p) as i32 <= k { + return false; + } + } + prev = Some(i); + } + } + true + } +} diff --git a/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.swift b/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.swift new file mode 100644 index 00000000..a6fc0d14 --- /dev/null +++ b/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.swift @@ -0,0 +1,17 @@ +class Solution { + func kLengthApart(_ nums: [Int], _ k: Int) -> Bool { + if k == 0 { + return true + } + var prev: Int? + for (i, num) in nums.enumerated() { + if num == 1 { + if let p = prev, i - p <= k { + return false + } + prev = i + } + } + return true + } +} diff --git a/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.ts b/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.ts new file mode 100644 index 00000000..737db1d9 --- /dev/null +++ b/tests/1001-1500/1437. check-if-all-1s-are-at-least-length-k-places-away/sol.ts @@ -0,0 +1,15 @@ +function kLengthApart(nums: number[], k: number): boolean { + if (k === 0) { + return true; + } + let prev: number | null = null; + for (let i = 0; i < nums.length; i++) { + if (nums[i] === 1) { + if (prev !== null && i - prev <= k) { + return false; + } + prev = i; + } + } + return true; +} diff --git a/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/manifest.yaml b/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/manifest.yaml new file mode 100644 index 00000000..324d6dc7 --- /dev/null +++ b/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/manifest.yaml @@ -0,0 +1,287 @@ +entry: + id: 1438 + title: "longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit" + params: + nums: + type: array + items: + type: int + limit: + type: int + call: + cpp: "Solution().longestSubarray({nums}, {limit})" + rust: "Solution::longest_subarray({nums}, {limit})" + python3: "Solution().longestSubarray({nums}, {limit})" + python2: "Solution().longestSubarray({nums}, {limit})" + ruby: "longest_subarray({nums}, {limit})" + java: "new Solution().longestSubarray({nums}, {limit})" + csharp: "new Solution().LongestSubarray({nums}, {limit})" + kotlin: "Solution().longestSubarray({nums}, {limit})" + go: "longestSubarray({nums}, {limit})" + dart: "Solution().longestSubarray({nums}, {limit})" + swift: "Solution().longestSubarray({nums}, {limit})" + typescript: "longestSubarray({nums}, {limit})" +judge: + type: exact +limits: + time_ms: 1000 + memory_mb: 300 +oracle: + python3: + call: "Checker().longestSubarray(nums, limit, {result})" + checker: | + import heapq + + class Checker: + def longestSubarray(self, nums, limit, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + min_heap = [] + max_heap = [] + left = 0 + best = 0 + for right, value in enumerate(nums): + heapq.heappush(min_heap, (value, right)) + heapq.heappush(max_heap, (-value, right)) + while -max_heap[0][0] - min_heap[0][0] > limit: + left += 1 + while min_heap[0][1] < left: + heapq.heappop(min_heap) + while max_heap[0][1] < left: + heapq.heappop(max_heap) + best = max(best, right - left + 1) + return result == best +seed: 1438 +tests: + - name: ex1 + in: + nums: [8, 2, 4, 7] + limit: 4 + out: 2 + - name: ex2 + in: + nums: [10, 1, 2, 4, 7, 2] + limit: 5 + out: 4 + - name: ex3 + in: + nums: [4, 2, 2, 2, 4, 4, 2, 2] + limit: 0 + out: 3 + - name: one + in: + nums: [5] + limit: 0 + out: 1 + - name: all_equal + in: + nums: [7, 7, 7, 7] + limit: 0 + out: 4 + - name: strict + in: + nums: [1, 2, 3, 4] + limit: 0 + - name: unlimited + in: + nums: [1, 100, 3, 50] + limit: 1000000000 + out: 4 + - name: adjacent + in: + nums: [1, 10, 1, 10] + limit: 0 + - name: alternating + in: + nums: [1, 3, 1, 3, 1] + limit: 2 + - name: increasing + in: + nums: [1, 2, 3, 4, 5, 6] + limit: 2 + - name: decreasing + in: + nums: [6, 5, 4, 3, 2, 1] + limit: 2 + - name: narrow_peak + in: + nums: [1, 2, 10, 2, 1] + limit: 1 + - name: narrow_valley + in: + nums: [10, 2, 1, 2, 10] + limit: 1 + - name: repeated_blocks + in: + nums: [4, 4, 5, 5, 6, 6] + limit: 1 + - name: high_values + in: + nums: [1000000000, 999999999, 1000000000] + limit: 1 + - name: low_limit + in: + nums: [2, 5, 2, 5, 2] + limit: 0 + - name: varied_a + in: + nums: [3, 8, 2, 7, 4, 6, 5] + limit: 3 + - name: varied_b + in: + nums: [10, 20, 15, 18, 12, 14] + limit: 5 + - name: varied_c + in: + nums: [1, 9, 2, 8, 3, 7, 4] + limit: 4 + - name: varied_d + in: + nums: [5, 1, 4, 2, 3, 9] + limit: 3 + - name: varied_e + in: + nums: [20, 18, 19, 17, 16, 15] + limit: 3 + - name: length_eight + in: + nums: [1, 5, 2, 4, 3, 7, 6, 8] + limit: 2 + - name: length_nine + in: + nums: [9, 1, 8, 2, 7, 3, 6, 4, 5] + limit: 3 + - name: length_ten + in: + nums: [1, 1, 5, 2, 2, 6, 3, 3, 7, 4] + limit: 1 + - name: length_eleven + in: + nums: [4, 6, 5, 7, 4, 6, 5, 7, 4, 6, 5] + limit: 2 + - name: length_twelve + in: + nums: [1, 4, 2, 5, 3, 6, 4, 7, 5, 8, 6, 9] + limit: 3 + - name: cluster_a + in: + nums: [1, 2, 1, 2, 10, 10, 10] + limit: 1 + - name: cluster_b + in: + nums: [10, 10, 1, 2, 1, 2, 10] + limit: 1 + - name: cluster_c + in: + nums: [5, 5, 5, 1, 1, 1, 5, 5] + limit: 0 + - name: boundary_a + in: + nums: [1, 100] + limit: 99 + - name: boundary_b + in: + nums: [1, 100] + limit: 98 + - name: boundary_c + in: + nums: [1000000000, 1, 1000000000] + limit: 999999999 + - name: final_a + in: + nums: [12, 3, 15, 6, 9, 18, 21] + limit: 6 + - name: final_b + in: + nums: [2, 8, 4, 6, 10, 12, 1] + limit: 4 + - name: final_c + in: + nums: [11, 2, 9, 4, 8, 3, 7, 5] + limit: 5 + - name: generated_small_random + seed: 143801 + in: + nums: + gen: "array" + len: + gen: "int" + min: 1 + max: 40 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + sorted: false + limit: + gen: "int" + min: 0 + max: 100 + - name: generated_medium_random + seed: 143802 + in: + nums: + gen: "array" + len: + gen: "int" + min: 200 + max: 1000 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + sorted: false + limit: + gen: "int" + min: 0 + max: 1000000000 + - name: generated_zero_limit + seed: 143803 + in: + nums: + gen: "array" + len: + gen: "int" + min: 1000 + max: 3000 + of: + gen: "int" + min: 1 + max: 5 + distinct: false + sorted: false + limit: 0 + - name: generated_large_random + seed: 143804 + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + sorted: false + limit: + gen: "int" + min: 0 + max: 1000000000 + - name: generated_large_tight_limit + seed: 143805 + in: + nums: + gen: "array" + len: 99999 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + sorted: false + limit: + gen: "int" + min: 0 + max: 10 diff --git a/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.cpp b/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.cpp new file mode 100644 index 00000000..15a49543 --- /dev/null +++ b/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int longestSubarray(vector& nums, int limit) { + deque maxq, minq; + int left = 0, max_len = 1; + for (int right = 0; right < nums.size(); ++right) { + while (!maxq.empty() && nums[maxq.back()] <= nums[right]) { + maxq.pop_back(); + } + maxq.push_back(right); + while (!minq.empty() && nums[minq.back()] >= nums[right]) { + minq.pop_back(); + } + minq.push_back(right); + while (nums[maxq.front()] - nums[minq.front()] > limit) { + ++left; + if (maxq.front() < left) { + maxq.pop_front(); + } + if (minq.front() < left) { + minq.pop_front(); + } + } + max_len = max(max_len, right - left + 1); + } + return max_len; + } +}; diff --git a/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.cs b/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.cs new file mode 100644 index 00000000..101f5110 --- /dev/null +++ b/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.cs @@ -0,0 +1,28 @@ +public class Solution { + public int LongestSubarray(int[] nums, int limit) { + var maxq = new LinkedList(); + var minq = new LinkedList(); + int left = 0, max_len = 1; + for (int right = 0; right < nums.Length; right++) { + while (maxq.Count > 0 && nums[maxq.Last.Value] <= nums[right]) { + maxq.RemoveLast(); + } + maxq.AddLast(right); + while (minq.Count > 0 && nums[minq.Last.Value] >= nums[right]) { + minq.RemoveLast(); + } + minq.AddLast(right); + while (nums[maxq.First.Value] - nums[minq.First.Value] > limit) { + left++; + if (maxq.First.Value < left) { + maxq.RemoveFirst(); + } + if (minq.First.Value < left) { + minq.RemoveFirst(); + } + } + max_len = Math.Max(max_len, right - left + 1); + } + return max_len; + } +} diff --git a/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.dart b/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.dart new file mode 100644 index 00000000..0d3184a3 --- /dev/null +++ b/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.dart @@ -0,0 +1,29 @@ +class Solution { + int longestSubarray(List nums, int limit) { + final maxq = Queue(); + final minq = Queue(); + int left = 0; + int max_len = 1; + for (int right = 0; right < nums.length; right++) { + while (maxq.isNotEmpty && nums[maxq.last] <= nums[right]) { + maxq.removeLast(); + } + maxq.addLast(right); + while (minq.isNotEmpty && nums[minq.last] >= nums[right]) { + minq.removeLast(); + } + minq.addLast(right); + while (nums[maxq.first] - nums[minq.first] > limit) { + left++; + if (maxq.first < left) { + maxq.removeFirst(); + } + if (minq.first < left) { + minq.removeFirst(); + } + } + max_len = max(max_len, right - left + 1); + } + return max_len; + } +} diff --git a/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.go b/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.go new file mode 100644 index 00000000..185b2d59 --- /dev/null +++ b/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.go @@ -0,0 +1,29 @@ +func longestSubarray(nums []int, limit int) int { + maxq := make([]int, 0) + minq := make([]int, 0) + left := 0 + max_len := 1 + for right := 0; right < len(nums); right++ { + for len(maxq) > 0 && nums[maxq[len(maxq)-1]] <= nums[right] { + maxq = maxq[:len(maxq)-1] + } + maxq = append(maxq, right) + for len(minq) > 0 && nums[minq[len(minq)-1]] >= nums[right] { + minq = minq[:len(minq)-1] + } + minq = append(minq, right) + for nums[maxq[0]]-nums[minq[0]] > limit { + left++ + if maxq[0] < left { + maxq = maxq[1:] + } + if minq[0] < left { + minq = minq[1:] + } + } + if right-left+1 > max_len { + max_len = right - left + 1 + } + } + return max_len +} diff --git a/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.java b/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.java new file mode 100644 index 00000000..fa6d572d --- /dev/null +++ b/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.java @@ -0,0 +1,29 @@ +class Solution { + public int longestSubarray(int[] nums, int limit) { + java.util.Deque maxq = new java.util.ArrayDeque<>(); + java.util.Deque minq = new java.util.ArrayDeque<>(); + int left = 0; + int max_len = 1; + for (int right = 0; right < nums.length; right++) { + while (!maxq.isEmpty() && nums[maxq.peekLast()] <= nums[right]) { + maxq.pollLast(); + } + maxq.offerLast(right); + while (!minq.isEmpty() && nums[minq.peekLast()] >= nums[right]) { + minq.pollLast(); + } + minq.offerLast(right); + while (nums[maxq.peekFirst()] - nums[minq.peekFirst()] > limit) { + left++; + if (maxq.peekFirst() < left) { + maxq.pollFirst(); + } + if (minq.peekFirst() < left) { + minq.pollFirst(); + } + } + max_len = Math.max(max_len, right - left + 1); + } + return max_len; + } +} diff --git a/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.kt b/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.kt new file mode 100644 index 00000000..5c981408 --- /dev/null +++ b/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.kt @@ -0,0 +1,29 @@ +class Solution { + fun longestSubarray(nums: IntArray, limit: Int): Int { + val maxq = ArrayDeque() + val minq = ArrayDeque() + var left = 0 + var max_len = 1 + for (right in nums.indices) { + while (maxq.isNotEmpty() && nums[maxq.last()] <= nums[right]) { + maxq.removeLast() + } + maxq.addLast(right) + while (minq.isNotEmpty() && nums[minq.last()] >= nums[right]) { + minq.removeLast() + } + minq.addLast(right) + while (nums[maxq.first()] - nums[minq.first()] > limit) { + left++ + if (maxq.first() < left) { + maxq.removeFirst() + } + if (minq.first() < left) { + minq.removeFirst() + } + } + max_len = maxOf(max_len, right - left + 1) + } + return max_len + } +} diff --git a/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.py b/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.py new file mode 100644 index 00000000..138c551e --- /dev/null +++ b/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.py @@ -0,0 +1,54 @@ +from collections import deque +from typing import List + + +class Solution: + def longestSubarray(self, nums: List[int], limit: int) -> int: + maxq = deque() + minq = deque() + + left = 0 + max_len = 1 + + for right in range(len(nums)): + while maxq and nums[maxq[-1]] <= nums[right]: + # print("right", right, "nums[maxq[-1]]", nums[maxq[-1]], "nums[right]", nums[right]) + maxq.pop() + maxq.append(right) + # print("maxq: ",maxq) + + while minq and nums[minq[-1]] >= nums[right]: + minq.pop() + minq.append(right) + + while nums[maxq[0]] - nums[minq[0]] > limit: + left += 1 + + if maxq[0] < left: + maxq.popleft() + if minq[0] < left: + minq.popleft() + + max_len = max(max_len, right - left + 1) + + return max_len + + # Will give TLE for finding max and min + + # max_len = 1 + # max_v = -1 + # min_v = float(inf) + + # left = 0 + + # for right in range(len(nums)): + # max_v = max(nums[left:right+1]) + # min_v = min(nums[left:right+1]) + + # while max_v-min_v > limit and left<=right: + # left+=1 + # max_v = max(nums[left:right+1]) + # min_v = min(nums[left:right+1]) + + # max_len = max(max_len, right-left+1) + # return max_len diff --git a/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.py2 b/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.py2 new file mode 100644 index 00000000..210204db --- /dev/null +++ b/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.py2 @@ -0,0 +1,27 @@ +from collections import deque +class Solution(object): + def longestSubarray(self, nums, limit): + """ + :type nums: List[int] + :type limit: int + :rtype: int + """ + maxq = deque() + minq = deque() + left = 0 + max_len = 1 + for right in range(len(nums)): + while maxq and nums[maxq[-1]] <= nums[right]: + maxq.pop() + maxq.append(right) + while minq and nums[minq[-1]] >= nums[right]: + minq.pop() + minq.append(right) + while nums[maxq[0]] - nums[minq[0]] > limit: + left += 1 + if maxq[0] < left: + maxq.popleft() + if minq[0] < left: + minq.popleft() + max_len = max(max_len, right - left + 1) + return max_len diff --git a/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.rb b/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.rb new file mode 100644 index 00000000..0a71245c --- /dev/null +++ b/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.rb @@ -0,0 +1,26 @@ +# @param {Integer[]} nums +# @param {Integer} limit +# @return {Integer} +def longest_subarray(nums, limit) + maxq = [] + minq = [] + left = 0 + max_len = 1 + nums.each_with_index do |num, right| + while !maxq.empty? && nums[maxq.last] <= num + maxq.pop + end + maxq.push(right) + while !minq.empty? && nums[minq.last] >= num + minq.pop + end + minq.push(right) + while nums[maxq.first] - nums[minq.first] > limit + left += 1 + maxq.shift if maxq.first < left + minq.shift if minq.first < left + end + max_len = [max_len, right - left + 1].max + end + max_len +end diff --git a/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.rs b/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.rs new file mode 100644 index 00000000..ff394308 --- /dev/null +++ b/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.rs @@ -0,0 +1,37 @@ +impl Solution { + pub fn longest_subarray(nums: Vec, limit: i32) -> i32 { + let mut maxq: std::collections::VecDeque = std::collections::VecDeque::new(); + let mut minq: std::collections::VecDeque = std::collections::VecDeque::new(); + let mut left = 0; + let mut max_len = 1; + for right in 0..nums.len() { + while let Some(&back) = maxq.back() { + if nums[back] <= nums[right] { + maxq.pop_back(); + } else { + break; + } + } + maxq.push_back(right); + while let Some(&back) = minq.back() { + if nums[back] >= nums[right] { + minq.pop_back(); + } else { + break; + } + } + minq.push_back(right); + while nums[*maxq.front().unwrap()] - nums[*minq.front().unwrap()] > limit { + left += 1; + if *maxq.front().unwrap() < left { + maxq.pop_front(); + } + if *minq.front().unwrap() < left { + minq.pop_front(); + } + } + max_len = max_len.max((right - left + 1) as i32); + } + max_len + } +} diff --git a/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.swift b/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.swift new file mode 100644 index 00000000..f20f8f3f --- /dev/null +++ b/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.swift @@ -0,0 +1,29 @@ +class Solution { + func longestSubarray(_ nums: [Int], _ limit: Int) -> Int { + var maxq = [Int]() + var minq = [Int]() + var left = 0 + var max_len = 1 + for right in 0..= nums[right] { + minq.removeLast() + } + minq.append(right) + while nums[maxq.first!] - nums[minq.first!] > limit { + left += 1 + if maxq.first! < left { + maxq.removeFirst() + } + if minq.first! < left { + minq.removeFirst() + } + } + max_len = max(max_len, right - left + 1) + } + return max_len + } +} diff --git a/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.ts b/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.ts new file mode 100644 index 00000000..9613265e --- /dev/null +++ b/tests/1001-1500/1438. longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/sol.ts @@ -0,0 +1,27 @@ +function longestSubarray(nums: number[], limit: number): number { + const maxq: number[] = []; + const minq: number[] = []; + let left = 0; + let max_len = 1; + for (let right = 0; right < nums.length; right++) { + while (maxq.length > 0 && nums[maxq[maxq.length - 1]] <= nums[right]) { + maxq.pop(); + } + maxq.push(right); + while (minq.length > 0 && nums[minq[minq.length - 1]] >= nums[right]) { + minq.pop(); + } + minq.push(right); + while (nums[maxq[0]] - nums[minq[0]] > limit) { + left++; + if (maxq[0] < left) { + maxq.shift(); + } + if (minq[0] < left) { + minq.shift(); + } + } + max_len = Math.max(max_len, right - left + 1); + } + return max_len; +} diff --git a/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/manifest.yaml b/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/manifest.yaml new file mode 100644 index 00000000..765d1022 --- /dev/null +++ b/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/manifest.yaml @@ -0,0 +1,592 @@ +entry: + id: 1439 + title: "find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows" + params: + mat: + type: array + items: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().kthSmallest({mat}, {k})" + rust: "Solution::kth_smallest({mat}, {k})" + python3: "Solution().kthSmallest({mat}, {k})" + python2: "Solution().kthSmallest({mat}, {k})" + ruby: "kth_smallest({mat}, {k})" + java: "new Solution().kthSmallest({mat}, {k})" + csharp: "new Solution().KthSmallest({mat}, {k})" + kotlin: "Solution().kthSmallest({mat}, {k})" + go: "kthSmallest({mat}, {k})" + dart: "Solution().kthSmallest({mat}, {k})" + swift: "Solution().kthSmallest({mat}, {k})" + typescript: "kthSmallest({mat}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().kthSmallest(mat, k, {result})" + checker: | + class Checker: + def kthSmallest(self, mat, k, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + sums = [0] + for row in mat: + sums = sorted(a + b for a in sums for b in row)[:k] + return 1 <= k <= len(sums) and result == sums[k - 1] + +seed: 1439 + +tests: + - name: "example_one" + in: + mat: + elemType: "int" + value: + - [1, 3, 11] + - [2, 4, 6] + k: 5 + - name: "example_two_last_sum" + in: + mat: + elemType: "int" + value: + - [1, 3, 11] + - [2, 4, 6] + k: 9 + - name: "example_three" + in: + mat: + elemType: "int" + value: + - [1, 10, 10] + - [1, 4, 5] + - [2, 3, 6] + k: 7 + - name: "two_by_two_first" + in: + mat: + elemType: "int" + value: + - [1, 2] + - [3, 4] + k: 1 + - name: "two_by_two_last" + in: + mat: + elemType: "int" + value: + - [1, 2] + - [3, 4] + k: 4 + - name: "duplicate_sums" + in: + mat: + elemType: "int" + value: + - [1, 2, 3] + - [1, 2, 3] + k: 5 + - name: "all_equal" + in: + mat: + elemType: "int" + value: + - [7, 7] + - [7, 7] + - [7, 7] + k: 8 + - name: "single_column" + in: + mat: + elemType: "int" + value: + - [5] + - [12] + - [100] + k: 1 + - name: "single_row_many_choices" + in: + mat: + elemType: "int" + value: + - [1, 5, 9, 20, 50] + k: 4 + - name: "wide_two_rows" + in: + mat: + elemType: "int" + value: + - [1, 2, 4, 8, 16, 32] + - [3, 5, 7, 11, 13, 17] + k: 12 + - name: "three_rows_ties" + in: + mat: + elemType: "int" + value: + - [1, 1, 2] + - [2, 2, 8] + - [3, 4, 4] + k: 6 + - name: "three_rows_k_one" + in: + mat: + elemType: "int" + value: + - [2, 20, 30] + - [1, 9, 10] + - [4, 5, 100] + k: 1 + - name: "three_rows_k_two_hundred_bound" + in: + mat: + elemType: "int" + value: + - [1, 2, 3, 4, 5] + - [10, 11, 12, 13, 14] + - [20, 21, 22, 23, 24] + - [30, 31, 32, 33, 34] + k: 125 + - name: "large_values_min" + in: + mat: + elemType: "int" + value: + - [1, 4999] + - [1, 4999] + k: 1 + - name: "large_values_max" + in: + mat: + elemType: "int" + value: + - [4998, 5000] + - [4997, 5000] + k: 4 + - name: "four_by_three" + in: + mat: + elemType: "int" + value: + - [1, 4, 8] + - [2, 3, 9] + - [1, 6, 7] + - [5, 5, 10] + k: 10 + - name: "five_by_two" + in: + mat: + elemType: "int" + value: + - [1, 100] + - [2, 90] + - [3, 80] + - [4, 70] + - [5, 60] + k: 16 + - name: "six_by_four" + in: + mat: + elemType: "int" + value: + - [1, 2, 10, 20] + - [2, 3, 11, 21] + - [3, 4, 12, 22] + - [4, 5, 13, 23] + - [5, 6, 14, 24] + - [6, 7, 15, 25] + k: 64 + - name: "nonuniform_gaps" + in: + mat: + elemType: "int" + value: + - [3, 100, 101] + - [4, 5, 1000] + - [1, 50, 500] + k: 8 + - name: "many_equal_prefixes" + in: + mat: + elemType: "int" + value: + - [2, 2, 2, 100] + - [3, 3, 4, 100] + - [1, 1, 9, 10] + k: 20 + - name: "ten_rows_two_choices" + in: + mat: + elemType: "int" + value: + - [1, 100] + - [2, 99] + - [3, 98] + - [4, 97] + - [5, 96] + - [6, 95] + - [7, 94] + - [8, 93] + - [9, 92] + - [10, 91] + k: 200 + - name: "ten_rows_three_choices" + in: + mat: + elemType: "int" + value: + - [1, 2, 20] + - [2, 3, 21] + - [3, 4, 22] + - [4, 5, 23] + - [5, 6, 24] + - [6, 7, 25] + - [7, 8, 26] + - [8, 9, 27] + - [9, 10, 28] + - [10, 11, 29] + k: 200 + - name: "twenty_rows_two_choices" + in: + mat: + elemType: "int" + value: + - [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] + k: 200 + - name: "generated_small_sorted_rows" + seed: 101 + in: + mat: + gen: "array" + len: 4 + of: + gen: "array" + len: 5 + sorted: true + of: + gen: "int" + min: 1 + max: 30 + k: 37 + - name: "generated_medium_rows" + seed: 202 + in: + mat: + gen: "array" + len: 8 + of: + gen: "array" + len: 7 + sorted: true + of: + gen: "int" + min: 1 + max: 500 + k: 200 + - name: "generated_duplicate_heavy" + seed: 303 + in: + mat: + gen: "array" + len: 12 + of: + gen: "array" + len: 4 + sorted: true + of: + gen: "int" + min: 1 + max: 8 + k: 150 + - name: "generated_maximum_dimensions" + seed: 404 + in: + mat: + gen: "array" + len: 40 + of: + gen: "array" + len: 40 + sorted: true + of: + gen: "int" + min: 1 + max: 5000 + k: 200 + - name: "generated_maximum_dimensions_offset" + seed: 505 + in: + mat: + gen: "array" + len: 40 + of: + gen: "array" + len: 39 + sorted: true + of: + gen: "int" + min: 100 + max: 5000 + k: 199 + - name: "two_rows_repeated_minimum" + in: + mat: + elemType: "int" + value: + - [1, 1, 1, 9] + - [2, 2, 8, 8] + k: 6 + - name: "two_rows_high_spread" + in: + mat: + elemType: "int" + value: + - [10, 100, 1000, 5000] + - [20, 200, 2000, 4000] + k: 7 + - name: "three_rows_all_minimum_choices" + in: + mat: + elemType: "int" + value: + - [1, 40] + - [2, 50] + - [3, 60] + k: 1 + - name: "three_rows_all_maximum_choices" + in: + mat: + elemType: "int" + value: + - [1, 40] + - [2, 50] + - [3, 60] + k: 8 + - name: "four_rows_duplicate_columns" + in: + mat: + elemType: "int" + value: + - [2, 2, 5] + - [1, 3, 3] + - [4, 4, 9] + - [2, 6, 7] + k: 18 + - name: "five_rows_balanced" + in: + mat: + elemType: "int" + value: + - [1, 3, 5, 7] + - [2, 4, 6, 8] + - [1, 2, 9, 10] + - [3, 5, 7, 11] + - [2, 6, 8, 12] + k: 50 + - name: "seven_rows_single_choice_variants" + in: + mat: + elemType: "int" + value: + - [1, 5] + - [1, 6] + - [1, 7] + - [1, 8] + - [1, 9] + - [1, 10] + - [1, 11] + k: 64 + - name: "boundary_value_mix" + in: + mat: + elemType: "int" + value: + - [1, 2500, 5000] + - [1, 2499, 5000] + - [2, 2501, 4999] + - [3, 2502, 4998] + k: 40 + - name: "maximum_width_two_rows" + 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, + ] + - [ + 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, + 58, + 60, + 62, + 64, + 66, + 68, + 70, + 72, + 74, + 76, + 78, + 80, + ] + k: 200 + - name: "forty_rows_single_column" + 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] + k: 1 + - name: "maximum_value_duplicate_frontier" + in: + mat: + elemType: "int" + value: + - [4998, 4999, 5000] + - [4998, 4999, 5000] + - [4998, 4999, 5000] + - [4998, 4999, 5000] + k: 80 + - name: "small_rows_with_crossing_gaps" + in: + mat: + elemType: "int" + value: + - [1, 100, 101, 102] + - [2, 3, 200, 201] + - [4, 50, 51, 500] + k: 13 diff --git a/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.cpp b/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.cpp new file mode 100644 index 00000000..73c8acf8 --- /dev/null +++ b/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int kthSmallest(vector>& mat, int k) { + vector sums(mat[0].begin(), mat[0].begin() + min((int)mat[0].size(), k)); + for (int i = 1; i < mat.size(); ++i) { + vector row = mat[i]; + int limit = min((int)row.size(), k); + vector next; + next.reserve(sums.size() * limit); + for (int a : sums) { + for (int j = 0; j < limit; ++j) { + next.push_back(a + row[j]); + } + } + sort(next.begin(), next.end()); + if (next.size() > k) next.resize(k); + sums = move(next); + } + return sums[k - 1]; + } +}; diff --git a/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.cs b/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.cs new file mode 100644 index 00000000..6ebbcfcc --- /dev/null +++ b/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.cs @@ -0,0 +1,18 @@ +public class Solution { + public int KthSmallest(int[][] mat, int k) { + int[] sums = mat[0].Take(k).ToArray(); + for (int i = 1; i < mat.Length; i++) { + int[] row = mat[i].Take(k).ToArray(); + int[] next = new int[sums.Length * row.Length]; + int idx = 0; + foreach (int a in sums) { + foreach (int b in row) { + next[idx++] = a + b; + } + } + Array.Sort(next); + sums = next.Take(k).ToArray(); + } + return sums[k - 1]; + } +} diff --git a/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.dart b/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.dart new file mode 100644 index 00000000..c279f9e6 --- /dev/null +++ b/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.dart @@ -0,0 +1,17 @@ +class Solution { + int kthSmallest(List> mat, int k) { + List sums = mat[0].take(k).toList(); + for (int i = 1; i < mat.length; i++) { + List row = mat[i].take(k).toList(); + List next = []; + for (int a in sums) { + for (int b in row) { + next.add(a + b); + } + } + next.sort(); + sums = next.take(k).toList(); + } + return sums[k - 1]; + } +} diff --git a/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.go b/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.go new file mode 100644 index 00000000..bc8116b0 --- /dev/null +++ b/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.go @@ -0,0 +1,21 @@ +func kthSmallest(mat [][]int, k int) int { + sums := make([]int, 0) + for i := 0; i < len(mat[0]) && i < k; i++ { + sums = append(sums, mat[0][i]) + } + for r := 1; r < len(mat); r++ { + row := mat[r] + next := make([]int, 0) + for _, a := range sums { + for j := 0; j < len(row) && j < k; j++ { + next = append(next, a + row[j]) + } + } + sort.Ints(next) + if len(next) > k { + next = next[:k] + } + sums = next + } + return sums[k-1] +} diff --git a/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.java b/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.java new file mode 100644 index 00000000..ca47041a --- /dev/null +++ b/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.java @@ -0,0 +1,19 @@ +class Solution { + public int kthSmallest(int[][] mat, int k) { + int[] sums = java.util.Arrays.copyOf(mat[0], Math.min(mat[0].length, k)); + for (int i = 1; i < mat.length; i++) { + int[] row = mat[i]; + int limit = Math.min(row.length, k); + int[] next = new int[sums.length * limit]; + int idx = 0; + for (int a : sums) { + for (int j = 0; j < limit; j++) { + next[idx++] = a + row[j]; + } + } + java.util.Arrays.sort(next); + sums = java.util.Arrays.copyOf(next, Math.min(k, next.length)); + } + return sums[k - 1]; + } +} diff --git a/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.kt b/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.kt new file mode 100644 index 00000000..868a4417 --- /dev/null +++ b/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.kt @@ -0,0 +1,17 @@ +class Solution { + fun kthSmallest(mat: Array, k: Int): Int { + var sums = mat[0].take(k).toIntArray() + for (i in 1 until mat.size) { + val row = mat[i].take(k) + val next = mutableListOf() + for (a in sums) { + for (b in row) { + next.add(a + b) + } + } + next.sort() + sums = next.take(k).toIntArray() + } + return sums[k - 1] + } +} diff --git a/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.py b/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.py new file mode 100644 index 00000000..77f8acaa --- /dev/null +++ b/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.py @@ -0,0 +1,9 @@ +from typing import List + + +class Solution: + def kthSmallest(self, mat: List[List[int]], k: int) -> int: + sums = mat[0][:k] + for row in mat[1:]: + sums = sorted(a + b for a in sums for b in row[:k])[:k] + return sums[k - 1] diff --git a/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.py2 b/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.py2 new file mode 100644 index 00000000..e52d6a07 --- /dev/null +++ b/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.py2 @@ -0,0 +1,11 @@ +class Solution(object): + def kthSmallest(self, mat, k): + """ + :type mat: List[List[int]] + :type k: int + :rtype: int + """ + sums = mat[0][:k] + for row in mat[1:]: + sums = sorted(a + b for a in sums for b in row[:k])[:k] + return sums[k - 1] diff --git a/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.rb b/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.rb new file mode 100644 index 00000000..9e4d9c1f --- /dev/null +++ b/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.rb @@ -0,0 +1,11 @@ +# @param {Integer[][]} mat +# @param {Integer} k +# @return {Integer} +def kth_smallest(mat, k) + sums = mat[0].first(k) + mat[1..].each do |row| + row_k = row.first(k) + sums = sums.flat_map { |a| row_k.map { |b| a + b } }.sort.first(k) + end + sums[k - 1] +end diff --git a/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.rs b/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.rs new file mode 100644 index 00000000..6b2da67b --- /dev/null +++ b/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.rs @@ -0,0 +1,19 @@ +impl Solution { + pub fn kth_smallest(mat: Vec>, k: i32) -> i32 { + let k = k as usize; + let mut sums: Vec = mat[0].iter().take(k).cloned().collect(); + for row in mat.iter().skip(1) { + let row_k: Vec = row.iter().take(k).cloned().collect(); + let mut next: Vec = Vec::with_capacity(sums.len() * row_k.len()); + for &a in &sums { + for &b in &row_k { + next.push(a + b); + } + } + next.sort_unstable(); + next.truncate(k); + sums = next; + } + sums[k - 1] + } +} diff --git a/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.swift b/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.swift new file mode 100644 index 00000000..13444545 --- /dev/null +++ b/tests/1001-1500/1439. find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/sol.swift @@ -0,0 +1,17 @@ +class Solution { + func kthSmallest(_ mat: [[Int]], _ k: Int) -> Int { + var sums = Array(mat[0].prefix(k)) + for i in 1.. x - y); + sums = next.slice(0, k); + } + return sums[k - 1]; +} diff --git a/tests/1001-1500/1441. build-an-array-with-stack-operations/manifest.yaml b/tests/1001-1500/1441. build-an-array-with-stack-operations/manifest.yaml new file mode 100644 index 00000000..4f242967 --- /dev/null +++ b/tests/1001-1500/1441. build-an-array-with-stack-operations/manifest.yaml @@ -0,0 +1,374 @@ +entry: + id: 1441 + title: build-an-array-with-stack-operations + params: + target: + type: array + items: + type: int + n: + type: int + call: + cpp: "Solution().buildArray({target}, {n})" + rust: "Solution::build_array({target}, {n})" + python3: "Solution().buildArray({target}, {n})" + python2: "Solution().buildArray({target}, {n})" + ruby: "build_array({target}, {n})" + java: "new Solution().buildArray({target}, {n})" + csharp: "new Solution().BuildArray({target}, {n})" + kotlin: "Solution().buildArray({target}, {n})" + go: "buildArray({target}, {n})" + dart: "Solution().buildArray({target}, {n})" + swift: "Solution().buildArray({target}, {n})" + typescript: "buildArray({target}, {n})" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().buildArray(target, n, {result})" + checker: | + class Checker: + def buildArray(self, target, n, result): + if not isinstance(target, list) or not isinstance(n, int): + return False + if not isinstance(result, list) or any(op not in ("Push", "Pop") for op in result): + return False + stack = [] + operation = 0 + for value in range(1, n + 1): + if stack == target: + return operation == len(result) + if operation >= len(result) or result[operation] != "Push": + return False + operation += 1 + stack.append(value) + if len(stack) > len(target) or stack[-1] != target[len(stack) - 1]: + if operation >= len(result) or result[operation] != "Pop": + return False + operation += 1 + stack.pop() + return stack == target and operation == len(result) +seed: 1441 +tests: + - name: singleton-first + in: + target: [1] + n: 1 + - name: singleton-second + in: + target: [2] + n: 2 + - name: singleton-middle + in: + target: [4] + n: 7 + - name: singleton-maximum + in: + target: [100] + n: 100 + - name: first-two + in: + target: [1, 2] + n: 2 + - name: first-three + in: + target: [1, 2, 3] + n: 5 + - name: prompt-example + in: + target: [1, 3] + n: 3 + - name: sparse-two + in: + target: [2, 3] + n: 3 + - name: last-two + in: + target: [6, 7] + n: 7 + - name: alternating-five + in: + target: [1, 3, 5] + n: 5 + - name: alternating-even + in: + target: [2, 4, 6] + n: 6 + - name: odd-seven + in: + target: [1, 3, 5, 7] + n: 7 + - name: full-five + in: + target: [1, 2, 3, 4, 5] + n: 5 + - name: sparse-five + in: + target: [2, 4, 5] + n: 5 + - name: late-prefix + in: + target: [6, 7, 8] + n: 8 + - name: prefix-six + in: + target: [1, 2, 3, 4, 5, 6] + n: 6 + - name: sparse-six + in: + target: [1, 3, 6] + n: 6 + - name: even-seven + in: + target: [2, 4, 6] + n: 7 + - name: odd-eight + in: + target: [1, 3, 5, 7] + n: 8 + - name: full-eight + in: + target: [1, 2, 3, 4, 5, 6, 7, 8] + n: 8 + - name: sparse-nine + in: + target: [2, 5, 9] + n: 9 + - name: near-prefix-ten + in: + target: [1, 2, 3, 4, 5, 6, 7, 8, 9] + n: 10 + - name: tail-ten + in: + target: [8, 9, 10] + n: 10 + - name: alternating-ten + in: + target: [1, 3, 5, 7, 9] + n: 10 + - name: even-twelve + in: + target: [2, 4, 6, 8, 10, 12] + n: 12 + - name: mixed-twelve + in: + target: [1, 4, 5, 9, 12] + n: 12 + - name: prefix-fifteen + in: + target: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + n: 15 + - name: sparse-fifteen + in: + target: [3, 7, 11, 15] + n: 15 + - name: odd-twenty + in: + target: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] + n: 20 + - name: tail-twenty + in: + target: [16, 17, 18, 19, 20] + n: 20 + - name: mixed-twenty + in: + target: [2, 3, 6, 10, 14, 20] + n: 20 + - name: boundary-gaps + in: + target: [1, 50, 100] + n: 100 + - name: maximum-dense + in: + target: + [ + 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, + ] + n: 100 + - name: maximum-sparse + in: + target: [1, 25, 50, 75, 100] + n: 100 + - name: maximum-tail + in: + target: [96, 97, 98, 99, 100] + n: 100 + - name: generated-short + in: + target: + gen: array + len: + gen: int + min: 1 + max: 8 + of: + gen: int + min: 1 + max: 100 + distinct: true + sorted: true + elemType: int + n: 100 + - name: generated-medium + in: + target: + gen: array + len: + gen: int + min: 10 + max: 30 + of: + gen: int + min: 1 + max: 100 + distinct: true + sorted: true + elemType: int + n: 100 + - name: generated-wide + in: + target: + gen: array + len: + gen: int + min: 40 + max: 60 + of: + gen: int + min: 1 + max: 100 + distinct: true + sorted: true + elemType: int + n: 100 + - name: generated-near-maximum + in: + target: + gen: array + len: + gen: int + min: 90 + max: 99 + of: + gen: int + min: 1 + max: 100 + distinct: true + sorted: true + elemType: int + n: 100 + - name: generated-maximum + in: + target: + gen: array + len: 100 + of: + gen: int + min: 1 + max: 100 + distinct: true + sorted: true + elemType: int + n: 100 diff --git a/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.cpp b/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.cpp new file mode 100644 index 00000000..3c2d83bc --- /dev/null +++ b/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + vector buildArray(vector& target, int n) { + vector s; + vector res; + int a = 0; + for (int i = 1; i <= n; i++) { + if (s == target) return res; + s.push_back(i); + res.push_back("Push"); + if (s[a] != target[a]) { + s.pop_back(); + res.push_back("Pop"); + } else { + a++; + } + } + return res; + } +}; diff --git a/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.cs b/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.cs new file mode 100644 index 00000000..e2cc95eb --- /dev/null +++ b/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.cs @@ -0,0 +1,19 @@ +public class Solution { + public IList BuildArray(int[] target, int n) { + List s = new List(); + List res = new List(); + int a = 0; + for (int i = 1; i <= n; i++) { + if (s.SequenceEqual(target)) return res; + s.Add(i); + res.Add("Push"); + if (s[a] != target[a]) { + s.RemoveAt(s.Count - 1); + res.Add("Pop"); + } else { + a++; + } + } + return res; + } +} diff --git a/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.dart b/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.dart new file mode 100644 index 00000000..df260cbe --- /dev/null +++ b/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.dart @@ -0,0 +1,28 @@ +class Solution { + List buildArray(List target, int n) { + List s = []; + List res = []; + int a = 0; + for (int i = 1; i <= n; i++) { + bool equal = s.length == target.length; + if (equal) { + for (int j = 0; j < s.length; j++) { + if (s[j] != target[j]) { + equal = false; + break; + } + } + } + if (equal) return res; + s.add(i); + res.add("Push"); + if (s[a] != target[a]) { + s.removeLast(); + res.add("Pop"); + } else { + a++; + } + } + return res; + } +} diff --git a/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.go b/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.go new file mode 100644 index 00000000..e9af3da5 --- /dev/null +++ b/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.go @@ -0,0 +1,28 @@ +func buildArray(target []int, n int) []string { + s := []int{} + res := []string{} + a := 0 + for i := 1; i <= n; i++ { + if len(s) == len(target) { + match := true + for j := 0; j < len(s); j++ { + if s[j] != target[j] { + match = false + break + } + } + if match { + return res + } + } + s = append(s, i) + res = append(res, "Push") + if s[a] != target[a] { + s = s[:len(s)-1] + res = append(res, "Pop") + } else { + a++ + } + } + return res +} diff --git a/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.java b/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.java new file mode 100644 index 00000000..b03c1ef2 --- /dev/null +++ b/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.java @@ -0,0 +1,19 @@ +class Solution { + public List buildArray(int[] target, int n) { + List res = new ArrayList<>(); + int a = 0; + List s = new ArrayList<>(); + for (int i = 1; i <= n; i++) { + if (s.size() == target.length && a == target.length) return res; + s.add(i); + res.add("Push"); + if (s.get(a) != target[a]) { + s.remove(s.size() - 1); + res.add("Pop"); + } else { + a++; + } + } + return res; + } +} diff --git a/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.kt b/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.kt new file mode 100644 index 00000000..6f86066c --- /dev/null +++ b/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.kt @@ -0,0 +1,19 @@ +class Solution { + fun buildArray(target: IntArray, n: Int): List { + val res = mutableListOf() + val s = mutableListOf() + var a = 0 + for (i in 1..n) { + if (s == target.toList()) return res + s.add(i) + res.add("Push") + if (s[a] != target[a]) { + s.removeAt(s.size - 1) + res.add("Pop") + } else { + a++ + } + } + return res + } +} diff --git a/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.py b/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.py new file mode 100644 index 00000000..b0a8fb96 --- /dev/null +++ b/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.py @@ -0,0 +1,16 @@ +class Solution(object): + def buildArray(self, target, n): + s = [] + res = [] + a = 0 + for i in range(1, n + 1): + if s == target: + return res + s.append(i) + res.append("Push") + if s[a] != target[a]: + s.pop() + res.append("Pop") + else: + a = a + 1 + return res diff --git a/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.py2 b/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.py2 new file mode 100644 index 00000000..49d2c81c --- /dev/null +++ b/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def buildArray(self, target, n): + s=[] + res=[] + a=0 + for i in range(1,n+1): + if s==target: + return res + s.append(i) + res.append("Push") + if s[a]!=target[a]: + s.pop() + res.append("Pop") + else: + a=a+1 + return res diff --git a/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.rb b/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.rb new file mode 100644 index 00000000..696dd87a --- /dev/null +++ b/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.rb @@ -0,0 +1,20 @@ +# @param {Integer[]} target +# @param {Integer} n +# @return {String[]} +def build_array(target, n) + s = [] + res = [] + a = 0 + (1..n).each do |i| + return res if s == target + s.push(i) + res.push("Push") + if s[a] != target[a] + s.pop + res.push("Pop") + else + a += 1 + end + end + res +end diff --git a/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.rs b/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.rs new file mode 100644 index 00000000..27f2de45 --- /dev/null +++ b/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.rs @@ -0,0 +1,21 @@ +impl Solution { + pub fn build_array(target: Vec, n: i32) -> Vec { + let mut s: Vec = Vec::new(); + let mut res: Vec = Vec::new(); + let mut a = 0; + for i in 1..=n { + if s == target { + return res; + } + s.push(i); + res.push("Push".to_string()); + if s[a] != target[a] { + s.pop(); + res.push("Pop".to_string()); + } else { + a += 1; + } + } + res + } +} diff --git a/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.swift b/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.swift new file mode 100644 index 00000000..ca10bbde --- /dev/null +++ b/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.swift @@ -0,0 +1,21 @@ +class Solution { + func buildArray(_ target: [Int], _ n: Int) -> [String] { + var s: [Int] = [] + var res: [String] = [] + var a = 0 + for i in 1...n { + if s == target { + return res + } + s.append(i) + res.append("Push") + if s[a] != target[a] { + s.removeLast() + res.append("Pop") + } else { + a += 1 + } + } + return res + } +} diff --git a/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.ts b/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.ts new file mode 100644 index 00000000..a4f4d6bf --- /dev/null +++ b/tests/1001-1500/1441. build-an-array-with-stack-operations/sol.ts @@ -0,0 +1,19 @@ +function buildArray(target: number[], n: number): string[] { + const s: number[] = []; + const res: string[] = []; + let a = 0; + for (let i = 1; i <= n; i++) { + if (s.length === target.length && s.every((v, idx) => v === target[idx])) { + return res; + } + s.push(i); + res.push("Push"); + if (s[a] !== target[a]) { + s.pop(); + res.push("Pop"); + } else { + a++; + } + } + return res; +} diff --git a/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/manifest.yaml b/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/manifest.yaml new file mode 100644 index 00000000..2bd6a6f4 --- /dev/null +++ b/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/manifest.yaml @@ -0,0 +1,207 @@ +entry: + id: 1442 + title: "count-triplets-that-can-form-two-arrays-of-equal-xor" + params: + arr: + type: array + items: + type: int + call: + cpp: "Solution().countTriplets({arr})" + rust: "Solution::count_triplets({arr})" + python3: "Solution().countTriplets({arr})" + python2: "Solution().countTriplets({arr})" + ruby: "count_triplets({arr})" + java: "new Solution().countTriplets({arr})" + csharp: "new Solution().CountTriplets({arr})" + kotlin: "Solution().countTriplets({arr})" + go: "countTriplets({arr})" + dart: "Solution().countTriplets({arr})" + swift: "Solution().countTriplets({arr})" + typescript: "countTriplets({arr})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().countTriplets(arr, {result})" + checker: | + class Checker: + def countTriplets(self, arr, result): + expected = 0 + for i in range(len(arr) - 1): + left_xor = 0 + for j in range(i, len(arr) - 1): + left_xor ^= arr[j] + right_xor = 0 + for k in range(j + 1, len(arr)): + right_xor ^= arr[k] + if left_xor == right_xor: + expected += 1 + return isinstance(result, int) and not isinstance(result, bool) and result == expected + +seed: 1442 + +tests: + - name: "example-one" + in: + arr: [2, 3, 1, 6, 7] + out: 4 + - name: "example-two" + in: + arr: [1, 1, 1, 1, 1] + out: 10 + - name: "single" + in: + arr: [1] + - name: "two-distinct" + in: + arr: [1, 2] + - name: "two-equal" + in: + arr: [7, 7] + - name: "three-equal" + in: + arr: [5, 5, 5] + - name: "all-ones-six" + in: + arr: [1, 1, 1, 1, 1, 1] + - name: "zero-xor-pair" + in: + arr: [2, 2, 3] + - name: "zero-xor-triple" + in: + arr: [4, 4, 4] + - name: "powers-of-two" + in: + arr: [1, 2, 4, 8] + - name: "repeated-powers" + in: + arr: [1, 2, 1, 2, 1, 2] + - name: "alternating" + in: + arr: [3, 5, 3, 5, 3] + - name: "nested-zero-xors" + in: + arr: [1, 1, 2, 2, 3, 3] + - name: "no-equal-xor" + in: + arr: [1, 2, 4] + - name: "single-zero-xor-total" + in: + arr: [1, 2, 3] + - name: "mixed-small" + in: + arr: [6, 4, 2, 7, 5] + - name: "mixed-medium" + in: + arr: [10, 15, 6, 3, 12, 9] + - name: "large-values" + in: + arr: [100000000, 100000000, 1] + - name: "large-xor-pattern" + in: + arr: [99999999, 99999998, 99999997, 99999996] + - name: "palindromic-values" + in: + arr: [8, 3, 5, 3, 8] + - name: "four-equal" + in: + arr: [9, 9, 9, 9] + - name: "five-equal" + in: + arr: [12, 12, 12, 12, 12] + - name: "six-equal" + in: + arr: [100, 100, 100, 100, 100, 100] + - name: "pair-blocks" + in: + arr: [1, 1, 2, 2, 4, 4, 8, 8] + - name: "xor-cancellation" + in: + arr: [7, 3, 4, 7, 3, 4] + - name: "odd-length-pattern" + in: + arr: [2, 7, 5, 2, 7, 5, 2] + - name: "even-length-pattern" + in: + arr: [11, 6, 13, 11, 6, 13] + - name: "ascending" + in: + arr: [1, 2, 3, 4, 5, 6, 7, 8] + - name: "descending" + in: + arr: [8, 7, 6, 5, 4, 3, 2, 1] + - name: "alternating-large" + in: + arr: [100000000, 1, 100000000, 1, 100000000] + - name: "ten-ones" + in: + arr: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - name: "ten-mixed" + in: + arr: [1, 2, 3, 1, 2, 3, 4, 5, 4, 5] + - name: "twelve-pairs" + in: + arr: [6, 6, 9, 9, 12, 12, 15, 15, 18, 18, 21, 21] + - name: "fifteen-pattern" + in: + arr: [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9] + - name: "sixteen-repeating-blocks" + in: + arr: [2, 4, 6, 2, 4, 6, 8, 10, 12, 8, 10, 12, 1, 1, 1, 1] + - name: "generated-small-positive" + seed: 144201 + in: + arr: + gen: "array" + len: 17 + of: + gen: "int" + min: 1 + max: 100000000 + - name: "generated-medium-positive" + seed: 144202 + in: + arr: + gen: "array" + len: 61 + of: + gen: "int" + min: 1 + max: 100000000 + - name: "generated-large-100" + seed: 144203 + in: + arr: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 100000000 + - name: "generated-large-299" + seed: 144204 + in: + arr: + gen: "array" + len: 299 + of: + gen: "int" + min: 1 + max: 100000000 + - name: "generated-maximum-300" + seed: 144205 + in: + arr: + gen: "array" + len: 300 + of: + gen: "int" + min: 1 + max: 100000000 diff --git a/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.cpp b/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.cpp new file mode 100644 index 00000000..b968d66d --- /dev/null +++ b/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int countTriplets(vector& arr) { + int totalCount = 0; + int prefixXor = 0; + unordered_map prefixCount; + unordered_map indexSum; + prefixCount[0] = 1; + indexSum[0] = 0; + for (int k = 1; k <= arr.size(); k++) { + prefixXor ^= arr[k - 1]; + if (prefixCount.find(prefixXor) != prefixCount.end()) { + totalCount += prefixCount[prefixXor] * (k - 1) - indexSum[prefixXor]; + } else { + prefixCount[prefixXor] = 0; + indexSum[prefixXor] = 0; + } + prefixCount[prefixXor]++; + indexSum[prefixXor] += k; + } + return totalCount; + } +}; diff --git a/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.cs b/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.cs new file mode 100644 index 00000000..0a1c8018 --- /dev/null +++ b/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.cs @@ -0,0 +1,22 @@ +public class Solution { + public int CountTriplets(int[] arr) { + int totalCount = 0; + int prefixXor = 0; + var prefixCount = new System.Collections.Generic.Dictionary(); + var indexSum = new System.Collections.Generic.Dictionary(); + prefixCount[0] = 1; + indexSum[0] = 0; + for (int k = 1; k <= arr.Length; k++) { + prefixXor ^= arr[k - 1]; + if (prefixCount.ContainsKey(prefixXor)) { + totalCount += prefixCount[prefixXor] * (k - 1) - indexSum[prefixXor]; + } else { + prefixCount[prefixXor] = 0; + indexSum[prefixXor] = 0; + } + prefixCount[prefixXor]++; + indexSum[prefixXor] += k; + } + return totalCount; + } +} diff --git a/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.dart b/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.dart new file mode 100644 index 00000000..d4559adc --- /dev/null +++ b/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.dart @@ -0,0 +1,20 @@ +class Solution { + int countTriplets(List arr) { + int totalCount = 0; + int prefixXor = 0; + Map prefixCount = {0: 1}; + Map indexSum = {0: 0}; + for (int k = 1; k <= arr.length; k++) { + prefixXor ^= arr[k - 1]; + if (prefixCount.containsKey(prefixXor)) { + totalCount += prefixCount[prefixXor]! * (k - 1) - indexSum[prefixXor]!; + } else { + prefixCount[prefixXor] = 0; + indexSum[prefixXor] = 0; + } + prefixCount[prefixXor] = prefixCount[prefixXor]! + 1; + indexSum[prefixXor] = indexSum[prefixXor]! + k; + } + return totalCount; + } +} diff --git a/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.go b/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.go new file mode 100644 index 00000000..501c8df1 --- /dev/null +++ b/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.go @@ -0,0 +1,18 @@ +func countTriplets(arr []int) int { + totalCount := 0 + prefixXor := 0 + prefixCount := map[int]int{0: 1} + indexSum := map[int]int{0: 0} + for k := 1; k <= len(arr); k++ { + prefixXor ^= arr[k-1] + if cnt, ok := prefixCount[prefixXor]; ok { + totalCount += cnt*(k-1) - indexSum[prefixXor] + } else { + prefixCount[prefixXor] = 0 + indexSum[prefixXor] = 0 + } + prefixCount[prefixXor]++ + indexSum[prefixXor] += k + } + return totalCount +} diff --git a/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.java b/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.java new file mode 100644 index 00000000..28a4f489 --- /dev/null +++ b/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.java @@ -0,0 +1,22 @@ +class Solution { + public int countTriplets(int[] arr) { + int totalCount = 0; + int prefixXor = 0; + java.util.Map prefixCount = new java.util.HashMap<>(); + java.util.Map indexSum = new java.util.HashMap<>(); + prefixCount.put(0, 1); + indexSum.put(0, 0); + for (int k = 1; k <= arr.length; k++) { + prefixXor ^= arr[k - 1]; + if (prefixCount.containsKey(prefixXor)) { + totalCount += prefixCount.get(prefixXor) * (k - 1) - indexSum.get(prefixXor); + } else { + prefixCount.put(prefixXor, 0); + indexSum.put(prefixXor, 0); + } + prefixCount.put(prefixXor, prefixCount.get(prefixXor) + 1); + indexSum.put(prefixXor, indexSum.get(prefixXor) + k); + } + return totalCount; + } +} diff --git a/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.kt b/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.kt new file mode 100644 index 00000000..eefc5711 --- /dev/null +++ b/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.kt @@ -0,0 +1,20 @@ +class Solution { + fun countTriplets(arr: IntArray): Int { + var totalCount = 0 + var prefixXor = 0 + val prefixCount = mutableMapOf(0 to 1) + val indexSum = mutableMapOf(0 to 0) + for (k in 1..arr.size) { + prefixXor = prefixXor xor arr[k - 1] + if (prefixCount.containsKey(prefixXor)) { + totalCount += prefixCount[prefixXor]!! * (k - 1) - indexSum[prefixXor]!! + } else { + prefixCount[prefixXor] = 0 + indexSum[prefixXor] = 0 + } + prefixCount[prefixXor] = prefixCount[prefixXor]!! + 1 + indexSum[prefixXor] = indexSum[prefixXor]!! + k + } + return totalCount + } +} diff --git a/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.py b/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.py new file mode 100644 index 00000000..bb8bbd52 --- /dev/null +++ b/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.py @@ -0,0 +1,20 @@ +class Solution: + def countTriplets(self, arr): + total_count = 0 + prefix_xor = 0 + prefix_count = {0: 1} + index_sum = {0: 0} + + for k, value in enumerate(arr, 1): + prefix_xor ^= value + if prefix_xor in prefix_count: + total_count += ( + prefix_count[prefix_xor] * (k - 1) - index_sum[prefix_xor] + ) + else: + prefix_count[prefix_xor] = 0 + index_sum[prefix_xor] = 0 + prefix_count[prefix_xor] += 1 + index_sum[prefix_xor] += k + + return total_count diff --git a/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.py2 b/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.py2 new file mode 100644 index 00000000..559b8d0f --- /dev/null +++ b/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def countTriplets(self, arr): + total_count = 0 + prefix_xor = 0 + prefix_count = {0: 1} + index_sum = {0: 0} + for k, value in enumerate(arr, 1): + prefix_xor ^= value + if prefix_xor in prefix_count: + total_count += prefix_count[prefix_xor] * (k - 1) - index_sum[prefix_xor] + else: + prefix_count[prefix_xor] = 0 + index_sum[prefix_xor] = 0 + prefix_count[prefix_xor] += 1 + index_sum[prefix_xor] += k + return total_count diff --git a/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.rb b/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.rb new file mode 100644 index 00000000..99d2e583 --- /dev/null +++ b/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.rb @@ -0,0 +1,21 @@ +# @param {Integer[]} arr +# @return {Integer} +def count_triplets(arr) + total_count = 0 + prefix_xor = 0 + prefix_count = {0 => 1} + index_sum = {0 => 0} + arr.each_with_index do |value, i| + k = i + 1 + prefix_xor ^= value + if prefix_count.key?(prefix_xor) + total_count += prefix_count[prefix_xor] * (k - 1) - index_sum[prefix_xor] + else + prefix_count[prefix_xor] = 0 + index_sum[prefix_xor] = 0 + end + prefix_count[prefix_xor] += 1 + index_sum[prefix_xor] += k + end + total_count +end diff --git a/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.rs b/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.rs new file mode 100644 index 00000000..e1d6f579 --- /dev/null +++ b/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.rs @@ -0,0 +1,23 @@ +impl Solution { + pub fn count_triplets(arr: Vec) -> i32 { + let mut total_count: i32 = 0; + let mut prefix_xor: i32 = 0; + let mut prefix_count: std::collections::HashMap = std::collections::HashMap::new(); + let mut index_sum: std::collections::HashMap = std::collections::HashMap::new(); + prefix_count.insert(0, 1); + index_sum.insert(0, 0); + for (i, &value) in arr.iter().enumerate() { + let k = (i + 1) as i32; + prefix_xor ^= value; + if prefix_count.contains_key(&prefix_xor) { + total_count += prefix_count[&prefix_xor] * (k - 1) - index_sum[&prefix_xor]; + } else { + prefix_count.insert(prefix_xor, 0); + index_sum.insert(prefix_xor, 0); + } + *prefix_count.get_mut(&prefix_xor).unwrap() += 1; + *index_sum.get_mut(&prefix_xor).unwrap() += k; + } + total_count + } +} diff --git a/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.swift b/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.swift new file mode 100644 index 00000000..2188811d --- /dev/null +++ b/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func countTriplets(_ arr: [Int]) -> Int { + var totalCount = 0 + var prefixXor = 0 + var prefixCount = [0: 1] + var indexSum = [0: 0] + for k in 1...arr.count { + prefixXor ^= arr[k - 1] + if let cnt = prefixCount[prefixXor], let sum = indexSum[prefixXor] { + totalCount += cnt * (k - 1) - sum + } else { + prefixCount[prefixXor] = 0 + indexSum[prefixXor] = 0 + } + prefixCount[prefixXor]! += 1 + indexSum[prefixXor]! += k + } + return totalCount + } +} diff --git a/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.ts b/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.ts new file mode 100644 index 00000000..5c40ce91 --- /dev/null +++ b/tests/1001-1500/1442. count-triplets-that-can-form-two-arrays-of-equal-xor/sol.ts @@ -0,0 +1,19 @@ +function countTriplets(arr: number[]): number { + let totalCount = 0; + let prefixXor = 0; + const prefixCount: Map = new Map([[0, 1]]); + const indexSum: Map = new Map([[0, 0]]); + for (let k = 1; k <= arr.length; k++) { + prefixXor ^= arr[k - 1]; + if (prefixCount.has(prefixXor)) { + totalCount += + prefixCount.get(prefixXor)! * (k - 1) - indexSum.get(prefixXor)!; + } else { + prefixCount.set(prefixXor, 0); + indexSum.set(prefixXor, 0); + } + prefixCount.set(prefixXor, prefixCount.get(prefixXor)! + 1); + indexSum.set(prefixXor, indexSum.get(prefixXor)! + k); + } + return totalCount; +} diff --git a/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/manifest.yaml b/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/manifest.yaml new file mode 100644 index 00000000..58f33a6f --- /dev/null +++ b/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/manifest.yaml @@ -0,0 +1,556 @@ +entry: + id: 1443 + title: minimum-time-to-collect-all-apples-in-a-tree + params: + n: + type: int + edges: + type: array + items: + type: array + items: + type: int + hasApple: + type: array + items: + type: bool + call: + cpp: "Solution().minTime({n}, {edges}, {hasApple})" + rust: "Solution::min_time({n}, {edges}, {hasApple})" + python3: "Solution().minTime({n}, {edges}, {hasApple})" + python2: "Solution().minTime({n}, {edges}, {hasApple})" + ruby: "min_time({n}, {edges}, {hasApple})" + java: "new Solution().minTime({n}, {edges}, {hasApple})" + csharp: "new Solution().MinTime({n}, {edges}, {hasApple})" + kotlin: "Solution().minTime({n}, {edges}, {hasApple})" + go: "minTime({n}, {edges}, {hasApple})" + dart: "Solution().minTime({n}, {edges}, {hasApple})" + swift: "Solution().minTime({n}, {edges}, {hasApple})" + typescript: "minTime({n}, {edges}, {hasApple})" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().minTime(n, edges, hasApple, {result})" + checker: | + class Checker: + def minTime(self, n, edges, hasApple, result): + if type(result) is not int: + return False + graph = [[] for _ in range(n)] + for edge in edges: + if 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) + parent = [-2] * n + parent[0] = -1 + order = [0] + for u in order: + for v in graph[u]: + if v == parent[u]: + continue + if parent[v] != -2: + return False + parent[v] = u + order.append(v) + if len(order) != n or len(hasApple) != n: + return False + contains = list(hasApple) + cost = 0 + for u in reversed(order[1:]): + if contains[u]: + cost += 2 + contains[parent[u]] = True + return result == cost +seed: 1443 +tests: + - name: one-no-apple + in: + n: 1 + edges: [] + hasApple: [false] + - name: one-apple + in: + n: 1 + edges: [] + hasApple: [true] + - name: two-leaf + in: + n: 2 + edges: + - [0, 1] + hasApple: [false, true] + - name: two-none + in: + n: 2 + edges: + - [0, 1] + hasApple: [false, false] + - name: chain-three-leaf + in: + n: 3 + edges: + - [0, 1] + - [1, 2] + hasApple: [false, false, true] + - name: chain-three-middle + in: + n: 3 + edges: + - [0, 1] + - [1, 2] + hasApple: [false, true, false] + - name: star-three + in: + n: 4 + edges: + - [0, 1] + - [0, 2] + - [0, 3] + hasApple: [false, true, false, true] + - name: star-none + in: + n: 5 + edges: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + hasApple: [false, false, false, false, false] + - name: chain-five-end + in: + n: 5 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + hasApple: [false, false, false, false, true] + - name: chain-five-middle + in: + n: 5 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + hasApple: [false, false, true, false, false] + - name: chain-five-both + in: + n: 5 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + hasApple: [false, true, false, false, true] + - name: balanced-seven + in: + n: 7 + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [2, 6] + hasApple: [false, false, false, true, false, false, true] + - name: balanced-all-leaves + in: + n: 7 + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [2, 6] + hasApple: [false, false, false, true, true, true, true] + - name: balanced-none + in: + n: 7 + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [2, 6] + hasApple: [false, false, false, false, false, false, false] + - name: internal-only + in: + n: 7 + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [2, 6] + hasApple: [false, true, false, false, false, true, false] + - name: branch-left + in: + n: 6 + edges: + - [0, 1] + - [1, 2] + - [1, 3] + - [3, 4] + - [3, 5] + hasApple: [false, false, false, false, true, false] + - name: branch-right + in: + n: 6 + edges: + - [0, 1] + - [0, 2] + - [2, 3] + - [2, 4] + - [4, 5] + hasApple: [false, false, false, false, false, true] + - name: apple-root + in: + n: 4 + edges: + - [0, 1] + - [1, 2] + - [1, 3] + hasApple: [true, false, false, false] + - name: multiple-prune + in: + n: 8 + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [2, 6] + - [6, 7] + hasApple: [false, false, false, true, false, false, false, true] + - name: deep-single + in: + n: 8 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + hasApple: [false, false, false, false, false, false, false, true] + - name: deep-two + in: + n: 8 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + hasApple: [false, false, true, false, false, false, false, true] + - name: wide-star + in: + n: 8 + edges: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [0, 5] + - [0, 6] + - [0, 7] + hasApple: [false, true, false, true, false, true, false, true] + - name: all-apples-six + in: + n: 6 + edges: + - [0, 1] + - [1, 2] + - [1, 3] + - [3, 4] + - [3, 5] + hasApple: [true, true, true, true, true, true] + - name: alternating-chain + in: + n: 9 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + hasApple: [false, true, false, true, false, true, false, true, false] + - name: branch-pruned + in: + n: 9 + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [2, 6] + - [6, 7] + - [6, 8] + hasApple: [false, false, false, false, true, false, false, false, true] + - name: two-branches + in: + n: 9 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [0, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + hasApple: [false, false, false, true, false, false, false, false, true] + - name: ten-chain + in: + n: 10 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + hasApple: + [false, false, false, false, false, false, false, false, false, true] + - name: ten-sparse + in: + n: 10 + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [2, 6] + - [3, 7] + - [5, 8] + - [6, 9] + hasApple: + [false, false, false, false, false, false, false, true, false, true] + - name: eleven-branches + in: + n: 11 + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [2, 6] + - [3, 7] + - [4, 8] + - [5, 9] + - [6, 10] + hasApple: + [ + false, + false, + false, + true, + false, + false, + true, + false, + true, + false, + true, + ] + - name: twelve-chain + in: + n: 12 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + - [10, 11] + hasApple: + [ + false, + false, + false, + false, + false, + false, + true, + false, + false, + false, + false, + true, + ] + - name: twelve-all + in: + n: 12 + edges: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [0, 5] + - [0, 6] + - [0, 7] + - [0, 8] + - [0, 9] + - [0, 10] + - [0, 11] + hasApple: + [ + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + ] + - name: final-mixed + in: + n: 10 + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [2, 6] + - [4, 7] + - [5, 8] + - [6, 9] + hasApple: + [false, false, false, true, false, false, true, false, true, false] + - name: final-left-deep + in: + n: 9 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [3, 5] + - [5, 6] + - [5, 7] + - [7, 8] + hasApple: [false, false, false, false, true, false, false, true, false] + - name: final-right-deep + in: + n: 9 + edges: + - [0, 1] + - [0, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [2, 6] + - [6, 7] + - [7, 8] + hasApple: [false, false, false, false, false, true, false, false, true] + - name: final-branch-prune + in: + n: 8 + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [2, 6] + - [6, 7] + hasApple: [false, false, false, false, true, false, false, true] + - name: official-example-one + in: + n: 7 + edges: + - [0, 1] + - [0, 2] + - [1, 4] + - [1, 5] + - [2, 3] + - [2, 6] + hasApple: [false, false, true, false, true, true, false] + - name: official-example-two + in: + n: 7 + edges: + - [0, 1] + - [0, 2] + - [1, 4] + - [1, 5] + - [2, 3] + - [2, 6] + hasApple: [false, false, true, false, false, true, false] + - name: official-example-three + in: + n: 7 + edges: + - [0, 1] + - [0, 2] + - [1, 4] + - [1, 5] + - [2, 3] + - [2, 6] + hasApple: [false, false, false, false, false, false, false] + - name: asymmetric-three-branches + in: + n: 10 + edges: + - [0, 1] + - [0, 2] + - [0, 3] + - [1, 4] + - [4, 5] + - [2, 6] + - [2, 7] + - [3, 8] + - [8, 9] + hasApple: + [false, false, false, false, false, true, false, true, false, true] + - name: only-deep-left + in: + n: 10 + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [2, 8] + - [8, 9] + hasApple: + [false, false, false, false, false, false, false, true, false, false] diff --git a/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.cpp b/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.cpp new file mode 100644 index 00000000..8f3f12a5 --- /dev/null +++ b/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.cpp @@ -0,0 +1,44 @@ +class Solution { +public: + int minTime(int n, vector>& edges, vector& hasApple) { + vector> adj(n); + vector degree(n, 0); + + for (auto& e : edges) { + int u = e[0], v = e[1]; + adj[u].push_back(v); + adj[v].push_back(u); + degree[u]++; + degree[v]++; + } + + queue q; + for (int i = 1; i < n; i++) { + if (degree[i] == 1 && !hasApple[i]) { + q.push(i); + } + } + + vector keep(n, true); + + while (!q.empty()) { + int u = q.front(); + q.pop(); + keep[u] = false; + + for (int v : adj[u]) { + degree[v]--; + if (v != 0 && keep[v] && !hasApple[v] && degree[v] == 1) { + q.push(v); + } + } + } + + int activeNodes = 0; + for (bool k : keep) { + if (k) activeNodes++; + } + + return max(0, (activeNodes - 1) * 2); + } +}; diff --git a/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.cs b/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.cs new file mode 100644 index 00000000..bb8ffdf4 --- /dev/null +++ b/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.cs @@ -0,0 +1,46 @@ +public class Solution { + public int MinTime(int n, int[][] edges, IList hasApple) { + List[] adj = new List[n]; + int[] degree = new int[n]; + for (int i = 0; i < n; i++) { + adj[i] = new List(); + } + + foreach (var e in edges) { + int u = e[0], v = e[1]; + adj[u].Add(v); + adj[v].Add(u); + degree[u]++; + degree[v]++; + } + + Queue q = new Queue(); + for (int i = 1; i < n; i++) { + if (degree[i] == 1 && !hasApple[i]) { + q.Enqueue(i); + } + } + + bool[] keep = new bool[n]; + Array.Fill(keep, true); + + while (q.Count > 0) { + int u = q.Dequeue(); + keep[u] = false; + + foreach (int v in adj[u]) { + degree[v]--; + if (v != 0 && keep[v] && !hasApple[v] && degree[v] == 1) { + q.Enqueue(v); + } + } + } + + int activeNodes = 0; + foreach (bool k in keep) { + if (k) activeNodes++; + } + + return Math.Max(0, (activeNodes - 1) * 2); + } +} diff --git a/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.dart b/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.dart new file mode 100644 index 00000000..1b3011d6 --- /dev/null +++ b/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.dart @@ -0,0 +1,38 @@ +class Solution { + int minTime(int n, List> edges, List hasApple) { + List> adj = List.generate(n, (_) => []); + List degree = List.filled(n, 0); + + for (var e in edges) { + int u = e[0], v = e[1]; + adj[u].add(v); + adj[v].add(u); + degree[u]++; + degree[v]++; + } + + List q = []; + for (int i = 1; i < n; i++) { + if (degree[i] == 1 && !hasApple[i]) { + q.add(i); + } + } + + List keep = List.filled(n, true); + + while (q.isNotEmpty) { + int u = q.removeAt(0); + keep[u] = false; + + for (int v in adj[u]) { + degree[v]--; + if (v != 0 && keep[v] && !hasApple[v] && degree[v] == 1) { + q.add(v); + } + } + } + + int activeNodes = keep.where((k) => k).length; + return (activeNodes - 1) * 2 > 0 ? (activeNodes - 1) * 2 : 0; + } +} diff --git a/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.go b/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.go new file mode 100644 index 00000000..c1a6750a --- /dev/null +++ b/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.go @@ -0,0 +1,53 @@ +func minTime(n int, edges [][]int, hasApple []bool) int { + adj := make([][]int, n) + degree := make([]int, n) + for i := 0; i < n; i++ { + adj[i] = []int{} + } + + for _, e := range edges { + u, v := e[0], e[1] + adj[u] = append(adj[u], v) + adj[v] = append(adj[v], u) + degree[u]++ + degree[v]++ + } + + q := []int{} + for i := 1; i < n; i++ { + if degree[i] == 1 && !hasApple[i] { + q = append(q, i) + } + } + + keep := make([]bool, n) + for i := range keep { + keep[i] = true + } + + for len(q) > 0 { + u := q[0] + q = q[1:] + keep[u] = false + + for _, v := range adj[u] { + degree[v]-- + if v != 0 && keep[v] && !hasApple[v] && degree[v] == 1 { + q = append(q, v) + } + } + } + + activeNodes := 0 + for _, k := range keep { + if k { + activeNodes++ + } + } + + res := (activeNodes - 1) * 2 + if res < 0 { + return 0 + } + return res +} diff --git a/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.java b/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.java new file mode 100644 index 00000000..3aa22e43 --- /dev/null +++ b/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.java @@ -0,0 +1,55 @@ +class Solution { + public int minTime(int n, int[][] edges, List hasApple) { + List> adj = new ArrayList<>(); + int[] degree = new int[n]; + for (int i = 0; i < n; i++) { + adj.add(new ArrayList<>()); + } + + for (int[] edge : edges) { + int u = edge[0], v = edge[1]; + adj.get(u).add(v); + adj.get(v).add(u); + degree[u]++; + degree[v]++; + } + + Queue q = new LinkedList<>(); + for (int i = 1; i < n; i++) { + if (degree[i] == 1 && !hasApple.get(i)) { + q.offer(i); + } + } + + boolean[] keep = new boolean[n]; + Arrays.fill(keep, true); + + while (!q.isEmpty()) { + int u = q.poll(); + keep[u] = false; + + for (int v : adj.get(u)) { + degree[v]--; + if (v != 0 && keep[v] && !hasApple.get(v) && degree[v] == 1) { + q.offer(v); + } + } + } + + int activeNodes = 0; + for (boolean k : keep) { + if (k) activeNodes++; + } + + return Math.max(0, (activeNodes - 1) * 2); + } + + // The local harness materializes boolean arrays for this parameter. + public int minTime(int n, int[][] edges, boolean[] hasApple) { + List apples = new ArrayList<>(n); + for (boolean apple : hasApple) { + apples.add(apple); + } + return minTime(n, edges, apples); + } +} diff --git a/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.kt b/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.kt new file mode 100644 index 00000000..51497f25 --- /dev/null +++ b/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.kt @@ -0,0 +1,42 @@ +class Solution { + fun minTime(n: Int, edges: Array, hasApple: List): Int { + val adj = List(n) { mutableListOf() } + val degree = IntArray(n) + + for ((u, v) in edges) { + adj[u].add(v) + adj[v].add(u) + degree[u]++ + degree[v]++ + } + + val q = ArrayDeque() + for (i in 1 until n) { + if (degree[i] == 1 && !hasApple[i]) { + q.add(i) + } + } + + val keep = BooleanArray(n) { true } + + while (q.isNotEmpty()) { + val u = q.removeFirst() + keep[u] = false + + for (v in adj[u]) { + degree[v]-- + if (v != 0 && keep[v] && !hasApple[v] && degree[v] == 1) { + q.add(v) + } + } + } + + val activeNodes = keep.count { it } + return maxOf(0, (activeNodes - 1) * 2) + } + + // The local harness materializes boolean arrays for this parameter. + fun minTime(n: Int, edges: Array, hasApple: BooleanArray): Int { + return minTime(n, edges, hasApple.toList()) + } +} diff --git a/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.py b/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.py new file mode 100644 index 00000000..1c6d29c4 --- /dev/null +++ b/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.py @@ -0,0 +1,33 @@ +from collections import deque +from typing import List + + +class Solution: + def minTime(self, n: int, edges: list[list[int]], hasApple: list[bool]) -> int: + adj = [[] for _ in range(n)] + degree = [0] * n + + for u, v in edges: + adj[u].append(v) + adj[v].append(u) + degree[u] += 1 + degree[v] += 1 + + q = deque() + for i in range(1, n): + if degree[i] == 1 and not hasApple[i]: + q.append(i) + + keep = [True] * n + + while q: + u = q.popleft() + keep[u] = False + + for v in adj[u]: + degree[v] -= 1 + if v != 0 and keep[v] and not hasApple[v] and degree[v] == 1: + q.append(v) + + activeNodes = sum(keep) + return max(0, (activeNodes - 1) * 2) diff --git a/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.py2 b/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.py2 new file mode 100644 index 00000000..4038c1e4 --- /dev/null +++ b/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.py2 @@ -0,0 +1,35 @@ +class Solution(object): + def minTime(self, n, edges, hasApple): + """ + :type n: int + :type edges: List[List[int]] + :type hasApple: List[bool] + :rtype: int + """ + adj = [[] for _ in range(n)] + degree = [0] * n + + for u, v in edges: + adj[u].append(v) + adj[v].append(u) + degree[u] += 1 + degree[v] += 1 + + q = [] + for i in range(1, n): + if degree[i] == 1 and not hasApple[i]: + q.append(i) + + keep = [True] * n + + while q: + u = q.pop(0) + keep[u] = False + + for v in adj[u]: + degree[v] -= 1 + if v != 0 and keep[v] and not hasApple[v] and degree[v] == 1: + q.append(v) + + activeNodes = sum(keep) + return max(0, (activeNodes - 1) * 2) diff --git a/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.rb b/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.rb new file mode 100644 index 00000000..2ffc00d9 --- /dev/null +++ b/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.rb @@ -0,0 +1,39 @@ +# @param {Integer} n +# @param {Integer[][]} edges +# @param {Boolean[]} has_apple +# @return {Integer} +def min_time(n, edges, has_apple) + adj = Array.new(n) { [] } + degree = Array.new(n, 0) + + edges.each do |u, v| + adj[u] << v + adj[v] << u + degree[u] += 1 + degree[v] += 1 + end + + q = [] + (1...n).each do |i| + if degree[i] == 1 && !has_apple[i] + q << i + end + end + + keep = Array.new(n, true) + + while !q.empty? + u = q.shift + keep[u] = false + + adj[u].each do |v| + degree[v] -= 1 + if v != 0 && keep[v] && !has_apple[v] && degree[v] == 1 + q << v + end + end + end + + active_nodes = keep.count(true) + [(active_nodes - 1) * 2, 0].max +end diff --git a/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.rs b/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.rs new file mode 100644 index 00000000..8d17c39a --- /dev/null +++ b/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.rs @@ -0,0 +1,39 @@ +impl Solution { + pub fn min_time(n: i32, edges: Vec>, has_apple: Vec) -> i32 { + let n = n as usize; + let mut adj = vec![vec![]; n]; + let mut degree = vec![0; n]; + + for edge in &edges { + let u = edge[0] as usize; + let v = edge[1] as usize; + adj[u].push(v); + adj[v].push(u); + degree[u] += 1; + degree[v] += 1; + } + + let mut q = std::collections::VecDeque::new(); + for i in 1..n { + if degree[i] == 1 && !has_apple[i] { + q.push_back(i); + } + } + + let mut keep = vec![true; n]; + + while let Some(u) = q.pop_front() { + keep[u] = false; + + for &v in &adj[u].clone() { + degree[v] -= 1; + if v != 0 && keep[v] && !has_apple[v] && degree[v] == 1 { + q.push_back(v); + } + } + } + + let active_nodes = keep.iter().filter(|&&k| k).count() as i32; + std::cmp::max(0, (active_nodes - 1) * 2) + } +} diff --git a/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.swift b/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.swift new file mode 100644 index 00000000..41460911 --- /dev/null +++ b/tests/1001-1500/1443. minimum-time-to-collect-all-apples-in-a-tree/sol.swift @@ -0,0 +1,38 @@ +class Solution { + func minTime(_ n: Int, _ edges: [[Int]], _ hasApple: [Bool]) -> Int { + var adj = [[Int]](repeating: [], count: n) + var degree = [Int](repeating: 0, count: n) + + for e in edges { + let u = e[0], v = e[1] + adj[u].append(v) + adj[v].append(u) + degree[u] += 1 + degree[v] += 1 + } + + var q = [Int]() + for i in 1.. []); + const degree: number[] = Array(n).fill(0); + + for (const [u, v] of edges) { + adj[u].push(v); + adj[v].push(u); + degree[u]++; + degree[v]++; + } + + const q: number[] = []; + for (let i = 1; i < n; i++) { + if (degree[i] === 1 && !hasApple[i]) { + q.push(i); + } + } + + const keep: boolean[] = Array(n).fill(true); + + while (q.length > 0) { + const u = q.shift()!; + keep[u] = false; + + for (const v of adj[u]) { + degree[v]--; + if (v !== 0 && keep[v] && !hasApple[v] && degree[v] === 1) { + q.push(v); + } + } + } + + const activeNodes = keep.filter((k) => k).length; + return Math.max(0, (activeNodes - 1) * 2); +} diff --git a/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/manifest.yaml b/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/manifest.yaml new file mode 100644 index 00000000..54fbdd7e --- /dev/null +++ b/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/manifest.yaml @@ -0,0 +1,358 @@ +entry: + id: 1444 + title: "number-of-ways-of-cutting-a-pizza" + params: + pizza: + type: array + items: + type: string + k: + type: int + call: + cpp: "Solution().ways({pizza}, {k})" + rust: "Solution::ways({pizza}, {k})" + python3: "Solution().ways({pizza}, {k})" + python2: "Solution().ways({pizza}, {k})" + ruby: "ways({pizza}, {k})" + java: "new Solution().ways({pizza}, {k})" + csharp: "new Solution().Ways({pizza}, {k})" + kotlin: "Solution().ways({pizza}, {k})" + go: "ways({pizza}, {k})" + dart: "Solution().ways({pizza}, {k})" + swift: "Solution().ways({pizza}, {k})" + typescript: "ways({pizza}, {k})" +judge: + type: "exact" +limits: + time_ms: 5000 + memory_mb: 300 +oracle: + python3: + call: "Checker().ways(pizza, k, {result})" + checker: | + class Checker: + def ways(self, pizza, k, result): + if type(result) is not int or not (1 <= k <= 10): + return False + rows = len(pizza) + cols = len(pizza[0]) + if not (1 <= rows <= 50 and 1 <= cols <= 50): + return False + if any(len(row) != cols or any(ch not in 'A.' for ch in row) for row in pizza): + return False + + def has_apple(top, left, bottom, right): + return any(pizza[r][c] == 'A' + for r in range(top, bottom) + for c in range(left, right)) + + memo = {} + def count(top, left, pieces): + key = (top, left, pieces) + if key in memo: + return memo[key] + if not has_apple(top, left, rows, cols): + return 0 + if pieces == 1: + return 1 + total = 0 + for cut in range(top + 1, rows): + if has_apple(top, left, cut, cols): + total += count(cut, left, pieces - 1) + for cut in range(left + 1, cols): + if has_apple(top, left, rows, cut): + total += count(top, cut, pieces - 1) + memo[key] = total % 1000000007 + return memo[key] + + return result == count(0, 0, k) +seed: 1444 +tests: + - name: "official-one" + in: + pizza: ["A..", "AAA", "..."] + k: 3 + out: 3 + - name: "official-two" + in: + pizza: ["A..", "AA.", "..."] + k: 3 + out: 1 + - name: "single-cell-one" + in: + pizza: ["A"] + k: 1 + out: 1 + - name: "single-cell-empty" + in: + pizza: ["."] + k: 1 + out: 0 + - name: "single-row-many-pieces" + in: + pizza: ["AAAAA"] + k: 5 + out: 1 + - name: "all-empty" + in: + pizza: ["...", "...", "..."] + k: 1 + out: 0 + - name: "all-apples-two-by-two-four" + in: + pizza: ["AA", "AA"] + k: 4 + out: 0 + - name: "top-left-only" + in: + pizza: ["A..", "...", "..."] + k: 2 + out: 0 + - name: "diagonal-apples" + in: + pizza: ["A..", ".A.", "..A"] + k: 2 + out: 4 + - name: "checkerboard" + in: + pizza: ["A.A", ".A.", "A.A"] + k: 3 + out: 10 + - name: "top-row-apples" + in: + pizza: ["AAAA", "....", "...."] + k: 3 + out: 3 + - name: "left-column-apples" + in: + pizza: ["A...", "A...", "A..."] + k: 3 + out: 1 + - name: "cross-shape" + in: + pizza: [".A.", "AAA", ".A."] + k: 3 + out: 6 + - name: "corner-pairs" + in: + pizza: ["A.A", "...", "A.A"] + k: 2 + out: 4 + - name: "two-by-three-full" + in: + pizza: ["AAA", "AAA"] + k: 3 + out: 5 + - name: "two-by-three-sparse" + in: + pizza: ["A.A", "..A"] + k: 2 + out: 3 + - name: "three-by-two-sparse" + in: + pizza: ["A.", ".A", "AA"] + k: 3 + out: 4 + - name: "four-by-four-diagonal" + in: + pizza: ["A...", ".A..", "..A.", "...A"] + k: 4 + out: 8 + - name: "four-by-four-border" + in: + pizza: ["AAAA", "A..A", "A..A", "AAAA"] + k: 3 + out: 24 + - name: "five-by-one" + in: + pizza: ["A", "A", "A", "A", "A"] + k: 5 + out: 1 + - name: "one-by-five" + in: + pizza: ["A.AAA"] + k: 3 + out: 5 + - name: "five-by-five-sparse" + in: + pizza: ["A....", "..A..", "....A", ".A...", "...A."] + k: 3 + out: 28 + - name: "five-by-five-dense" + in: + pizza: ["AAAA.", "AAA..", "AA...", "A....", "....."] + k: 4 + out: 8 + - name: "apple-strip-middle" + in: + pizza: [".....", ".AAA.", "....."] + k: 2 + out: 2 + - name: "apple-strip-bottom" + in: + pizza: [".....", ".....", "AAAAA"] + k: 3 + out: 6 + - name: "alternating-rows" + in: + pizza: ["AAAA", "....", "AAAA", "...."] + k: 4 + out: 19 + - name: "alternating-columns" + in: + pizza: ["A.A.", "A.A.", "A.A.", "A.A."] + k: 4 + out: 19 + - name: "six-by-six-diagonal-band" + in: + pizza: ["A.....", ".AA...", "..AA..", "...AA.", "....AA", ".....A"] + k: 5 + out: 182 + - name: "six-by-six-full" + in: + pizza: ["AAAAAA", "AAAAAA", "AAAAAA", "AAAAAA", "AAAAAA", "AAAAAA"] + k: 6 + out: 2252 + - name: "eight-by-eight-sparse" + in: + pizza: + [ + "A.......", + "........", + "...A....", + "........", + ".......A", + "........", + ".A......", + ".....A..", + ] + k: 4 + out: 268 + - name: "maximum-all-apples" + in: + pizza: + [ + "AAAAAAAAAA", + "AAAAAAAAAA", + "AAAAAAAAAA", + "AAAAAAAAAA", + "AAAAAAAAAA", + "AAAAAAAAAA", + "AAAAAAAAAA", + "AAAAAAAAAA", + "AAAAAAAAAA", + "AAAAAAAAAA", + ] + k: 10 + out: 5280932 + - name: "maximum-mixed-grid" + in: + pizza: + [ + "A.A.A.A.A.", + "A.A.A.A.A.", + "A.A.A.A.A.", + "A.A.A.A.A.", + "A.A.A.A.A.", + "A.A.A.A.A.", + "A.A.A.A.A.", + "A.A.A.A.A.", + "A.A.A.A.A.", + "A.A.A.A.A.", + ] + k: 10 + out: 511561 + - name: "maximum-empty-grid" + in: + pizza: + [ + "..........", + "..........", + "..........", + "..........", + "..........", + "..........", + "..........", + "..........", + "..........", + "..........", + ] + k: 10 + out: 0 + - name: "maximum-single-row" + in: + pizza: ["AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"] + k: 10 + out: 54455620 + - name: "maximum-k-one" + in: + pizza: + [ + "AAAAAAAAAA", + "..........", + "AAAAAAAAAA", + "..........", + "AAAAAAAAAA", + "..........", + "AAAAAAAAAA", + "..........", + "AAAAAAAAAA", + "..........", + ] + k: 1 + out: 1 + - name: "generated-50x50-k1" + seed: 144401 + in: + pizza: + gen: "array" + len: 50 + of: + gen: "str" + len: 50 + alphabet: "A." + k: 1 + - name: "generated-50x50-k2" + seed: 144402 + in: + pizza: + gen: "array" + len: 50 + of: + gen: "str" + len: 50 + alphabet: "A." + k: 2 + - name: "generated-50x50-k5" + seed: 144405 + in: + pizza: + gen: "array" + len: 50 + of: + gen: "str" + len: 50 + alphabet: "A." + k: 5 + - name: "generated-50x50-k9" + seed: 144409 + in: + pizza: + gen: "array" + len: 50 + of: + gen: "str" + len: 50 + alphabet: "A." + k: 9 + - name: "generated-50x50-k10" + seed: 144410 + in: + pizza: + gen: "array" + len: 50 + of: + gen: "str" + len: 50 + alphabet: "A." + k: 10 diff --git a/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.cpp b/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.cpp new file mode 100644 index 00000000..9da419da --- /dev/null +++ b/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.cpp @@ -0,0 +1,43 @@ +class Solution { +public: + int ways(vector& pizza, int k) { + int m = pizza.size(), n = pizza[0].size(), MOD = 1'000'000'007; + vector> preSum(m + 1, vector(n + 1, 0)); + + for (int r = m - 1; r >= 0; r--) { + for (int c = n - 1; c >= 0; c--) { + preSum[r][c] = preSum[r][c + 1] + preSum[r + 1][c] - preSum[r + 1][c + 1] + (pizza[r][c] == 'A' ? 1 : 0); + } + } + + vector>> dp(k, vector>(m, vector(n, 0))); + + for (int r = 0; r < m; r++) { + for (int c = 0; c < n; c++) { + dp[0][r][c] = preSum[r][c] > 0 ? 1 : 0; + } + } + + for (int cuts = 1; cuts < k; cuts++) { + for (int r = 0; r < m; r++) { + for (int c = 0; c < n; c++) { + if (preSum[r][c] == 0) continue; + int ans = 0; + for (int nr = r + 1; nr < m; nr++) { + if (preSum[r][c] - preSum[nr][c] > 0) { + ans = (ans + dp[cuts - 1][nr][c]) % MOD; + } + } + for (int nc = c + 1; nc < n; nc++) { + if (preSum[r][c] - preSum[r][nc] > 0) { + ans = (ans + dp[cuts - 1][r][nc]) % MOD; + } + } + dp[cuts][r][c] = ans; + } + } + } + + return dp[k - 1][0][0]; + } +}; diff --git a/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.cs b/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.cs new file mode 100644 index 00000000..2169791a --- /dev/null +++ b/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.cs @@ -0,0 +1,42 @@ +public class Solution { + public int Ways(string[] pizza, int k) { + int m = pizza.Length, n = pizza[0].Length, MOD = 1_000_000_007; + int[,] preSum = new int[m + 1, n + 1]; + + for (int r = m - 1; r >= 0; r--) { + for (int c = n - 1; c >= 0; c--) { + preSum[r, c] = preSum[r, c + 1] + preSum[r + 1, c] - preSum[r + 1, c + 1] + (pizza[r][c] == 'A' ? 1 : 0); + } + } + + int[,,] dp = new int[k, m, n]; + + for (int r = 0; r < m; r++) { + for (int c = 0; c < n; c++) { + dp[0, r, c] = preSum[r, c] > 0 ? 1 : 0; + } + } + + for (int cuts = 1; cuts < k; cuts++) { + for (int r = 0; r < m; r++) { + for (int c = 0; c < n; c++) { + if (preSum[r, c] == 0) continue; + int ans = 0; + for (int nr = r + 1; nr < m; nr++) { + if (preSum[r, c] - preSum[nr, c] > 0) { + ans = (ans + dp[cuts - 1, nr, c]) % MOD; + } + } + for (int nc = c + 1; nc < n; nc++) { + if (preSum[r, c] - preSum[r, nc] > 0) { + ans = (ans + dp[cuts - 1, r, nc]) % MOD; + } + } + dp[cuts, r, c] = ans; + } + } + } + + return dp[k - 1, 0, 0]; + } +} diff --git a/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.dart b/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.dart new file mode 100644 index 00000000..7475eb56 --- /dev/null +++ b/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.dart @@ -0,0 +1,43 @@ +class Solution { + int ways(List pizza, int k) { + int m = pizza.length, n = pizza[0].length; + int MOD = 1000000007; + List> preSum = List.generate(m + 1, (_) => List.filled(n + 1, 0)); + + for (int r = m - 1; r >= 0; r--) { + for (int c = n - 1; c >= 0; c--) { + preSum[r][c] = preSum[r][c + 1] + preSum[r + 1][c] - preSum[r + 1][c + 1] + (pizza[r][c] == 'A' ? 1 : 0); + } + } + + List>> dp = List.generate(k, (_) => List.generate(m, (_) => List.filled(n, 0))); + + for (int r = 0; r < m; r++) { + for (int c = 0; c < n; c++) { + dp[0][r][c] = preSum[r][c] > 0 ? 1 : 0; + } + } + + for (int cuts = 1; cuts < k; cuts++) { + for (int r = 0; r < m; r++) { + for (int c = 0; c < n; c++) { + if (preSum[r][c] == 0) continue; + int ans = 0; + for (int nr = r + 1; nr < m; nr++) { + if (preSum[r][c] - preSum[nr][c] > 0) { + ans = (ans + dp[cuts - 1][nr][c]) % MOD; + } + } + for (int nc = c + 1; nc < n; nc++) { + if (preSum[r][c] - preSum[r][nc] > 0) { + ans = (ans + dp[cuts - 1][r][nc]) % MOD; + } + } + dp[cuts][r][c] = ans; + } + } + } + + return dp[k - 1][0][0]; + } +} diff --git a/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.go b/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.go new file mode 100644 index 00000000..5d8aed09 --- /dev/null +++ b/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.go @@ -0,0 +1,58 @@ +func ways(pizza []string, k int) int { + m, n := len(pizza), len(pizza[0]) + MOD := 1_000_000_007 + preSum := make([][]int, m+1) + for i := range preSum { + preSum[i] = make([]int, n+1) + } + + for r := m - 1; r >= 0; r-- { + for c := n - 1; c >= 0; c-- { + val := 0 + if pizza[r][c] == 'A' { + val = 1 + } + preSum[r][c] = preSum[r][c+1] + preSum[r+1][c] - preSum[r+1][c+1] + val + } + } + + dp := make([][][]int, k) + for i := 0; i < k; i++ { + dp[i] = make([][]int, m) + for j := 0; j < m; j++ { + dp[i][j] = make([]int, n) + } + } + + for r := 0; r < m; r++ { + for c := 0; c < n; c++ { + if preSum[r][c] > 0 { + dp[0][r][c] = 1 + } + } + } + + for cuts := 1; cuts < k; cuts++ { + for r := 0; r < m; r++ { + for c := 0; c < n; c++ { + if preSum[r][c] == 0 { + continue + } + ans := 0 + for nr := r + 1; nr < m; nr++ { + if preSum[r][c]-preSum[nr][c] > 0 { + ans = (ans + dp[cuts-1][nr][c]) % MOD + } + } + for nc := c + 1; nc < n; nc++ { + if preSum[r][c]-preSum[r][nc] > 0 { + ans = (ans + dp[cuts-1][r][nc]) % MOD + } + } + dp[cuts][r][c] = ans + } + } + } + + return dp[k-1][0][0] +} diff --git a/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.java b/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.java new file mode 100644 index 00000000..48de5cc5 --- /dev/null +++ b/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.java @@ -0,0 +1,42 @@ +class Solution { + public int ways(String[] pizza, int k) { + int m = pizza.length, n = pizza[0].length(), MOD = 1_000_000_007; + int[][] preSum = new int[m + 1][n + 1]; + + for (int r = m - 1; r >= 0; r--) { + for (int c = n - 1; c >= 0; c--) { + preSum[r][c] = preSum[r][c + 1] + preSum[r + 1][c] - preSum[r + 1][c + 1] + (pizza[r].charAt(c) == 'A' ? 1 : 0); + } + } + + int[][][] dp = new int[k][m][n]; + + for (int r = 0; r < m; r++) { + for (int c = 0; c < n; c++) { + dp[0][r][c] = preSum[r][c] > 0 ? 1 : 0; + } + } + + for (int cuts = 1; cuts < k; cuts++) { + for (int r = 0; r < m; r++) { + for (int c = 0; c < n; c++) { + if (preSum[r][c] == 0) continue; + int ans = 0; + for (int nr = r + 1; nr < m; nr++) { + if (preSum[r][c] - preSum[nr][c] > 0) { + ans = (ans + dp[cuts - 1][nr][c]) % MOD; + } + } + for (int nc = c + 1; nc < n; nc++) { + if (preSum[r][c] - preSum[r][nc] > 0) { + ans = (ans + dp[cuts - 1][r][nc]) % MOD; + } + } + dp[cuts][r][c] = ans; + } + } + } + + return dp[k - 1][0][0]; + } +} diff --git a/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.kt b/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.kt new file mode 100644 index 00000000..129e7640 --- /dev/null +++ b/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.kt @@ -0,0 +1,44 @@ +class Solution { + fun ways(pizza: Array, k: Int): Int { + val m = pizza.size + val n = pizza[0].length + val MOD = 1_000_000_007 + val preSum = Array(m + 1) { IntArray(n + 1) } + + for (r in m - 1 downTo 0) { + for (c in n - 1 downTo 0) { + preSum[r][c] = preSum[r][c + 1] + preSum[r + 1][c] - preSum[r + 1][c + 1] + (if (pizza[r][c] == 'A') 1 else 0) + } + } + + val dp = Array(k) { Array(m) { IntArray(n) } } + + for (r in 0 until m) { + for (c in 0 until n) { + dp[0][r][c] = if (preSum[r][c] > 0) 1 else 0 + } + } + + for (cuts in 1 until k) { + for (r in 0 until m) { + for (c in 0 until n) { + if (preSum[r][c] == 0) continue + var ans = 0 + for (nr in r + 1 until m) { + if (preSum[r][c] - preSum[nr][c] > 0) { + ans = (ans + dp[cuts - 1][nr][c]) % MOD + } + } + for (nc in c + 1 until n) { + if (preSum[r][c] - preSum[r][nc] > 0) { + ans = (ans + dp[cuts - 1][r][nc]) % MOD + } + } + dp[cuts][r][c] = ans + } + } + } + + return dp[k - 1][0][0] + } +} diff --git a/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.py b/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.py new file mode 100644 index 00000000..6d944e71 --- /dev/null +++ b/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.py @@ -0,0 +1,32 @@ +class Solution: + def ways(self, pizza: List[str], K: int) -> int: + m, n, MOD = len(pizza), len(pizza[0]), 10**9 + 7 + preSum = [[0] * (n + 1) for _ in range(m + 1)] + + for r in range(m - 1, -1, -1): + for c in range(n - 1, -1, -1): + preSum[r][c] = ( + preSum[r][c + 1] + + preSum[r + 1][c] + - preSum[r + 1][c + 1] + + (pizza[r][c] == "A") + ) + + @lru_cache(None) + def dp(k, r, c): + if preSum[r][c] == 0: + return 0 + if k == 0: + return 1 + ans = 0 + + for nr in range(r + 1, m): + if preSum[r][c] - preSum[nr][c] > 0: + ans = (ans + dp(k - 1, nr, c)) % MOD + for nc in range(c + 1, n): + if preSum[r][c] - preSum[r][nc] > 0: + ans = (ans + dp(k - 1, r, nc)) % MOD + + return ans + + return dp(K - 1, 0, 0) diff --git a/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.py2 b/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.py2 new file mode 100644 index 00000000..cddba9f4 --- /dev/null +++ b/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.py2 @@ -0,0 +1,35 @@ +class Solution(object): + def ways(self, pizza, k): + """ + :type pizza: List[str] + :type k: int + :rtype: int + """ + m, n, MOD = len(pizza), len(pizza[0]), 10 ** 9 + 7 + preSum = [[0] * (n + 1) for _ in range(m + 1)] + + for r in range(m - 1, -1, -1): + for c in range(n - 1, -1, -1): + preSum[r][c] = preSum[r][c + 1] + preSum[r + 1][c] - preSum[r + 1][c + 1] + (pizza[r][c] == 'A') + + memo = {} + def dp(k, r, c): + key = (k, r, c) + if key in memo: + return memo[key] + if preSum[r][c] == 0: return 0 + if k == 0: + return 1 + ans = 0 + + for nr in range(r + 1, m): + if preSum[r][c] - preSum[nr][c] > 0: + ans = (ans + dp(k - 1, nr, c)) % MOD + for nc in range(c + 1, n): + if preSum[r][c] - preSum[r][nc] > 0: + ans = (ans + dp(k - 1, r, nc)) % MOD + + memo[key] = ans + return ans + + return dp(k - 1, 0, 0) diff --git a/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.rb b/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.rb new file mode 100644 index 00000000..b54b9372 --- /dev/null +++ b/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.rb @@ -0,0 +1,44 @@ +# @param {String[]} pizza +# @param {Integer} k +# @return {Integer} +def ways(pizza, k) + m, n = pizza.length, pizza[0].length + mod = 10 ** 9 + 7 + pre_sum = Array.new(m + 1) { Array.new(n + 1, 0) } + + (m - 1).downto(0) do |r| + (n - 1).downto(0) do |c| + pre_sum[r][c] = pre_sum[r][c + 1] + pre_sum[r + 1][c] - pre_sum[r + 1][c + 1] + (pizza[r][c] == 'A' ? 1 : 0) + end + end + + dp = Array.new(k) { Array.new(m) { Array.new(n, 0) } } + + (0...m).each do |r| + (0...n).each do |c| + dp[0][r][c] = pre_sum[r][c] > 0 ? 1 : 0 + end + end + + (1...k).each do |cuts| + (0...m).each do |r| + (0...n).each do |c| + next if pre_sum[r][c] == 0 + ans = 0 + (r + 1...m).each do |nr| + if pre_sum[r][c] - pre_sum[nr][c] > 0 + ans = (ans + dp[cuts - 1][nr][c]) % mod + end + end + (c + 1...n).each do |nc| + if pre_sum[r][c] - pre_sum[r][nc] > 0 + ans = (ans + dp[cuts - 1][r][nc]) % mod + end + end + dp[cuts][r][c] = ans + end + end + end + + dp[k - 1][0][0] +end diff --git a/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.rs b/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.rs new file mode 100644 index 00000000..b3bf2891 --- /dev/null +++ b/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.rs @@ -0,0 +1,48 @@ +impl Solution { + pub fn ways(pizza: Vec, k: i32) -> i32 { + let m = pizza.len(); + let n = pizza[0].len(); + let k = k as usize; + let MOD: i32 = 1_000_000_007; + let mut pre_sum = vec![vec![0i32; n + 1]; m + 1]; + let chars: Vec> = pizza.iter().map(|s| s.chars().collect()).collect(); + + for r in (0..m).rev() { + for c in (0..n).rev() { + pre_sum[r][c] = pre_sum[r][c + 1] + pre_sum[r + 1][c] - pre_sum[r + 1][c + 1] + if chars[r][c] == 'A' { 1 } else { 0 }; + } + } + + let mut dp = vec![vec![vec![0i32; n]; m]; k]; + + for r in 0..m { + for c in 0..n { + dp[0][r][c] = if pre_sum[r][c] > 0 { 1 } else { 0 }; + } + } + + for cuts in 1..k { + for r in 0..m { + for c in 0..n { + if pre_sum[r][c] == 0 { + continue; + } + let mut ans = 0; + for nr in r + 1..m { + if pre_sum[r][c] - pre_sum[nr][c] > 0 { + ans = (ans + dp[cuts - 1][nr][c]) % MOD; + } + } + for nc in c + 1..n { + if pre_sum[r][c] - pre_sum[r][nc] > 0 { + ans = (ans + dp[cuts - 1][r][nc]) % MOD; + } + } + dp[cuts][r][c] = ans; + } + } + } + + dp[k - 1][0][0] + } +} diff --git a/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.swift b/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.swift new file mode 100644 index 00000000..335d7512 --- /dev/null +++ b/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.swift @@ -0,0 +1,43 @@ +class Solution { + func ways(_ pizza: [String], _ k: Int) -> Int { + let m = pizza.count, n = pizza[0].count, MOD = 1_000_000_007 + var preSum = Array(repeating: Array(repeating: 0, count: n + 1), count: m + 1) + let chars = pizza.map { Array($0) } + + for r in stride(from: m - 1, through: 0, by: -1) { + for c in stride(from: n - 1, through: 0, by: -1) { + preSum[r][c] = preSum[r][c + 1] + preSum[r + 1][c] - preSum[r + 1][c + 1] + (chars[r][c] == "A" ? 1 : 0) + } + } + + var dp = Array(repeating: Array(repeating: Array(repeating: 0, count: n), count: m), count: k) + + for r in 0.. 0 ? 1 : 0 + } + } + + for cuts in 1.. 0 else { continue } + var ans = 0 + for nr in r + 1.. 0 { + ans = (ans + dp[cuts - 1][nr][c]) % MOD + } + } + for nc in c + 1.. 0 { + ans = (ans + dp[cuts - 1][r][nc]) % MOD + } + } + dp[cuts][r][c] = ans + } + } + } + + return dp[k - 1][0][0] + } +} diff --git a/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.ts b/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.ts new file mode 100644 index 00000000..fdfb638e --- /dev/null +++ b/tests/1001-1500/1444. number-of-ways-of-cutting-a-pizza/sol.ts @@ -0,0 +1,50 @@ +function ways(pizza: string[], k: number): number { + const m = pizza.length, + n = pizza[0].length, + MOD = 1_000_000_007; + const preSum: number[][] = Array.from({ length: m + 1 }, () => + Array(n + 1).fill(0), + ); + + for (let r = m - 1; r >= 0; r--) { + for (let c = n - 1; c >= 0; c--) { + preSum[r][c] = + preSum[r][c + 1] + + preSum[r + 1][c] - + preSum[r + 1][c + 1] + + (pizza[r][c] === "A" ? 1 : 0); + } + } + + const dp: number[][][] = Array.from({ length: k }, () => + Array.from({ length: m }, () => Array(n).fill(0)), + ); + + for (let r = 0; r < m; r++) { + for (let c = 0; c < n; c++) { + dp[0][r][c] = preSum[r][c] > 0 ? 1 : 0; + } + } + + for (let cuts = 1; cuts < k; cuts++) { + for (let r = 0; r < m; r++) { + for (let c = 0; c < n; c++) { + if (preSum[r][c] === 0) continue; + let ans = 0; + for (let nr = r + 1; nr < m; nr++) { + if (preSum[r][c] - preSum[nr][c] > 0) { + ans = (ans + dp[cuts - 1][nr][c]) % MOD; + } + } + for (let nc = c + 1; nc < n; nc++) { + if (preSum[r][c] - preSum[r][nc] > 0) { + ans = (ans + dp[cuts - 1][r][nc]) % MOD; + } + } + dp[cuts][r][c] = ans; + } + } + } + + return dp[k - 1][0][0]; +} diff --git a/tests/1001-1500/1446. consecutive-characters/manifest.yaml b/tests/1001-1500/1446. consecutive-characters/manifest.yaml new file mode 100644 index 00000000..5f984843 --- /dev/null +++ b/tests/1001-1500/1446. consecutive-characters/manifest.yaml @@ -0,0 +1,172 @@ +entry: + id: 1446 + title: "consecutive-characters" + params: + s: + type: string + call: + cpp: "Solution().maxPower({s})" + rust: "Solution::max_power({s})" + python3: "Solution().maxPower({s})" + python2: "Solution().maxPower({s})" + ruby: "max_power({s})" + java: "new Solution().maxPower({s})" + csharp: "new Solution().MaxPower({s})" + kotlin: "Solution().maxPower({s})" + go: "maxPower({s})" + dart: "Solution().maxPower({s})" + swift: "Solution().maxPower({s})" + typescript: "maxPower({s})" +judge: + type: exact +limits: + time_ms: 300 + memory_mb: 300 +oracle: + python3: + call: "Checker().maxPower(s, {result})" + checker: | + class Checker: + def maxPower(self, s, result): + best = run = 1 + for i in range(1, len(s)): + run = run + 1 if s[i] == s[i-1] else 1 + best = max(best, run) + return result == best +seed: 1446 +tests: + - name: ex1 + in: + s: leetcode + out: 2 + - name: ex2 + in: + s: abbcccddddeeeeedcba + out: 5 + - name: single + in: + s: a + out: 1 + - name: all_a + in: + s: aaaaa + out: 5 + - name: all_b + in: + s: bbbbbbb + out: 7 + - name: alternating + in: + s: abababab + out: 1 + - name: pair + in: + s: aa + out: 2 + - name: three + in: + s: abc + out: 1 + - name: middle_run + in: + s: abccdef + out: 2 + - name: long_middle + in: + s: abbbbbc + - name: runs_a + in: + s: aabbcc + - name: runs_b + in: + s: aaabbbcccc + - name: runs_c + in: + s: zzzzyyxxx + - name: runs_d + in: + s: abcdddddef + - name: runs_e + in: + s: qqqwerty + - name: runs_f + in: + s: wwwwxyz + - name: runs_g + in: + s: mnmmmmmop + - name: runs_h + in: + s: aabaaaaac + - name: runs_i + in: + s: xyzzyzz + - name: runs_j + in: + s: kkkkklmnop + - name: length_ten + in: + s: abcdefghij + - name: length_twelve + in: + s: aabbccddeeff + - name: length_fifteen + in: + s: aaaaaaaaaaaaaaa + - name: length_mixed_a + in: + s: aaabccccdde + - name: length_mixed_b + in: + s: abcbbbbbbdef + - name: length_mixed_c + in: + s: aaaaaabcdefff + - name: boundaries_a + in: + s: zzzzzzzzzzy + - name: boundaries_b + in: + s: aaaaaaaaaaz + - name: distinct_long + in: + s: abcdefghijklmnopqrstuvwxyz + - name: repeated_blocks_a + in: + s: aaabbbcccdddeee + - name: repeated_blocks_b + in: + s: aabbbbbccdddd + - name: repeated_blocks_c + in: + s: xyyyyyzzzzza + - name: run_one + in: + s: qwertyuiop + - name: run_two + in: + s: qqaazzxxcc + - name: final_a + in: + s: abcdefffffghij + - name: max_all_same + in: + s: + gen: "str" + len: 500 + alphabet: "a" + - name: max_binary_runs + in: + s: + gen: "str" + len: 500 + alphabet: "ab" + - name: longest_run_at_start + in: + s: bbbbbba + - name: longest_run_at_end + in: + s: abbbbbbb + - name: separated_equal_runs + in: + s: aaabaaaacaa diff --git a/tests/1001-1500/1446. consecutive-characters/sol.cpp b/tests/1001-1500/1446. consecutive-characters/sol.cpp new file mode 100644 index 00000000..711ea54c --- /dev/null +++ b/tests/1001-1500/1446. consecutive-characters/sol.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int maxPower(string s) { + int maxcnt = 0; + int cnt = 0; + for (int i = 1; i < s.length(); i++) { + if (s[i] == s[i - 1]) { + cnt++; + } else { + cnt = 0; + } + maxcnt = max(cnt, maxcnt); + } + return maxcnt + 1; + } +}; diff --git a/tests/1001-1500/1446. consecutive-characters/sol.cs b/tests/1001-1500/1446. consecutive-characters/sol.cs new file mode 100644 index 00000000..1c1f76c8 --- /dev/null +++ b/tests/1001-1500/1446. consecutive-characters/sol.cs @@ -0,0 +1,15 @@ +public class Solution { + public int MaxPower(string s) { + int maxcnt = 0; + int cnt = 0; + for (int i = 1; i < s.Length; i++) { + if (s[i] == s[i - 1]) { + cnt++; + } else { + cnt = 0; + } + maxcnt = Math.Max(cnt, maxcnt); + } + return maxcnt + 1; + } +} diff --git a/tests/1001-1500/1446. consecutive-characters/sol.dart b/tests/1001-1500/1446. consecutive-characters/sol.dart new file mode 100644 index 00000000..9ff1363a --- /dev/null +++ b/tests/1001-1500/1446. consecutive-characters/sol.dart @@ -0,0 +1,17 @@ +class Solution { + int maxPower(String s) { + int maxcnt = 0; + int cnt = 0; + for (int i = 1; i < s.length; i++) { + if (s[i] == s[i - 1]) { + cnt++; + } else { + cnt = 0; + } + if (cnt > maxcnt) { + maxcnt = cnt; + } + } + return maxcnt + 1; + } +} diff --git a/tests/1001-1500/1446. consecutive-characters/sol.go b/tests/1001-1500/1446. consecutive-characters/sol.go new file mode 100644 index 00000000..707e2303 --- /dev/null +++ b/tests/1001-1500/1446. consecutive-characters/sol.go @@ -0,0 +1,15 @@ +func maxPower(s string) int { + maxcnt := 0 + cnt := 0 + for i := 1; i < len(s); i++ { + if s[i] == s[i-1] { + cnt++ + } else { + cnt = 0 + } + if cnt > maxcnt { + maxcnt = cnt + } + } + return maxcnt + 1 +} diff --git a/tests/1001-1500/1446. consecutive-characters/sol.java b/tests/1001-1500/1446. consecutive-characters/sol.java new file mode 100644 index 00000000..a1410df9 --- /dev/null +++ b/tests/1001-1500/1446. consecutive-characters/sol.java @@ -0,0 +1,15 @@ +class Solution { + public int maxPower(String s) { + int maxcnt = 0; + int cnt = 0; + for (int i = 1; i < s.length(); i++) { + if (s.charAt(i) == s.charAt(i - 1)) { + cnt++; + } else { + cnt = 0; + } + maxcnt = Math.max(cnt, maxcnt); + } + return maxcnt + 1; + } +} diff --git a/tests/1001-1500/1446. consecutive-characters/sol.kt b/tests/1001-1500/1446. consecutive-characters/sol.kt new file mode 100644 index 00000000..cd0274f2 --- /dev/null +++ b/tests/1001-1500/1446. consecutive-characters/sol.kt @@ -0,0 +1,15 @@ +class Solution { + fun maxPower(s: String): Int { + var maxcnt = 0 + var cnt = 0 + for (i in 1 until s.length) { + if (s[i] == s[i - 1]) { + cnt++ + } else { + cnt = 0 + } + maxcnt = maxOf(cnt, maxcnt) + } + return maxcnt + 1 + } +} diff --git a/tests/1001-1500/1446. consecutive-characters/sol.py b/tests/1001-1500/1446. consecutive-characters/sol.py new file mode 100644 index 00000000..29dd2c26 --- /dev/null +++ b/tests/1001-1500/1446. consecutive-characters/sol.py @@ -0,0 +1,13 @@ +class Solution(object): + def maxPower(self, s): + maxcnt = 0 + cnt = 0 + + for i in range(1, len(s)): + if s[i] == s[i - 1]: + cnt += 1 + + else: + cnt = 0 + maxcnt = max(cnt, maxcnt) + return maxcnt + 1 diff --git a/tests/1001-1500/1446. consecutive-characters/sol.py2 b/tests/1001-1500/1446. consecutive-characters/sol.py2 new file mode 100644 index 00000000..0611a68d --- /dev/null +++ b/tests/1001-1500/1446. consecutive-characters/sol.py2 @@ -0,0 +1,14 @@ +class Solution(object): + def maxPower(self, s): + maxcnt=0 + cnt=0 + + for i in range(1,len(s)): + + if s[i]==s[i-1]: + cnt+=1 + + else: + cnt=0 + maxcnt=max(cnt,maxcnt) + return maxcnt+1 diff --git a/tests/1001-1500/1446. consecutive-characters/sol.rb b/tests/1001-1500/1446. consecutive-characters/sol.rb new file mode 100644 index 00000000..66c6cc29 --- /dev/null +++ b/tests/1001-1500/1446. consecutive-characters/sol.rb @@ -0,0 +1,15 @@ +# @param {String} s +# @return {Integer} +def max_power(s) + maxcnt = 0 + cnt = 0 + (1...s.length).each do |i| + if s[i] == s[i-1] + cnt += 1 + else + cnt = 0 + end + maxcnt = [cnt, maxcnt].max + end + maxcnt + 1 +end diff --git a/tests/1001-1500/1446. consecutive-characters/sol.rs b/tests/1001-1500/1446. consecutive-characters/sol.rs new file mode 100644 index 00000000..45c325dd --- /dev/null +++ b/tests/1001-1500/1446. consecutive-characters/sol.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn max_power(s: String) -> i32 { + let mut maxcnt = 0; + let mut cnt = 0; + let bytes = s.as_bytes(); + for i in 1..bytes.len() { + if bytes[i] == bytes[i - 1] { + cnt += 1; + } else { + cnt = 0; + } + maxcnt = maxcnt.max(cnt); + } + maxcnt + 1 + } +} diff --git a/tests/1001-1500/1446. consecutive-characters/sol.swift b/tests/1001-1500/1446. consecutive-characters/sol.swift new file mode 100644 index 00000000..ac0cd3f4 --- /dev/null +++ b/tests/1001-1500/1446. consecutive-characters/sol.swift @@ -0,0 +1,16 @@ +class Solution { + func maxPower(_ s: String) -> Int { + var maxcnt = 0 + var cnt = 0 + let chars = Array(s) + for i in 1.. n or numerator < 1 or numerator >= denominator: + return False + if math.gcd(numerator, denominator) != 1: + return False + return set(result) == expected + +seed: 1447 + +tests: + - name: "example-two" + in: + n: 2 + - name: "example-three" + in: + n: 3 + - name: "example-four" + in: + n: 4 + - name: "minimum-one" + in: + n: 1 + - name: "five" + in: + n: 5 + - name: "six-composite" + in: + n: 6 + - name: "seven-prime" + in: + n: 7 + - name: "eight-power" + in: + n: 8 + - name: "nine-composite" + in: + n: 9 + - name: "ten" + in: + n: 10 + - name: "twelve" + in: + n: 12 + - name: "fifteen" + in: + n: 15 + - name: "sixteen" + in: + n: 16 + - name: "eighteen" + in: + n: 18 + - name: "twenty" + in: + n: 20 + - name: "twenty-four" + in: + n: 24 + - name: "twenty-five-square" + in: + n: 25 + - name: "twenty-seven" + in: + n: 27 + - name: "twenty-eight" + in: + n: 28 + - name: "thirty" + in: + n: 30 + - name: "thirty-two" + in: + n: 32 + - name: "thirty-five" + in: + n: 35 + - name: "thirty-six-square" + in: + n: 36 + - name: "forty" + in: + n: 40 + - name: "forty-two" + in: + n: 42 + - name: "forty-five" + in: + n: 45 + - name: "forty-nine-square" + in: + n: 49 + - name: "fifty" + in: + n: 50 + - name: "fifty-four" + in: + n: 54 + - name: "sixty" + in: + n: 60 + - name: "sixty-four-square" + in: + n: 64 + - name: "seventy-two" + in: + n: 72 + - name: "eighty-one-square" + in: + n: 81 + - name: "ninety-seven-prime" + in: + n: 97 + - name: "generated-boundary-range-a" + in: + n: + gen: "int" + min: 1 + max: 100 + seed: 144701 + - name: "generated-boundary-range-b" + in: + n: + gen: "int" + min: 1 + max: 100 + seed: 144702 + - name: "generated-boundary-range-c" + in: + n: + gen: "int" + min: 1 + max: 100 + seed: 144703 + - name: "generated-boundary-range-d" + in: + n: + gen: "int" + min: 1 + max: 100 + seed: 144704 + - name: "generated-boundary-range-e" + in: + n: + gen: "int" + min: 1 + max: 100 + seed: 144705 + - name: "generated-boundary-range-f" + in: + n: + gen: "int" + min: 1 + max: 100 + seed: 144706 diff --git a/tests/1001-1500/1447. simplified-fractions/sol.cpp b/tests/1001-1500/1447. simplified-fractions/sol.cpp new file mode 100644 index 00000000..8ece8399 --- /dev/null +++ b/tests/1001-1500/1447. simplified-fractions/sol.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + vector simplifiedFractions(int n) { + vector fractions; + for (int numerator = 1; numerator < n; numerator++) { + for (int denominator = numerator + 1; denominator <= n; denominator++) { + if (gcd(numerator, denominator) == 1) { + fractions.push_back(to_string(numerator) + "/" + to_string(denominator)); + } + } + } + return fractions; + } +}; diff --git a/tests/1001-1500/1447. simplified-fractions/sol.cs b/tests/1001-1500/1447. simplified-fractions/sol.cs new file mode 100644 index 00000000..5aa397e1 --- /dev/null +++ b/tests/1001-1500/1447. simplified-fractions/sol.cs @@ -0,0 +1,22 @@ +public class Solution { + public IList SimplifiedFractions(int n) { + IList fractions = new List(); + for (int numerator = 1; numerator < n; numerator++) { + for (int denominator = numerator + 1; denominator <= n; denominator++) { + if (Gcd(numerator, denominator) == 1) { + fractions.Add($"{numerator}/{denominator}"); + } + } + } + return fractions; + } + + private int Gcd(int a, int b) { + while (b != 0) { + int temp = b; + b = a % b; + a = temp; + } + return a; + } +} diff --git a/tests/1001-1500/1447. simplified-fractions/sol.dart b/tests/1001-1500/1447. simplified-fractions/sol.dart new file mode 100644 index 00000000..e4f9e6d2 --- /dev/null +++ b/tests/1001-1500/1447. simplified-fractions/sol.dart @@ -0,0 +1,22 @@ +class Solution { + List simplifiedFractions(int n) { + List fractions = []; + for (int numerator = 1; numerator < n; numerator++) { + for (int denominator = numerator + 1; denominator <= n; denominator++) { + if (gcd(numerator, denominator) == 1) { + fractions.add("$numerator/$denominator"); + } + } + } + return fractions; + } + + int gcd(int a, int b) { + while (b != 0) { + int temp = b; + b = a % b; + a = temp; + } + return a; + } +} diff --git a/tests/1001-1500/1447. simplified-fractions/sol.go b/tests/1001-1500/1447. simplified-fractions/sol.go new file mode 100644 index 00000000..12f72653 --- /dev/null +++ b/tests/1001-1500/1447. simplified-fractions/sol.go @@ -0,0 +1,18 @@ +func simplifiedFractions(n int) []string { + fractions := make([]string, 0) + for numerator := 1; numerator < n; numerator++ { + for denominator := numerator + 1; denominator <= n; denominator++ { + if gcd(numerator, denominator) == 1 { + fractions = append(fractions, fmt.Sprintf("%d/%d", numerator, denominator)) + } + } + } + return fractions +} + +func gcd(a, b int) int { + for b != 0 { + a, b = b, a%b + } + return a +} diff --git a/tests/1001-1500/1447. simplified-fractions/sol.java b/tests/1001-1500/1447. simplified-fractions/sol.java new file mode 100644 index 00000000..aea0bd45 --- /dev/null +++ b/tests/1001-1500/1447. simplified-fractions/sol.java @@ -0,0 +1,22 @@ +class Solution { + public List simplifiedFractions(int n) { + List fractions = new ArrayList<>(); + for (int numerator = 1; numerator < n; numerator++) { + for (int denominator = numerator + 1; denominator <= n; denominator++) { + if (gcd(numerator, denominator) == 1) { + fractions.add(numerator + "/" + denominator); + } + } + } + return fractions; + } + + private int gcd(int a, int b) { + while (b != 0) { + int temp = b; + b = a % b; + a = temp; + } + return a; + } +} diff --git a/tests/1001-1500/1447. simplified-fractions/sol.kt b/tests/1001-1500/1447. simplified-fractions/sol.kt new file mode 100644 index 00000000..e6410662 --- /dev/null +++ b/tests/1001-1500/1447. simplified-fractions/sol.kt @@ -0,0 +1,24 @@ +class Solution { + fun simplifiedFractions(n: Int): List { + val fractions = mutableListOf() + for (numerator in 1 until n) { + for (denominator in numerator + 1..n) { + if (gcd(numerator, denominator) == 1) { + fractions.add("$numerator/$denominator") + } + } + } + return fractions + } + + 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/1001-1500/1447. simplified-fractions/sol.py b/tests/1001-1500/1447. simplified-fractions/sol.py new file mode 100644 index 00000000..457b63b3 --- /dev/null +++ b/tests/1001-1500/1447. simplified-fractions/sol.py @@ -0,0 +1,11 @@ +from math import gcd + + +class Solution: + def simplifiedFractions(self, n: int) -> List[str]: + fractions = [] + for numerator in range(1, n): + for denominator in range(numerator + 1, n + 1): + if gcd(numerator, denominator) == 1: + fractions.append(f"{numerator}/{denominator}") + return fractions diff --git a/tests/1001-1500/1447. simplified-fractions/sol.py2 b/tests/1001-1500/1447. simplified-fractions/sol.py2 new file mode 100644 index 00000000..b6f8fe6a --- /dev/null +++ b/tests/1001-1500/1447. simplified-fractions/sol.py2 @@ -0,0 +1,18 @@ +class Solution(object): + def simplifiedFractions(self, n): + """ + :type n: int + :rtype: List[str] + """ + fractions = [] + + def gcd(a, b): + while b: + a, b = b, a % b + return a + + for numerator in range(1, n): + for denominator in range(numerator + 1, n + 1): + if gcd(numerator, denominator) == 1: + fractions.append("{}/{}".format(numerator, denominator)) + return fractions diff --git a/tests/1001-1500/1447. simplified-fractions/sol.rb b/tests/1001-1500/1447. simplified-fractions/sol.rb new file mode 100644 index 00000000..dcdbcc29 --- /dev/null +++ b/tests/1001-1500/1447. simplified-fractions/sol.rb @@ -0,0 +1,13 @@ +# @param {Integer} n +# @return {String[]} +def simplified_fractions(n) + fractions = [] + (1...n).each do |numerator| + (numerator+1..n).each do |denominator| + if numerator.gcd(denominator) == 1 + fractions << "#{numerator}/#{denominator}" + end + end + end + fractions +end diff --git a/tests/1001-1500/1447. simplified-fractions/sol.rs b/tests/1001-1500/1447. simplified-fractions/sol.rs new file mode 100644 index 00000000..6982a9ca --- /dev/null +++ b/tests/1001-1500/1447. simplified-fractions/sol.rs @@ -0,0 +1,22 @@ +impl Solution { + pub fn simplified_fractions(n: i32) -> Vec { + let mut fractions = Vec::new(); + for numerator in 1..n { + for denominator in (numerator + 1)..=n { + if Self::gcd(numerator, denominator) == 1 { + fractions.push(format!("{}/{}", numerator, denominator)); + } + } + } + fractions + } + + 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/1001-1500/1447. simplified-fractions/sol.swift b/tests/1001-1500/1447. simplified-fractions/sol.swift new file mode 100644 index 00000000..57a848bc --- /dev/null +++ b/tests/1001-1500/1447. simplified-fractions/sol.swift @@ -0,0 +1,24 @@ +class Solution { + func simplifiedFractions(_ n: Int) -> [String] { + var fractions: [String] = [] + for numerator in 1.. Int { + var x = a + var y = b + while y != 0 { + let temp = y + y = x % y + x = temp + } + return x + } +} diff --git a/tests/1001-1500/1447. simplified-fractions/sol.ts b/tests/1001-1500/1447. simplified-fractions/sol.ts new file mode 100644 index 00000000..3cf057e9 --- /dev/null +++ b/tests/1001-1500/1447. simplified-fractions/sol.ts @@ -0,0 +1,18 @@ +function simplifiedFractions(n: number): string[] { + const fractions: string[] = []; + for (let numerator = 1; numerator < n; numerator++) { + for (let denominator = numerator + 1; denominator <= n; denominator++) { + if (gcd(numerator, denominator) === 1) { + fractions.push(`${numerator}/${denominator}`); + } + } + } + return fractions; +} + +function gcd(a: number, b: number): number { + while (b !== 0) { + [a, b] = [b, a % b]; + } + return a; +} diff --git a/tests/1001-1500/1448. count-good-nodes-in-binary-tree/manifest.yaml b/tests/1001-1500/1448. count-good-nodes-in-binary-tree/manifest.yaml new file mode 100644 index 00000000..c1fd28ea --- /dev/null +++ b/tests/1001-1500/1448. count-good-nodes-in-binary-tree/manifest.yaml @@ -0,0 +1,236 @@ +entry: + id: 1448 + title: "count-good-nodes-in-binary-tree" + params: + root: + type: tree_node + call: + cpp: "Solution().goodNodes({root})" + rust: "Solution::good_nodes({root})" + python3: "Solution().goodNodes({root})" + python2: "Solution().goodNodes({root})" + ruby: "good_nodes({root})" + java: "new Solution().goodNodes({root})" + csharp: "new Solution().GoodNodes({root})" + kotlin: "Solution().goodNodes({root})" + go: "goodNodes({root})" + dart: "Solution().goodNodes({root})" + swift: "Solution().goodNodes({root})" + typescript: "goodNodes({root})" +judge: + type: "exact" +limits: + time_ms: 900 + memory_mb: 300 +oracle: + python3: + call: "Checker().goodNodes(root, {result})" + checker: | + class Checker: + def goodNodes(self, root, result): + class Node: + def __init__(self, value): + self.val = value + self.left = None + self.right = None + nodes = [Node(value) if value is not None else None for value in root] + child = 1 + for node in nodes: + if node is not None: + if child < len(nodes): + node.left = nodes[child] + child += 1 + if child < len(nodes): + node.right = nodes[child] + child += 1 + root = nodes[0] + def visit(node, path_max): + if node is None: + return 0 + good = 1 if node.val >= path_max else 0 + next_max = max(path_max, node.val) + return good + visit(node.left, next_max) + visit(node.right, next_max) + return result == visit(root, root.val) +seed: 1448 +tests: + - name: "single-root" + in: + root: [3] + out: 1 + - name: "official-balanced" + in: + root: [3, 1, 4, 3, null, 1, 5] + out: 4 + - name: "official-left-chain" + in: + root: [3, 3, null, 4, 2] + out: 3 + - name: "two-equal" + in: + root: [5, 5, 5] + out: 3 + - name: "decreasing-left" + in: + root: [5, 4, null, 3, null, 2] + out: 1 + - name: "increasing-left" + in: + root: [1, 2, null, 3, null, 4] + out: 4 + - name: "decreasing-right" + in: + root: [8, null, 7, null, 6, null, 5] + out: 1 + - name: "increasing-right" + in: + root: [1, null, 2, null, 3, null, 4] + out: 4 + - name: "negative-root" + in: + root: [-5, -6, -4, -7, null, -3, -2] + out: 4 + - name: "all-negative-decreasing" + in: + root: [-1, -2, -3, -4, -5, -6, -7] + out: 1 + - name: "all-negative-increasing" + in: + root: [-7, -6, -5, -4, -3, -2, -1] + out: 7 + - name: "root-minimum" + in: + root: [-10000, -9999, -10000] + out: 3 + - name: "root-maximum" + in: + root: [10000, 9999, 10000] + out: 2 + - name: "large-positive-leaf" + in: + root: [0, -5, 7] + out: 2 + - name: "large-negative-leaf" + in: + root: [0, -5, -7] + out: 1 + - name: "zigzag-highs" + in: + root: [5, 4, 6, 3, 7, 2, 8] + out: 4 + - name: "zigzag-lows" + in: + root: [5, 6, 4, 7, 3, 8, 2] + out: 4 + - name: "complete-constant" + in: + root: [9, 9, 9, 9, 9, 9, 9] + out: 7 + - name: "complete-descending" + in: + root: [10, 9, 8, 7, 6, 5, 4] + out: 1 + - name: "complete-ascending-levels" + in: + root: [1, 2, 2, 3, 3, 3, 3] + out: 7 + - name: "left-heavy-mixed" + in: + root: [6, 3, 8, 2, 5, null, 9, 1, null, 4] + out: 3 + - name: "right-heavy-mixed" + in: + root: [6, 3, 8, null, 5, 7, 9, null, null, 6, 10] + out: 4 + - name: "missing-middle-child" + in: + root: [4, 2, 6, 1, null, 5, 7, null, null, null, null, 4] + out: 3 + - name: "repeated-plateaus" + in: + root: [2, 2, 3, 2, 2, 3, 1, 2] + out: 7 + - name: "root-negative-branches" + in: + root: [-2, -3, -1, -4, -2, -2, 0] + out: 4 + - name: "alternating-signs" + in: + root: [0, -1, 1, 2, -2, 2, -3] + out: 4 + - name: "deep-left-records" + in: + root: [1, 2, null, 1, null, 3, null, 2] + out: 3 + - name: "deep-right-records" + in: + root: [4, null, 5, null, 3, null, 6, null, 2] + out: 3 + - name: "wide-records" + in: + root: [5, 1, 9, 0, 2, 8, 10] + out: 3 + - name: "wide-no-new-records" + in: + root: [10, 5, 9, 1, 4, 8, 7] + out: 1 + - name: "boundary-values" + in: + root: [-10000, 10000, -10000, 9999, null, -9999] + out: 4 + - name: "duplicate-boundary" + in: + root: [10000, 10000, 9999, 10000, 9998, null, 9999] + out: 3 + - name: "balanced-random-one" + in: + root: [7, 3, 11, 5, 1, 9, 13, 4, 6, 0, 2, 8, 10, 12, 14] + out: 4 + - name: "balanced-random-two" + in: + root: [0, -3, 4, -5, -2, 2, 6, -6, -4, -1, 1, 3, 5, 7, 8] + out: 7 + - name: "sparse-seven" + in: + root: [8, 3, null, 2, 5, null, null, 1, null, 4] + out: 1 + - name: "sparse-right-record" + in: + root: [2, null, 1, null, 3, null, 0, null, 4] + out: 3 + - name: "all-two-levels" + in: + root: [2, 1, 2, 0, 1, 1, 2] + out: 3 + - name: "stress-complete-maximum" + seed: 144801 + in: + root: + gen: "array" + len: 100000 + elemType: "int" + of: + gen: "int" + min: -10000 + max: 10000 + - name: "stress-complete-near-maximum" + seed: 144802 + in: + root: + gen: "array" + len: 99999 + elemType: "int" + of: + gen: "int" + min: -10000 + max: 10000 + - name: "stress-complete-mid-large" + seed: 144803 + in: + root: + gen: "array" + len: 75000 + elemType: "int" + of: + gen: "int" + min: -10000 + max: 10000 diff --git a/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.cpp b/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.cpp new file mode 100644 index 00000000..efd539b2 --- /dev/null +++ b/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.cpp @@ -0,0 +1,25 @@ +/** + * 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: + int goodNodes(TreeNode* root) { + function dfs = [&](TreeNode* node, int maxSoFar) -> int { + if (!node) return 0; + int count = node->val >= maxSoFar ? 1 : 0; + int newMax = max(maxSoFar, node->val); + count += dfs(node->left, newMax); + count += dfs(node->right, newMax); + return count; + }; + return dfs(root, root->val); + } +}; diff --git a/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.cs b/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.cs new file mode 100644 index 00000000..a4b8de3b --- /dev/null +++ b/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.cs @@ -0,0 +1,26 @@ +/** + * 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 GoodNodes(TreeNode root) { + int Dfs(TreeNode node, int maxSoFar) { + if (node == null) return 0; + int count = node.val >= maxSoFar ? 1 : 0; + int newMax = Math.Max(maxSoFar, node.val); + count += Dfs(node.left, newMax); + count += Dfs(node.right, newMax); + return count; + } + return Dfs(root, root.val); + } +} diff --git a/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.dart b/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.dart new file mode 100644 index 00000000..3f6bfe40 --- /dev/null +++ b/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.dart @@ -0,0 +1,13 @@ +class Solution { + int goodNodes(TreeNode? root) { + int dfs(TreeNode? node, int maxSoFar) { + if (node == null) return 0; + + final int nextMax = node.val > maxSoFar ? node.val : maxSoFar; + final int good = node.val >= maxSoFar ? 1 : 0; + return good + dfs(node.left, nextMax) + dfs(node.right, nextMax); + } + + return dfs(root, root!.val); + } +} diff --git a/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.go b/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.go new file mode 100644 index 00000000..4ae7f597 --- /dev/null +++ b/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.go @@ -0,0 +1,28 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func goodNodes(root *TreeNode) int { + var dfs func(*TreeNode, int) int + dfs = func(node *TreeNode, maxSoFar int) int { + if node == nil { + return 0 + } + count := 0 + if node.Val >= maxSoFar { + count = 1 + } + newMax := maxSoFar + if node.Val > newMax { + newMax = node.Val + } + count += dfs(node.Left, newMax) + count += dfs(node.Right, newMax) + return count + } + return dfs(root, root.Val) +} diff --git a/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.java b/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.java new file mode 100644 index 00000000..9d447cb0 --- /dev/null +++ b/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.java @@ -0,0 +1,29 @@ +/** + * 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 goodNodes(TreeNode root) { + return dfs(root, root.val); + } + + private int dfs(TreeNode node, int maxSoFar) { + if (node == null) return 0; + int count = node.val >= maxSoFar ? 1 : 0; + int newMax = Math.max(maxSoFar, node.val); + count += dfs(node.left, newMax); + count += dfs(node.right, newMax); + return count; + } +} diff --git a/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.kt b/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.kt new file mode 100644 index 00000000..d64aa2f6 --- /dev/null +++ b/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.kt @@ -0,0 +1,23 @@ +/** + * 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 goodNodes(root: TreeNode?): Int { + fun dfs(node: TreeNode?, maxSoFar: Int): Int { + if (node == null) return 0 + var count = if (node.`val` >= maxSoFar) 1 else 0 + val newMax = maxOf(maxSoFar, node.`val`) + count += dfs(node.left, newMax) + count += dfs(node.right, newMax) + return count + } + return dfs(root, root!!.`val`) + } +} diff --git a/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.py b/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.py new file mode 100644 index 00000000..39b928f4 --- /dev/null +++ b/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.py @@ -0,0 +1,28 @@ +# 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 goodNodes(self, root: TreeNode) -> int: + # helper dfs returns count of good nodes from this node down + def dfs(node, max_so_far): + if not node: + return 0 # base case: null node, 0 good nodes + + # is this node good? + count = 1 if node.val >= max_so_far else 0 + + # update max for children + new_max = max(max_so_far, node.val) + + # count good nodes in left and right subtrees + count += dfs(node.left, new_max) + count += dfs(node.right, new_max) + + return count + + return dfs(root, root.val) diff --git a/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.py2 b/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.py2 new file mode 100644 index 00000000..09f95a85 --- /dev/null +++ b/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.py2 @@ -0,0 +1,22 @@ +# 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 goodNodes(self, root): + """ + :type root: TreeNode + :rtype: int + """ + def dfs(node, max_so_far): + if not node: + return 0 + count = 1 if node.val >= max_so_far else 0 + new_max = max(max_so_far, node.val) + count += dfs(node.left, new_max) + count += dfs(node.right, new_max) + return count + + return dfs(root, root.val) diff --git a/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.rb b/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.rb new file mode 100644 index 00000000..8832e888 --- /dev/null +++ b/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.rb @@ -0,0 +1,22 @@ +# 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 {Integer} +def good_nodes(root) + dfs = lambda do |node, max_so_far| + return 0 if node.nil? + count = node.val >= max_so_far ? 1 : 0 + new_max = [max_so_far, node.val].max + count += dfs.call(node.left, new_max) + count += dfs.call(node.right, new_max) + count + end + dfs.call(root, root.val) +end diff --git a/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.rs b/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.rs new file mode 100644 index 00000000..53b05eb5 --- /dev/null +++ b/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.rs @@ -0,0 +1,39 @@ +// 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 good_nodes(root: Option>>) -> i32 { + fn dfs(node: Option<&Rc>>, max_so_far: i32) -> i32 { + match node { + None => 0, + Some(n) => { + let n = n.borrow(); + let count = if n.val >= max_so_far { 1 } else { 0 }; + let new_max = max_so_far.max(n.val); + count + dfs(n.left.as_ref(), new_max) + dfs(n.right.as_ref(), new_max) + } + } + } + if let Some(root_node) = &root { + let val = root_node.borrow().val; + dfs(Some(root_node), val) + } else { + 0 + } + } +} diff --git a/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.swift b/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.swift new file mode 100644 index 00000000..bfb62b5c --- /dev/null +++ b/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.swift @@ -0,0 +1,28 @@ +/** + * 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 goodNodes(_ root: TreeNode?) -> Int { + func dfs(_ node: TreeNode?, _ maxSoFar: Int) -> Int { + guard let node = node else { return 0 } + var count = node.val >= maxSoFar ? 1 : 0 + let newMax = max(maxSoFar, node.val) + count += dfs(node.left, newMax) + count += dfs(node.right, newMax) + return count + } + return dfs(root, root!.val) + } +} diff --git a/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.ts b/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.ts new file mode 100644 index 00000000..257fafb6 --- /dev/null +++ b/tests/1001-1500/1448. count-good-nodes-in-binary-tree/sol.ts @@ -0,0 +1,25 @@ +/** + * 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 goodNodes(root: TreeNode | null): number { + const dfs = (node: TreeNode | null, maxSoFar: number): number => { + if (!node) return 0; + let count = node.val >= maxSoFar ? 1 : 0; + const newMax = Math.max(maxSoFar, node.val); + count += dfs(node.left, newMax); + count += dfs(node.right, newMax); + return count; + }; + return dfs(root, root!.val); +} diff --git a/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/manifest.yaml b/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/manifest.yaml new file mode 100644 index 00000000..afc8571d --- /dev/null +++ b/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/manifest.yaml @@ -0,0 +1,278 @@ +entry: + id: 1449 + title: "form-largest-integer-with-digits-that-add-up-to-target" + params: + cost: + type: array + items: + type: int + target: + type: int + call: + cpp: "Solution().largestNumber({cost}, {target})" + rust: "Solution::largest_number({cost}, {target})" + python3: "Solution().largestNumber({cost}, {target})" + python2: "Solution().largestNumber({cost}, {target})" + ruby: "largest_number({cost}, {target})" + java: "new Solution().largestNumber({cost}, {target})" + csharp: "new Solution().LargestNumber({cost}, {target})" + kotlin: "Solution().largestNumber({cost}, {target})" + go: "largestNumber({cost}, {target})" + dart: "Solution().largestNumber({cost}, {target})" + swift: "Solution().largestNumber({cost}, {target})" + typescript: "largestNumber({cost}, {target})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().largestNumber(cost, target, {result})" + checker: | + class Checker: + def largestNumber(self, cost, target, result): + if len(cost) != 9: + return False + best = [None] * (target + 1) + best[0] = "" + for total in range(1, target + 1): + choices = [] + for digit, c in enumerate(cost, 1): + if total >= c and best[total - c] is not None: + choices.append(str(digit) + best[total - c]) + if choices: + best[total] = max(choices, key=lambda s: (len(s), s)) + if best[target] is None: + return isinstance(result, str) and result == "0" + if not isinstance(result, str): + return False + return result == best[target] + +seed: 1449 + +tests: + - name: "example_one" + in: + cost: [4, 3, 2, 5, 6, 7, 2, 5, 5] + target: 9 + - name: "example_two" + in: + cost: [7, 6, 5, 5, 5, 6, 8, 7, 8] + target: 12 + - name: "example_three_impossible" + in: + cost: [2, 4, 6, 2, 4, 6, 4, 4, 4] + target: 5 + out: '"0"' + - name: "single_digit_one" + in: + cost: [1, 9, 9, 9, 9, 9, 9, 9, 9] + target: 1 + - name: "single_digit_nine" + in: + cost: [9, 9, 9, 9, 9, 9, 9, 9, 1] + target: 1 + - name: "all_costs_one" + in: + cost: [1, 1, 1, 1, 1, 1, 1, 1, 1] + target: 12 + - name: "all_costs_nine" + in: + cost: [9, 9, 9, 9, 9, 9, 9, 9, 9] + target: 8 + out: '"0"' + - name: "target_equals_cheapest" + in: + cost: [8, 7, 6, 5, 4, 3, 2, 9, 1] + target: 1 + - name: "highest_digit_tie" + in: + cost: [2, 2, 2, 2, 2, 2, 2, 2, 2] + target: 6 + - name: "longer_beats_digit" + in: + cost: [3, 3, 3, 3, 3, 3, 3, 3, 4] + target: 12 + - name: "digit_nine_expensive" + in: + cost: [1, 1, 1, 1, 1, 1, 1, 1, 10] + target: 10 + - name: "digit_nine_affordable" + in: + cost: [2, 2, 2, 2, 2, 2, 2, 2, 1] + target: 4 + - name: "mixed_small_target" + in: + cost: [2, 3, 4, 5, 6, 7, 8, 9, 10] + target: 6 + - name: "mixed_target_seven" + in: + cost: [5, 4, 3, 2, 1, 6, 7, 8, 9] + target: 7 + - name: "unreachable_gap" + in: + cost: [4, 6, 8, 10, 12, 14, 16, 18, 20] + target: 7 + out: '"0"' + - name: "even_costs_reachable" + in: + cost: [2, 4, 6, 8, 10, 12, 14, 16, 18] + target: 20 + - name: "all_distinct" + in: + cost: [9, 8, 7, 6, 5, 4, 3, 2, 1] + target: 15 + - name: "high_digits_cheap" + in: + cost: [8, 8, 8, 8, 8, 8, 1, 1, 1] + target: 10 + - name: "low_digits_cheap" + in: + cost: [1, 2, 3, 4, 5, 6, 7, 8, 9] + target: 10 + - name: "zero_result_target_two" + in: + cost: [3, 3, 3, 3, 3, 3, 3, 3, 3] + target: 2 + out: '"0"' + - name: "repeated_best_digit" + in: + cost: [6, 6, 6, 6, 6, 6, 2, 6, 6] + target: 14 + - name: "target_fifteen" + in: + cost: [2, 5, 9, 4, 7, 3, 8, 6, 1] + target: 15 + - name: "target_twenty_five" + in: + cost: [3, 8, 2, 9, 4, 7, 5, 6, 1] + target: 25 + - name: "target_fifty" + in: + cost: [10, 9, 8, 7, 6, 5, 4, 3, 2] + target: 50 + - name: "target_one_hundred" + in: + cost: [1, 10, 10, 10, 10, 10, 10, 10, 10] + target: 100 + - name: "target_five_hundred" + in: + cost: [11, 12, 13, 14, 15, 16, 17, 18, 19] + target: 500 + - name: "target_maximum_uniform" + in: + cost: [25, 25, 25, 25, 25, 25, 25, 25, 25] + target: 5000 + - name: "target_maximum_cheap_nine" + in: + cost: [5000, 4999, 4998, 4997, 4996, 4995, 4994, 4993, 1] + target: 5000 + - name: "target_maximum_mixed" + in: + cost: [4992, 4991, 4990, 4989, 4988, 4987, 4986, 4985, 4984] + target: 5000 + - name: "generated_low_costs" + seed: 101 + in: + cost: + gen: "array" + len: 9 + of: + gen: "int" + min: 1 + max: 9 + target: + gen: "int" + min: 1 + max: 100 + - name: "generated_medium_costs" + seed: 202 + in: + cost: + gen: "array" + len: 9 + of: + gen: "int" + min: 10 + max: 100 + target: + gen: "int" + min: 100 + max: 1000 + - name: "generated_large_target" + seed: 303 + in: + cost: + gen: "array" + len: 9 + of: + gen: "int" + min: 1 + max: 5000 + target: 5000 + - name: "generated_dense_options" + seed: 404 + in: + cost: + gen: "array" + len: 9 + of: + gen: "int" + min: 1 + max: 20 + target: + gen: "int" + min: 200 + max: 5000 + - name: "generated_high_costs" + seed: 505 + in: + cost: + gen: "array" + len: 9 + of: + gen: "int" + min: 4000 + max: 5000 + target: + gen: "int" + min: 1 + max: 5000 + - name: "generated_small_impossible_possible" + seed: 606 + in: + cost: + gen: "array" + len: 9 + of: + gen: "int" + min: 2 + max: 6 + target: + gen: "int" + min: 1 + max: 15 + - name: "minimum_target_impossible" + in: + cost: [2, 2, 2, 2, 2, 2, 2, 2, 2] + target: 1 + - name: "max_cost_single_digit" + in: + cost: [5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000] + target: 5000 + - name: "max_cost_impossible" + in: + cost: [5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000] + target: 4999 + - name: "nine_cost_three_longer" + in: + cost: [2, 2, 2, 2, 2, 2, 2, 2, 3] + target: 9 + - name: "mixed_remainder_longest" + in: + cost: [2, 3, 4, 5, 6, 7, 8, 9, 10] + target: 11 diff --git a/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.cpp b/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.cpp new file mode 100644 index 00000000..3530ef05 --- /dev/null +++ b/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + string largestNumber(vector& cost, int target) { + int N = cost.size(); + vector> memo(N + 1, vector(target + 1, -1)); + + function helper = [&](int i, int c) -> int { + if (c == 0) return 0; + if (i == N || c < 0) return INT_MIN; + if (memo[i][c] != -1) return memo[i][c]; + int take = helper(i, c - cost[i]); + if (take != INT_MIN) take += 1; + int notTake = helper(i + 1, c); + memo[i][c] = max(take, notTake); + return memo[i][c]; + }; + + int e = helper(0, target); + if (e == INT_MIN) return "0"; + + string s = ""; + int t = target; + for (int k = 0; k < e; k++) { + for (int j = 9; j >= 1; j--) { + if (cost[j-1] <= t && helper(0, t - cost[j-1]) == e - k - 1) { + t -= cost[j-1]; + s += to_string(j); + break; + } + } + } + return s; + } +}; diff --git a/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.cs b/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.cs new file mode 100644 index 00000000..0f08d326 --- /dev/null +++ b/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.cs @@ -0,0 +1,40 @@ +public class Solution { + public string LargestNumber(int[] cost, int target) { + int N = cost.Length; + int[][] memo = new int[N + 1][]; + for (int i = 0; i <= N; i++) { + memo[i] = new int[target + 1]; + for (int j = 0; j <= target; j++) { + memo[i][j] = -1; + } + } + + Func helper = null; + helper = (i, c) => { + if (c == 0) return 0; + if (i == N || c < 0) return int.MinValue; + if (memo[i][c] != -1) return memo[i][c]; + int take = helper(i, c - cost[i]); + if (take != int.MinValue) take += 1; + int notTake = helper(i + 1, c); + memo[i][c] = Math.Max(take, notTake); + return memo[i][c]; + }; + + int e = helper(0, target); + if (e == int.MinValue) return "0"; + + string s = ""; + int t = target; + for (int k = 0; k < e; k++) { + for (int j = 9; j >= 1; j--) { + if (cost[j-1] <= t && helper(0, t - cost[j-1]) == e - k - 1) { + t -= cost[j-1]; + s += j.ToString(); + break; + } + } + } + return s; + } +} diff --git a/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.dart b/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.dart new file mode 100644 index 00000000..660b5951 --- /dev/null +++ b/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.dart @@ -0,0 +1,33 @@ +class Solution { + String largestNumber(List cost, int target) { + int N = cost.length; + List> memo = List.generate(N + 1, (_) => List.filled(target + 1, -1)); + + int helper(int i, int c) { + if (c == 0) return 0; + if (i == N || c < 0) return -9223372036854775808; + if (memo[i][c] != -1) return memo[i][c]; + int take = helper(i, c - cost[i]); + if (take != -9223372036854775808) take += 1; + int notTake = helper(i + 1, c); + memo[i][c] = take > notTake ? take : notTake; + return memo[i][c]; + } + + int e = helper(0, target); + if (e == -9223372036854775808) return "0"; + + StringBuffer s = StringBuffer(); + int t = target; + for (int k = 0; k < e; k++) { + for (int j = 9; j >= 1; j--) { + if (cost[j-1] <= t && helper(0, t - cost[j-1]) == e - k - 1) { + t -= cost[j-1]; + s.write(j.toString()); + break; + } + } + } + return s.toString(); + } +} diff --git a/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.go b/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.go new file mode 100644 index 00000000..1fb629e8 --- /dev/null +++ b/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.go @@ -0,0 +1,52 @@ +func largestNumber(cost []int, target int) string { + N := len(cost) + memo := make([][]int, N+1) + for i := range memo { + memo[i] = make([]int, target+1) + for j := range memo[i] { + memo[i][j] = -1 + } + } + + var helper func(int, int) int + helper = func(i, c int) int { + if c == 0 { + return 0 + } + if i == N || c < 0 { + return -2147483648 + } + if memo[i][c] != -1 { + return memo[i][c] + } + take := helper(i, c-cost[i]) + if take != -2147483648 { + take += 1 + } + notTake := helper(i+1, c) + if take > notTake { + memo[i][c] = take + } else { + memo[i][c] = notTake + } + return memo[i][c] + } + + e := helper(0, target) + if e == -2147483648 { + return "0" + } + + var s []byte + t := target + for k := 0; k < e; k++ { + for j := 9; j >= 1; j-- { + if cost[j-1] <= t && helper(0, t-cost[j-1]) == e-k-1 { + t -= cost[j-1] + s = append(s, byte('0'+j)) + break + } + } + } + return string(s) +} diff --git a/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.java b/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.java new file mode 100644 index 00000000..4ee8a973 --- /dev/null +++ b/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.java @@ -0,0 +1,35 @@ +class Solution { + public String largestNumber(int[] cost, int target) { + int N = cost.length; + int[][] memo = new int[N + 1][target + 1]; + for (int i = 0; i <= N; i++) { + for (int j = 0; j <= target; j++) { + memo[i][j] = -1; + } + } + int e = helper(0, target, cost, N, memo); + if (e == Integer.MIN_VALUE) return "0"; + StringBuilder s = new StringBuilder(); + for (int k = 0; k < e; k++) { + for (int j = 9; j >= 1; j--) { + if (cost[j-1] <= target && helper(0, target - cost[j-1], cost, N, memo) == e - k - 1) { + target -= cost[j-1]; + s.append(j); + break; + } + } + } + return s.toString(); + } + + private int helper(int i, int c, int[] cost, int N, int[][] memo) { + if (c == 0) return 0; + if (i == N || c < 0) return Integer.MIN_VALUE; + if (memo[i][c] != -1) return memo[i][c]; + int take = helper(i, c - cost[i], cost, N, memo); + int notTake = helper(i + 1, c, cost, N, memo); + if (take != Integer.MIN_VALUE) take += 1; + memo[i][c] = Math.max(take, notTake); + return memo[i][c]; + } +} diff --git a/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.kt b/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.kt new file mode 100644 index 00000000..09285fcc --- /dev/null +++ b/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.kt @@ -0,0 +1,33 @@ +class Solution { + fun largestNumber(cost: IntArray, target: Int): String { + val N = cost.size + val memo = Array(N + 1) { IntArray(target + 1) { -1 } } + + fun helper(i: Int, c: Int): Int { + if (c == 0) return 0 + if (i == N || c < 0) return Int.MIN_VALUE + if (memo[i][c] != -1) return memo[i][c] + val take = helper(i, c - cost[i]) + val notTake = helper(i + 1, c) + val takeVal = if (take != Int.MIN_VALUE) take + 1 else Int.MIN_VALUE + memo[i][c] = maxOf(takeVal, notTake) + return memo[i][c] + } + + val e = helper(0, target) + if (e == Int.MIN_VALUE) return "0" + + var t = target + val sb = StringBuilder() + for (k in 0 until e) { + for (j in 9 downTo 1) { + if (cost[j-1] <= t && helper(0, t - cost[j-1]) == e - k - 1) { + t -= cost[j-1] + sb.append(j) + break + } + } + } + return sb.toString() + } +} diff --git a/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.py b/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.py new file mode 100644 index 00000000..f43731f7 --- /dev/null +++ b/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.py @@ -0,0 +1,29 @@ +from functools import cache +from typing import List + + +class Solution: + def largestNumber(self, cost: List[int], target: int) -> str: + N = len(cost) + s = "" + + @cache + def helper(i, c): + if c == 0: + return 0 + if i == N or c < 0: + return -float("inf") + return max(helper(i + 1, c), 1 + helper(i, c - cost[i])) + + e = helper(0, target) + if e == -float("inf"): + return "0" + for i in range(e): + for j in reversed(range(1, 10)): + if ( + cost[j - 1] <= target + and helper(0, target - cost[j - 1]) == e - i - 1 + ): + target -= cost[j - 1] + s += str(j) + return s diff --git a/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.py2 b/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.py2 new file mode 100644 index 00000000..8acd85a6 --- /dev/null +++ b/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.py2 @@ -0,0 +1,31 @@ +class Solution(object): + def largestNumber(self, cost, target): + """ + :type cost: List[int] + :type target: int + :rtype: str + """ + N = len(cost) + memo = {} + def helper(i, c): + if c == 0: + return 0 + if i == N or c < 0: + return -float('inf') + if (i, c) in memo: + return memo[(i, c)] + res = max(helper(i+1, c), 1 + helper(i, c - cost[i])) + memo[(i, c)] = res + return res + + e = helper(0, target) + if e == -float('inf'): + return "0" + s = "" + for _ in range(e): + for j in range(9, 0, -1): + if cost[j-1] <= target and helper(0, target - cost[j-1]) == e - len(s) - 1: + target -= cost[j-1] + s += str(j) + break + return s diff --git a/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.rb b/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.rb new file mode 100644 index 00000000..3f0c4448 --- /dev/null +++ b/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.rb @@ -0,0 +1,31 @@ +# @param {Integer[]} cost +# @param {Integer} target +# @return {String} +def largest_number(cost, target) + n = cost.length + memo = {} + helper = lambda do |i, c| + return 0 if c == 0 + return -Float::INFINITY if i == n || c < 0 + key = [i, c] + return memo[key] if memo.key?(key) + res = [helper.call(i + 1, c), 1 + helper.call(i, c - cost[i])].max + memo[key] = res + res + end + + e = helper.call(0, target) + return "0" if e == -Float::INFINITY + + s = "" + while s.length < e + (9).downto(1) do |j| + if cost[j-1] <= target && helper.call(0, target - cost[j-1]) == e - s.length - 1 + target -= cost[j-1] + s += j.to_s + break + end + end + end + s +end diff --git a/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.rs b/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.rs new file mode 100644 index 00000000..da8723ec --- /dev/null +++ b/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.rs @@ -0,0 +1,48 @@ +impl Solution { + pub fn largest_number(cost: Vec, target: i32) -> String { + let n = cost.len(); + let target = target as usize; + let mut memo = vec![vec![-1; target + 1]; n + 1]; + + fn helper(i: usize, c: usize, cost: &Vec, n: usize, memo: &mut Vec>) -> i32 { + if c == 0 { + return 0; + } + if i == n || (c as i32) < 0 { + return i32::MIN; + } + if memo[i][c] != -1 { + return memo[i][c]; + } + let cost_i = cost[i] as usize; + let take = if c >= cost_i { + let res = helper(i, c - cost_i, cost, n, memo); + if res != i32::MIN { res + 1 } else { i32::MIN } + } else { + i32::MIN + }; + let not_take = helper(i + 1, c, cost, n, memo); + memo[i][c] = take.max(not_take); + memo[i][c] + } + + let e = helper(0, target, &cost, n, &mut memo); + if e == i32::MIN { + return "0".to_string(); + } + + let mut t = target; + let mut s = String::new(); + for k in 0..e as usize { + for j in (1..=9).rev() { + let c = cost[j - 1] as usize; + if c <= t && helper(0, t - c, &cost, n, &mut memo) == e - k as i32 - 1 { + t -= c; + s.push_str(&j.to_string()); + break; + } + } + } + s + } +} diff --git a/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.swift b/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.swift new file mode 100644 index 00000000..c8318f63 --- /dev/null +++ b/tests/1001-1500/1449. form-largest-integer-with-digits-that-add-up-to-target/sol.swift @@ -0,0 +1,33 @@ +class Solution { + func largestNumber(_ cost: [Int], _ target: Int) -> String { + let N = cost.count + var memo = Array(repeating: Array(repeating: -1, count: target + 1), count: N + 1) + + func helper(_ i: Int, _ c: Int) -> Int { + if c == 0 { return 0 } + if i == N || c < 0 { return Int.min } + if memo[i][c] != -1 { return memo[i][c] } + var take = helper(i, c - cost[i]) + if take != Int.min { take += 1 } + let notTake = helper(i + 1, c) + memo[i][c] = max(take, notTake) + return memo[i][c] + } + + let e = helper(0, target) + if e == Int.min { return "0" } + + var t = target + var s = "" + for k in 0.. + Array(target + 1).fill(-1), + ); + + const helper = (i: number, c: number): number => { + if (c === 0) return 0; + if (i === N || c < 0) return -Infinity; + if (memo[i][c] !== -1) return memo[i][c]; + let take = helper(i, c - cost[i]); + if (take !== -Infinity) take += 1; + const notTake = helper(i + 1, c); + memo[i][c] = Math.max(take, notTake); + return memo[i][c]; + }; + + const e = helper(0, target); + if (e === -Infinity) return "0"; + + let t = target; + let s = ""; + for (let k = 0; k < e; k++) { + for (let j = 9; j >= 1; j--) { + if (cost[j - 1] <= t && helper(0, t - cost[j - 1]) === e - k - 1) { + t -= cost[j - 1]; + s += j.toString(); + break; + } + } + } + return s; +} diff --git a/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/manifest.yaml b/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/manifest.yaml new file mode 100644 index 00000000..06da51b8 --- /dev/null +++ b/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/manifest.yaml @@ -0,0 +1,576 @@ +entry: + id: 1450 + title: number-of-students-doing-homework-at-a-given-time + params: + startTime: + type: array + items: + type: int + endTime: + type: array + items: + type: int + queryTime: + type: int + call: + cpp: "Solution().busyStudent({startTime}, {endTime}, {queryTime})" + rust: "Solution::busy_student({startTime}, {endTime}, {queryTime})" + python3: "Solution().busyStudent({startTime}, {endTime}, {queryTime})" + python2: "Solution().busyStudent({startTime}, {endTime}, {queryTime})" + ruby: "busy_student({startTime}, {endTime}, {queryTime})" + java: "new Solution().busyStudent({startTime}, {endTime}, {queryTime})" + csharp: "new Solution().BusyStudent({startTime}, {endTime}, {queryTime})" + kotlin: "Solution().busyStudent({startTime}, {endTime}, {queryTime})" + go: "busyStudent({startTime}, {endTime}, {queryTime})" + dart: "Solution().busyStudent({startTime}, {endTime}, {queryTime})" + swift: "Solution().busyStudent({startTime}, {endTime}, {queryTime})" + typescript: "busyStudent({startTime}, {endTime}, {queryTime})" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().busyStudent(startTime, endTime, queryTime, {result})" + checker: | + class Checker: + def busyStudent(self, startTime, endTime, queryTime, result): + expected = sum(start <= queryTime <= end for start, end in zip(startTime, endTime)) + return type(result) is int and result == expected +seed: 1450 +tests: + - name: example_one + in: + startTime: [1, 2, 3] + endTime: [3, 2, 7] + queryTime: 4 + out: 1 + - name: example_two + in: + startTime: [4] + endTime: [4] + queryTime: 4 + out: 1 + - name: single_inside + in: + startTime: [2] + endTime: [8] + queryTime: 5 + out: 1 + - name: single_before + in: + startTime: [3] + endTime: [5] + queryTime: 2 + out: 0 + - name: single_after + in: + startTime: [3] + endTime: [5] + queryTime: 6 + out: 0 + - name: start_boundary + in: + startTime: [2] + endTime: [5] + queryTime: 2 + out: 1 + - name: end_boundary + in: + startTime: [2] + endTime: [5] + queryTime: 5 + out: 1 + - name: one_point_interval_miss + in: + startTime: [7] + endTime: [7] + queryTime: 6 + out: 0 + - name: all_overlap + in: + startTime: [1, 1, 1, 1] + endTime: [10, 10, 10, 10] + queryTime: 5 + out: 4 + - name: no_overlap + in: + startTime: [1, 5, 9] + endTime: [2, 6, 10] + queryTime: 3 + out: 0 + - name: touching_intervals + in: + startTime: [1, 3, 5] + endTime: [2, 4, 6] + queryTime: 3 + out: 1 + - name: nested_intervals + in: + startTime: [1, 2, 3, 4] + endTime: [10, 9, 8, 7] + queryTime: 5 + out: 4 + - name: disjoint_query_middle + in: + startTime: [1, 10, 20] + endTime: [3, 12, 22] + queryTime: 11 + out: 1 + - name: earliest_query + in: + startTime: [1, 4, 7] + endTime: [2, 6, 9] + queryTime: 1 + out: 1 + - name: latest_query + in: + startTime: [990, 995, 1000] + endTime: [1000, 1000, 1000] + queryTime: 1000 + out: 3 + - name: repeated_intervals + in: + startTime: [2, 2, 2, 5, 5] + endTime: [6, 6, 6, 8, 8] + queryTime: 5 + out: 5 + - name: one_point_intervals + in: + startTime: [4, 5, 6, 7] + endTime: [4, 5, 6, 7] + queryTime: 5 + out: 1 + - name: unsorted_intervals + in: + startTime: [10, 1, 7, 3] + endTime: [12, 5, 8, 9] + queryTime: 7 + out: 2 + - name: all_end_at_query + in: + startTime: [1, 2, 3, 4] + endTime: [4, 4, 4, 4] + queryTime: 4 + out: 4 + - name: mixed_activity + in: + startTime: [1, 2, 4, 7] + endTime: [5, 3, 8, 9] + queryTime: 4 + out: 2 + - name: staggered_none + in: + startTime: [1, 4, 7, 10] + endTime: [2, 5, 8, 11] + queryTime: 6 + out: 0 + - name: five_students + in: + startTime: [1, 2, 3, 4, 5] + endTime: [5, 5, 5, 5, 5] + queryTime: 4 + out: 4 + - name: alternating_ranges + in: + startTime: [1, 5, 1, 5] + endTime: [3, 7, 7, 9] + queryTime: 6 + out: 3 + - name: broad_and_point + in: + startTime: [1, 4, 6] + endTime: [10, 4, 6] + queryTime: 4 + out: 2 + - name: query_at_first_start + in: + startTime: [100, 200, 300] + endTime: [150, 250, 350] + queryTime: 100 + out: 1 + - name: query_at_last_end + in: + startTime: [100, 200, 300] + endTime: [150, 250, 350] + queryTime: 350 + out: 1 + - name: all_times_minimum + in: + startTime: [1, 1, 1] + endTime: [1, 1, 1] + queryTime: 1 + out: 3 + - name: all_times_maximum + in: + startTime: [1000, 1000] + endTime: [1000, 1000] + queryTime: 1000 + out: 2 + - name: query_between_ranges + in: + startTime: [10, 20, 30, 40] + endTime: [19, 29, 39, 49] + queryTime: 25 + out: 1 + - name: varied_overlap + in: + startTime: [2, 8, 1, 12, 5] + endTime: [4, 10, 6, 15, 9] + queryTime: 8 + out: 2 + - name: broad_overlap + in: + startTime: [1, 100, 200] + endTime: [1000, 900, 800] + queryTime: 500 + out: 3 + - name: only_first_active + in: + startTime: [1, 20, 30] + endTime: [10, 25, 40] + queryTime: 5 + out: 1 + - name: only_last_active + in: + startTime: [1, 20, 30] + endTime: [10, 25, 40] + queryTime: 35 + out: 1 + - name: all_contain_query + in: + startTime: [1, 10, 20, 30] + endTime: [100, 90, 80, 70] + queryTime: 50 + out: 4 + - name: max_length_all_active + in: + startTime: + [ + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + ] + endTime: + [ + 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, + 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, + ] + queryTime: 500 + out: 100 + - name: generated_max_length_all_active + seed: 145001 + in: + startTime: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 499 + distinct: false + sorted: false + elemType: "int" + endTime: + gen: "array" + len: 100 + of: + gen: "int" + min: 500 + max: 1000 + distinct: false + sorted: false + elemType: "int" + queryTime: 500 + - name: generated_max_length_none_at_start + seed: 145002 + in: + startTime: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 499 + distinct: false + sorted: false + elemType: "int" + endTime: + gen: "array" + len: 100 + of: + gen: "int" + min: 500 + max: 1000 + distinct: false + sorted: false + elemType: "int" + queryTime: 1 + - name: generated_max_length_all_at_end + seed: 145003 + in: + startTime: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 500 + distinct: false + sorted: false + elemType: "int" + endTime: + gen: "array" + len: 100 + of: + gen: "int" + min: 500 + max: 1000 + distinct: false + sorted: false + elemType: "int" + queryTime: 1000 + - name: generated_max_length_midpoint + seed: 145004 + in: + startTime: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + sorted: false + elemType: "int" + endTime: + gen: "array" + len: 100 + of: + gen: "int" + min: 100 + max: 1000 + distinct: false + sorted: false + elemType: "int" + queryTime: 50 + - name: generated_max_length_late_intervals + seed: 145005 + in: + startTime: + gen: "array" + len: 100 + of: + gen: "int" + min: 500 + max: 500 + distinct: false + sorted: false + elemType: "int" + endTime: + gen: "array" + len: 100 + of: + gen: "int" + min: 500 + max: 1000 + distinct: false + sorted: false + elemType: "int" + queryTime: 750 diff --git a/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.cpp b/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.cpp new file mode 100644 index 00000000..d4c01fa3 --- /dev/null +++ b/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int busyStudent(vector& startTime, vector& endTime, int queryTime) { + int count = 0; + for (int i = 0; i < startTime.size(); i++) { + if (startTime[i] <= queryTime && queryTime <= endTime[i]) { + count++; + } + } + return count; + } +}; diff --git a/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.cs b/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.cs new file mode 100644 index 00000000..23367c39 --- /dev/null +++ b/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.cs @@ -0,0 +1,11 @@ +public class Solution { + public int BusyStudent(int[] startTime, int[] endTime, int queryTime) { + int count = 0; + for (int i = 0; i < startTime.Length; i++) { + if (startTime[i] <= queryTime && queryTime <= endTime[i]) { + count++; + } + } + return count; + } +} diff --git a/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.dart b/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.dart new file mode 100644 index 00000000..28902c09 --- /dev/null +++ b/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.dart @@ -0,0 +1,11 @@ +class Solution { + int busyStudent(List startTime, List endTime, int queryTime) { + int count = 0; + for (int i = 0; i < startTime.length; i++) { + if (startTime[i] <= queryTime && queryTime <= endTime[i]) { + count++; + } + } + return count; + } +} diff --git a/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.go b/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.go new file mode 100644 index 00000000..10c97e8c --- /dev/null +++ b/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.go @@ -0,0 +1,9 @@ +func busyStudent(startTime []int, endTime []int, queryTime int) int { + count := 0 + for i := range startTime { + if startTime[i] <= queryTime && queryTime <= endTime[i] { + count++ + } + } + return count +} diff --git a/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.java b/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.java new file mode 100644 index 00000000..c2d6e909 --- /dev/null +++ b/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.java @@ -0,0 +1,11 @@ +class Solution { + public int busyStudent(int[] startTime, int[] endTime, int queryTime) { + int count = 0; + for (int i = 0; i < startTime.length; i++) { + if (startTime[i] <= queryTime && queryTime <= endTime[i]) { + count++; + } + } + return count; + } +} diff --git a/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.kt b/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.kt new file mode 100644 index 00000000..9b16fb4a --- /dev/null +++ b/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.kt @@ -0,0 +1,5 @@ +class Solution { + fun busyStudent(startTime: IntArray, endTime: IntArray, queryTime: Int): Int { + return startTime.indices.count { startTime[it] <= queryTime && queryTime <= endTime[it] } + } +} diff --git a/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.py b/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.py new file mode 100644 index 00000000..a13aef29 --- /dev/null +++ b/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.py @@ -0,0 +1,13 @@ +from typing import List + + +class Solution: + def busyStudent( + self, startTime: List[int], endTime: List[int], queryTime: int + ) -> int: + return sum( + [ + ((queryTime >= s) and (queryTime <= e)) + for s, e in zip(startTime, endTime) + ] + ) diff --git a/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.py2 b/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.py2 new file mode 100644 index 00000000..d94e57a1 --- /dev/null +++ b/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.py2 @@ -0,0 +1,9 @@ +class Solution(object): + def busyStudent(self, startTime, endTime, queryTime): + """ + :type startTime: List[int] + :type endTime: List[int] + :type queryTime: int + :rtype: int + """ + return sum(1 for s, e in zip(startTime, endTime) if s <= queryTime <= e) diff --git a/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.rb b/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.rb new file mode 100644 index 00000000..381da068 --- /dev/null +++ b/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.rb @@ -0,0 +1,7 @@ +# @param {Integer[]} start_time +# @param {Integer[]} end_time +# @param {Integer} query_time +# @return {Integer} +def busy_student(start_time, end_time, query_time) + start_time.zip(end_time).count { |s, e| s <= query_time && query_time <= e } +end diff --git a/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.rs b/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.rs new file mode 100644 index 00000000..193965bf --- /dev/null +++ b/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.rs @@ -0,0 +1,7 @@ +impl Solution { + pub fn busy_student(start_time: Vec, end_time: Vec, query_time: i32) -> i32 { + start_time.iter().zip(end_time.iter()) + .filter(|&(s, e)| *s <= query_time && query_time <= *e) + .count() as i32 + } +} diff --git a/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.swift b/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.swift new file mode 100644 index 00000000..f066da76 --- /dev/null +++ b/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.swift @@ -0,0 +1,5 @@ +class Solution { + func busyStudent(_ startTime: [Int], _ endTime: [Int], _ queryTime: Int) -> Int { + return zip(startTime, endTime).filter { $0 <= queryTime && queryTime <= $1 }.count + } +} diff --git a/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.ts b/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.ts new file mode 100644 index 00000000..0e45aaa5 --- /dev/null +++ b/tests/1001-1500/1450. number-of-students-doing-homework-at-a-given-time/sol.ts @@ -0,0 +1,9 @@ +function busyStudent( + startTime: number[], + endTime: number[], + queryTime: number, +): number { + return startTime.filter( + (_, i) => startTime[i] <= queryTime && queryTime <= endTime[i], + ).length; +} diff --git a/tests/1001-1500/1451. rearrange-words-in-a-sentence/manifest.yaml b/tests/1001-1500/1451. rearrange-words-in-a-sentence/manifest.yaml new file mode 100644 index 00000000..a40ebea7 --- /dev/null +++ b/tests/1001-1500/1451. rearrange-words-in-a-sentence/manifest.yaml @@ -0,0 +1,197 @@ +entry: + id: 1451 + title: "rearrange-words-in-a-sentence" + params: + text: + type: string + call: + cpp: "Solution().arrangeWords({text})" + rust: "Solution::arrange_words({text})" + python3: "Solution().arrangeWords({text})" + python2: "Solution().arrangeWords({text})" + ruby: "arrange_words({text})" + java: "new Solution().arrangeWords({text})" + csharp: "new Solution().ArrangeWords({text})" + kotlin: "Solution().arrangeWords({text})" + go: "arrangeWords({text})" + dart: "Solution().arrangeWords({text})" + swift: "Solution().arrangeWords({text})" + typescript: "arrangeWords({text})" +judge: + type: exact +limits: + time_ms: 400 + memory_mb: 300 +oracle: + python3: + call: "Checker().arrangeWords(text, {result})" + checker: | + class Checker: + def arrangeWords(self, text, result): + words = text.split() + expected = sorted((word.lower() for word in words), key=len) + expected = " ".join(expected) + expected = expected[0].upper() + expected[1:] + return result == expected +seed: 1451 +tests: + - name: ex1 + in: + text: "Leetcode is cool" + out: "Is cool leetcode" + - name: ex2 + in: + text: "Keep calm and code on" + out: "On and keep calm code" + - name: ex3 + in: + text: "To be or not to be" + out: "To be or to be not" + - name: single_word + in: + text: "Hello" + out: "Hello" + - name: two_words + in: + text: "Hello a" + out: "A hello" + - name: all_equal + in: + text: "One two six" + out: "One two six" + - name: increasing_lengths + in: + text: "A bb ccc dddd" + out: "A bb ccc dddd" + - name: decreasing_lengths + in: + text: "Dddd ccc bb a" + out: "A bb ccc dddd" + - name: repeated_short_words + in: + text: "I am a coder" + out: "I a am coder" + - name: repeated_same_word + in: + text: "Apple apple apple" + out: "Apple apple apple" + - name: mixed_basic + in: + text: "This is a simple test" + out: "A is this test simple" + - name: short_middle + in: + text: "Programming is fun" + out: "Is fun programming" + - name: tie_at_end + in: + text: "Sort these words by length" + out: "By sort these words length" + - name: equal_length_groups + in: + text: "The quick brown fox jumps" + out: "The fox quick brown jumps" + - name: long_first + in: + text: "Extraordinary is a word" + out: "A is word extraordinary" + - name: already_sorted + in: + text: "A word extraordinary" + out: "A word extraordinary" + - name: four_equal_words + in: + text: "Cat dog pig hen" + out: "Cat dog pig hen" + - name: three_equal_words + in: + text: "Blue gold sand" + out: "Blue gold sand" + - name: stable_mixed + in: + text: "Rearrange words in this sentence" + out: "In this words sentence rearrange" + - name: stable_five_words + in: + text: "Small words become ordered" + out: "Small words become ordered" + - name: stable_sorting + in: + text: "Testing stable sorting order" + out: "Order stable testing sorting" + - name: longest_tie + in: + text: "Length determines final arrangement" + out: "Final length determines arrangement" + - name: common_words + in: + text: "Short and long words" + out: "And long short words" + - name: two_long_words + in: + text: "A very interesting challenge" + out: "A very challenge interesting" + - name: varied_lengths + in: + text: "Practice makes perfect coding" + out: "Makes coding perfect practice" + - name: same_length_reordered + in: + text: "Sort every word carefully" + out: "Sort word every carefully" + - name: two_and_four_lengths + in: + text: "Words of various lengths here" + out: "Of here words various lengths" + - name: three_seven_eight + in: + text: "Another sentence for testing" + out: "For another testing sentence" + - name: three_equal_fives + in: + text: "Good code needs clear tests" + out: "Good code needs clear tests" + - name: three_equal_threes + in: + text: "Arrange all the words now" + out: "All the now words arrange" + - name: ordered_by_groups + in: + text: "One two three four five" + out: "One two four five three" + - name: all_five_letters + in: + text: "Alpha beta gamma delta" + out: "Beta alpha gamma delta" + - name: stable_five_group + in: + text: "Keep words in stable order" + out: "In keep words order stable" + - name: final_example + in: + text: "Final example sentence here" + out: "Here final example sentence" + - name: source_order_preserved + in: + text: "Carefully arrange these words" + out: "These words arrange carefully" + - name: one_two_four + in: + text: "Zebra a aa abcd" + out: "A aa abcd zebra" + - name: equal_short_group + in: + text: "Bright tiny calm remarkable" + out: "Tiny calm bright remarkable" + - name: many_length_groups + in: + text: "Code makes tests reliable and fast" + out: "And code fast makes tests reliable" + - name: six_increasing_lengths + in: + text: "A bb ccc dddd eeeee ffffff" + out: "A bb ccc dddd eeeee ffffff" + - name: long_sentence_groups + in: + text: "Development is about making reliable software for people" + out: "Is for about making people reliable software development" diff --git a/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.cpp b/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.cpp new file mode 100644 index 00000000..5773e7b5 --- /dev/null +++ b/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + string arrangeWords(string text) { + vector s; + istringstream iss(text); + string word; + while (iss >> word) { + s.push_back(word); + } + stable_sort(s.begin(), s.end(), [](const string& a, const string& b) { + return a.length() < b.length(); + }); + for (auto& w : s) { + transform(w.begin(), w.end(), w.begin(), ::tolower); + } + if (!s.empty()) { + s[0][0] = toupper(s[0][0]); + } + ostringstream oss; + for (size_t i = 0; i < s.size(); ++i) { + if (i > 0) oss << " "; + oss << s[i]; + } + return oss.str(); + } +}; diff --git a/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.cs b/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.cs new file mode 100644 index 00000000..79fb5109 --- /dev/null +++ b/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.cs @@ -0,0 +1,13 @@ +public class Solution { + public string ArrangeWords(string text) { + string[] s = text.Split(" "); + Array.Sort(s, (a, b) => a.Length.CompareTo(b.Length)); + for (int i = 0; i < s.Length; i++) { + s[i] = s[i].ToLower(); + } + if (s.Length > 0) { + s[0] = char.ToUpper(s[0][0]) + s[0].Substring(1); + } + return string.Join(" ", s); + } +} diff --git a/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.dart b/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.dart new file mode 100644 index 00000000..3ea8a3df --- /dev/null +++ b/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.dart @@ -0,0 +1,9 @@ +class Solution { + String arrangeWords(String text) { + List s = text.split(" "); + s.sort((a, b) => a.length.compareTo(b.length)); + s = s.map((i) => i.toLowerCase()).toList(); + s[0] = s[0][0].toUpperCase() + s[0].substring(1); + return s.join(" "); + } +} diff --git a/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.go b/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.go new file mode 100644 index 00000000..69b122c5 --- /dev/null +++ b/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.go @@ -0,0 +1,13 @@ +func arrangeWords(text string) string { + s := strings.Split(text, " ") + sort.SliceStable(s, func(i, j int) bool { + return len(s[i]) < len(s[j]) + }) + for i := range s { + s[i] = strings.ToLower(s[i]) + } + if len(s) > 0 { + s[0] = strings.ToUpper(s[0][:1]) + s[0][1:] + } + return strings.Join(s, " ") +} diff --git a/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.java b/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.java new file mode 100644 index 00000000..8db1227f --- /dev/null +++ b/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.java @@ -0,0 +1,11 @@ +class Solution { + public String arrangeWords(String text) { + String[] s = text.split(" "); + Arrays.sort(s, (a, b) -> Integer.compare(a.length(), b.length())); + for (int i = 0; i < s.length; i++) { + s[i] = s[i].toLowerCase(); + } + s[0] = s[0].substring(0, 1).toUpperCase() + s[0].substring(1); + return String.join(" ", s); + } +} diff --git a/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.kt b/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.kt new file mode 100644 index 00000000..db20b8e9 --- /dev/null +++ b/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.kt @@ -0,0 +1,11 @@ +class Solution { + fun arrangeWords(text: String): String { + val s = text.split(" ").toMutableList() + s.sortBy { it.length } + for (i in s.indices) { + s[i] = s[i].lowercase() + } + s[0] = s[0][0].uppercase() + s[0].substring(1) + return s.joinToString(" ") + } +} diff --git a/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.py b/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.py new file mode 100644 index 00000000..dcf125ad --- /dev/null +++ b/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.py @@ -0,0 +1,7 @@ +class Solution: + def arrangeWords(self, text: str) -> str: + s = text.split() + s = sorted(s, key=lambda x: len(x)) + s = [i.lower() for i in s] + s[0] = s[0][0].upper() + s[0][1:] + return " ".join(s) diff --git a/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.py2 b/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.py2 new file mode 100644 index 00000000..9efbd963 --- /dev/null +++ b/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.py2 @@ -0,0 +1,11 @@ +class Solution(object): + def arrangeWords(self, text): + """ + :type text: str + :rtype: str + """ + s = text.split() + s = sorted(s, key=lambda x: len(x)) + s = [i.lower() for i in s] + s[0] = s[0][0].upper() + s[0][1:] + return " ".join(s) diff --git a/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.rb b/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.rb new file mode 100644 index 00000000..719a5f30 --- /dev/null +++ b/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.rb @@ -0,0 +1,9 @@ +# @param {String} text +# @return {String} +def arrange_words(text) + s = text.split + s = s.sort_by { |x| x.length } + s = s.map { |i| i.downcase } + s[0] = s[0][0].upcase + s[0][1..] + s.join(" ") +end diff --git a/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.rs b/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.rs new file mode 100644 index 00000000..c2966724 --- /dev/null +++ b/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.rs @@ -0,0 +1,11 @@ +impl Solution { + pub fn arrange_words(text: String) -> String { + let mut s: Vec = text.split_whitespace().map(|w| w.to_string()).collect(); + s.sort_by_key(|w| w.len()); + s = s.iter().map(|w| w.to_lowercase()).collect(); + if !s.is_empty() { + s[0] = s[0][..1].to_uppercase() + &s[0][1..]; + } + s.join(" ") + } +} diff --git a/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.swift b/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.swift new file mode 100644 index 00000000..342adbf5 --- /dev/null +++ b/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.swift @@ -0,0 +1,11 @@ +class Solution { + func arrangeWords(_ text: String) -> String { + var s = text.split(separator: " ").map { String($0) } + s.sort { $0.count < $1.count } + s = s.map { $0.lowercased() } + if !s.isEmpty { + s[0] = s[0].prefix(1).uppercased() + s[0].dropFirst() + } + return s.joined(separator: " ") + } +} diff --git a/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.ts b/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.ts new file mode 100644 index 00000000..06684a8b --- /dev/null +++ b/tests/1001-1500/1451. rearrange-words-in-a-sentence/sol.ts @@ -0,0 +1,7 @@ +function arrangeWords(text: string): string { + let s = text.split(" "); + s.sort((a, b) => a.length - b.length); + s = s.map((i) => i.toLowerCase()); + s[0] = s[0][0].toUpperCase() + s[0].slice(1); + return s.join(" "); +} diff --git a/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/manifest.yaml b/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/manifest.yaml new file mode 100644 index 00000000..9ae9920b --- /dev/null +++ b/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/manifest.yaml @@ -0,0 +1,501 @@ +entry: + id: 1452 + title: people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list + params: + favoriteCompanies: + type: array + items: + type: array + items: + type: string + call: + cpp: "Solution().peopleIndexes({favoriteCompanies})" + rust: "Solution::people_indexes({favoriteCompanies})" + python3: "Solution().peopleIndexes({favoriteCompanies})" + python2: "Solution().peopleIndexes({favoriteCompanies})" + ruby: "people_indexes({favoriteCompanies})" + java: "new Solution().peopleIndexes({favoriteCompanies})" + csharp: "new Solution().PeopleIndexes({favoriteCompanies})" + kotlin: "Solution().peopleIndexes({favoriteCompanies})" + go: "peopleIndexes({favoriteCompanies})" + dart: "Solution().peopleIndexes({favoriteCompanies})" + swift: "Solution().peopleIndexes({favoriteCompanies})" + typescript: "peopleIndexes({favoriteCompanies})" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().peopleIndexes(favoriteCompanies, {result})" + checker: | + class Checker: + def peopleIndexes(self, companies, result): + if not isinstance(result, list): + return False + sets = [set(x) for x in companies] + expected = [i for i, current in enumerate(sets) + if not any(i != j and current.issubset(other) + for j, other in enumerate(sets))] + return result == expected +seed: 1452 +tests: + - name: example-one + in: + favoriteCompanies: + elemType: "string" + value: + - ["leetcode", "google", "facebook"] + - ["google", "microsoft"] + - ["google", "facebook"] + - ["google"] + - ["amazon"] + out: [0, 1, 4] + - name: example-two + in: + favoriteCompanies: + elemType: "string" + value: + - ["leetcode", "google", "facebook"] + - ["leetcode", "amazon"] + - ["facebook", "google"] + out: [0, 1] + - name: example-three + in: + favoriteCompanies: + elemType: "string" + value: + - ["leetcode"] + - ["google"] + - ["facebook"] + - ["amazon"] + out: [0, 1, 2, 3] + - name: single-list + in: + favoriteCompanies: + elemType: "string" + value: + - ["solo"] + out: [0] + - name: two-disjoint + in: + favoriteCompanies: + elemType: "string" + value: + - ["alpha"] + - ["beta"] + out: [0, 1] + - name: first-contained + in: + favoriteCompanies: + elemType: "string" + value: + - ["a"] + - ["a", "b"] + out: [1] + - name: second-contained + in: + favoriteCompanies: + elemType: "string" + value: + - ["a", "b"] + - ["a"] + out: [0] + - name: four-level-chain + in: + favoriteCompanies: + elemType: "string" + value: + - ["a"] + - ["a", "b"] + - ["a", "b", "c"] + - ["a", "b", "c", "d"] + out: [3] + - name: reverse-chain + in: + favoriteCompanies: + elemType: "string" + value: + - ["a", "b", "c", "d"] + - ["a", "b", "c"] + - ["a", "b"] + - ["a"] + out: [0] + - name: pairwise-incomparable + in: + favoriteCompanies: + elemType: "string" + value: + - ["a", "b"] + - ["b", "c"] + - ["a", "c"] + out: [0, 1, 2] + - name: two-maxima-and-subset + in: + favoriteCompanies: + elemType: "string" + value: + - ["a", "b"] + - ["a", "c"] + - ["a"] + out: [0, 1] + - name: separate-maxima + in: + favoriteCompanies: + elemType: "string" + value: + - ["a", "b"] + - ["c", "d"] + - ["a", "b", "c"] + out: [1, 2] + - name: all-singletons + in: + favoriteCompanies: + elemType: "string" + value: + - ["a"] + - ["b"] + - ["c"] + - ["d"] + - ["e"] + out: [0, 1, 2, 3, 4] + - name: overlapping-singletons + in: + favoriteCompanies: + elemType: "string" + value: + - ["a", "b"] + - ["b", "c"] + - ["c", "d"] + - ["d", "e"] + out: [0, 1, 2, 3] + - name: broad-set + in: + favoriteCompanies: + elemType: "string" + value: + - ["a", "b", "c", "d", "e"] + - ["a", "b"] + - ["c", "d"] + - ["e"] + - ["x"] + out: [0, 4] + - name: mixed-five + in: + favoriteCompanies: + elemType: "string" + value: + - ["a", "b"] + - ["a", "b", "c"] + - ["b", "c"] + - ["a", "c", "d"] + - ["a", "b", "c", "d"] + out: [4] + - name: two-independent-chains + in: + favoriteCompanies: + elemType: "string" + value: + - ["a"] + - ["a", "b"] + - ["x"] + - ["x", "y"] + out: [1, 3] + - name: early-maximal + in: + favoriteCompanies: + elemType: "string" + value: + - ["a", "b", "c"] + - ["a"] + - ["b"] + - ["c"] + out: [0] + - name: late-maximal + in: + favoriteCompanies: + elemType: "string" + value: + - ["a"] + - ["a", "b"] + - ["x", "y"] + - ["x", "y", "z"] + out: [1, 3] + - name: four-way-crossing + in: + favoriteCompanies: + elemType: "string" + value: + - ["a", "b", "c"] + - ["a", "b", "d"] + - ["a", "c", "d"] + - ["b", "c", "d"] + out: [0, 1, 2, 3] + - name: nested-three + in: + favoriteCompanies: + elemType: "string" + value: + - ["x"] + - ["x", "y"] + - ["x", "y", "z"] + out: [2] + - name: six-level-chain + in: + favoriteCompanies: + elemType: "string" + value: + - ["a"] + - ["a", "b"] + - ["a", "b", "c"] + - ["a", "b", "c", "d"] + - ["a", "b", "c", "d", "e"] + - ["a", "b", "c", "d", "e", "f"] + out: [5] + - name: six-disjoint + in: + favoriteCompanies: + elemType: "string" + value: + - ["a"] + - ["b"] + - ["c"] + - ["d"] + - ["e"] + - ["f"] + out: [0, 1, 2, 3, 4, 5] + - name: named-companies + in: + favoriteCompanies: + elemType: "string" + value: + - ["apple", "google"] + - ["google", "microsoft"] + - ["apple", "amazon"] + - ["amazon", "google", "microsoft"] + out: [0, 2, 3] + - name: maximal-with-singletons + in: + favoriteCompanies: + elemType: "string" + value: + - ["red", "blue", "green"] + - ["red"] + - ["blue"] + - ["yellow"] + - ["green", "yellow"] + out: [0, 4] + - name: disjoint-large-lists + in: + favoriteCompanies: + elemType: "string" + value: + - ["a", "b", "c", "d"] + - ["e", "f", "g", "h"] + - ["a", "b"] + - ["e", "f"] + - ["i", "j", "k"] + out: [0, 1, 4] + - name: interleaved-chain + in: + favoriteCompanies: + elemType: "string" + value: + - ["a", "b"] + - ["x"] + - ["a", "b", "c"] + - ["x", "y"] + - ["a", "b", "c", "d"] + - ["x", "y", "z"] + out: [4, 5] + - name: no-full-containment + in: + favoriteCompanies: + elemType: "string" + value: + - ["aa", "bb"] + - ["aa", "cc"] + - ["bb", "cc"] + - ["aa", "bb", "cc"] + - ["dd", "ee"] + out: [3, 4] + - name: four-maxima-with-subsets + in: + favoriteCompanies: + elemType: "string" + value: + - ["a", "b", "c", "d"] + - ["a", "b"] + - ["c", "d"] + - ["a", "c"] + - ["e", "f"] + - ["e"] + out: [0, 4] + - name: order-does-not-matter + in: + favoriteCompanies: + elemType: "string" + value: + - ["z", "y", "x"] + - ["x", "y"] + - ["y", "z"] + - ["a", "b", "c", "d"] + out: [0, 3] + - name: length-twenty + in: + favoriteCompanies: + elemType: "string" + value: + - [ + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + "q", + "r", + "s", + "t", + ] + - ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"] + - ["k", "l", "m", "n", "o", "p", "q", "r", "s", "t"] + - ["u", "v"] + out: [0, 3] + - name: mixed-seven + in: + favoriteCompanies: + elemType: "string" + value: + - ["a"] + - ["a", "b"] + - ["c"] + - ["c", "d"] + - ["a", "b", "c"] + - ["x"] + - ["x", "y"] + out: [3, 4, 6] + - name: disjoint-maximal-and-chain + in: + favoriteCompanies: + elemType: "string" + value: + - ["p", "q", "r"] + - ["p", "q"] + - ["q", "r"] + - ["s"] + - ["s", "t"] + - ["u", "v"] + out: [0, 4, 5] + - name: overlapping-maxima + in: + favoriteCompanies: + elemType: "string" + value: + - ["a", "b", "c", "d"] + - ["a", "b", "c"] + - ["b", "c", "d"] + - ["a", "d"] + - ["e", "f", "g"] + - ["e", "f"] + out: [0, 4] + - name: long-names + in: + favoriteCompanies: + elemType: "string" + value: + - ["abcdefghijklmnopqrst", "abcdefghijklmnopqrs"] + - ["abcdefghijklmnopqrst"] + - ["zzzzzzzzzzzzzzzzzzzzzz"] + out: [0, 2] + - name: generated-maximal-100x500-a + seed: 145201 + in: + favoriteCompanies: + gen: array + elemType: "string" + len: 60 + distinct: true + of: + gen: array + len: 250 + distinct: true + of: + gen: str + len: 20 + alphabet: "abcdefghijklmnopqrstuvwxyz" + - name: generated-maximal-100x500-b + seed: 145202 + in: + favoriteCompanies: + gen: array + elemType: "string" + len: 40 + distinct: true + of: + gen: array + len: 120 + distinct: true + of: + gen: str + len: 20 + alphabet: "abcdefghijklmnopqrstuvwxyz" + - name: generated-maximal-100x500-c + seed: 145203 + in: + favoriteCompanies: + gen: array + elemType: "string" + len: 30 + distinct: true + of: + gen: array + len: 80 + distinct: true + of: + gen: str + len: 20 + alphabet: "abcdefghijklmnopqrstuvwxyz" + - name: generated-maximal-100x500-d + seed: 145204 + in: + favoriteCompanies: + gen: array + elemType: "string" + len: 20 + distinct: true + of: + gen: array + len: 60 + distinct: true + of: + gen: str + len: 20 + alphabet: "abcdefghijklmnopqrstuvwxyz" + - name: generated-maximal-100x500-e + seed: 145205 + in: + favoriteCompanies: + gen: array + elemType: "string" + len: 12 + distinct: true + of: + gen: array + len: 40 + distinct: true + of: + gen: str + len: 20 + alphabet: "abcdefghijklmnopqrstuvwxyz" diff --git a/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.cpp b/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.cpp new file mode 100644 index 00000000..d17a91e8 --- /dev/null +++ b/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + vector peopleIndexes(vector>& favoriteCompanies) { + vector> sets; + for (const auto& companies : favoriteCompanies) { + sets.push_back(unordered_set(companies.begin(), companies.end())); + } + + vector result; + int n = sets.size(); + + for (int i = 0; i < n; i++) { + bool isSubset = false; + for (int j = 0; j < n; j++) { + if (i != j) { + bool allFound = true; + for (const auto& company : sets[i]) { + if (sets[j].find(company) == sets[j].end()) { + allFound = false; + break; + } + } + if (allFound) { + isSubset = true; + break; + } + } + } + if (!isSubset) { + result.push_back(i); + } + } + + return result; + } +}; diff --git a/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.cs b/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.cs new file mode 100644 index 00000000..e415f445 --- /dev/null +++ b/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.cs @@ -0,0 +1,26 @@ +public class Solution { + public IList PeopleIndexes(IList> favoriteCompanies) { + var sets = new List>(); + foreach (var companies in favoriteCompanies) { + sets.Add(new HashSet(companies)); + } + + var result = new List(); + int n = sets.Count; + + for (int i = 0; i < n; i++) { + bool isSubset = false; + for (int j = 0; j < n; j++) { + if (i != j && sets[i].IsSubsetOf(sets[j])) { + isSubset = true; + break; + } + } + if (!isSubset) { + result.Add(i); + } + } + + return result; + } +} diff --git a/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.dart b/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.dart new file mode 100644 index 00000000..bcfc19b7 --- /dev/null +++ b/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.dart @@ -0,0 +1,21 @@ +class Solution { + List peopleIndexes(List> favoriteCompanies) { + List> sets = favoriteCompanies.map((companies) => companies.toSet()).toList(); + List result = []; + + for (int i = 0; i < sets.length; i++) { + bool isSubset = false; + for (int j = 0; j < sets.length; j++) { + if (i != j && sets[j].containsAll(sets[i])) { + isSubset = true; + break; + } + } + if (!isSubset) { + result.add(i); + } + } + + return result; + } +} diff --git a/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.go b/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.go new file mode 100644 index 00000000..d32ee91ea --- /dev/null +++ b/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.go @@ -0,0 +1,35 @@ +func peopleIndexes(favoriteCompanies [][]string) []int { + sets := make([]map[string]bool, len(favoriteCompanies)) + for i, companies := range favoriteCompanies { + sets[i] = make(map[string]bool) + for _, company := range companies { + sets[i][company] = true + } + } + + result := []int{} + + for i := 0; i < len(sets); i++ { + isSubset := false + for j := 0; j < len(sets); j++ { + if i != j { + allFound := true + for company := range sets[i] { + if !sets[j][company] { + allFound = false + break + } + } + if allFound { + isSubset = true + break + } + } + } + if !isSubset { + result = append(result, i) + } + } + + return result +} diff --git a/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.java b/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.java new file mode 100644 index 00000000..87ca0af7 --- /dev/null +++ b/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.java @@ -0,0 +1,28 @@ +import java.util.*; + +class Solution { + public List peopleIndexes(String[][] favoriteCompanies) { + List> sets = new ArrayList<>(); + for (String[] companies : favoriteCompanies) { + sets.add(new HashSet<>(Arrays.asList(companies))); + } + + List result = new ArrayList<>(); + int n = sets.size(); + + for (int i = 0; i < n; i++) { + boolean isSubset = false; + for (int j = 0; j < n; j++) { + if (i != j && sets.get(j).containsAll(sets.get(i))) { + isSubset = true; + break; + } + } + if (!isSubset) { + result.add(i); + } + } + + return result; + } +} diff --git a/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.kt b/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.kt new file mode 100644 index 00000000..9726ca09 --- /dev/null +++ b/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.kt @@ -0,0 +1,21 @@ +class Solution { + fun peopleIndexes(favoriteCompanies: Array>): List { + val sets = favoriteCompanies.map { it.toSet() } + val result = mutableListOf() + + for (i in sets.indices) { + var isSubset = false + for (j in sets.indices) { + if (i != j && sets[j].containsAll(sets[i])) { + isSubset = true + break + } + } + if (!isSubset) { + result.add(i) + } + } + + return result + } +} diff --git a/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.py b/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.py new file mode 100644 index 00000000..b1bc3247 --- /dev/null +++ b/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.py @@ -0,0 +1,22 @@ +from typing import List + + +class Solution(object): + def peopleIndexes(self, favoriteCompanies): + """ + :type favoriteCompanies: List[List[str]] + :rtype: List[int] + """ + sets = [set(companies) for companies in favoriteCompanies] + result = [] + + for i in range(len(sets)): + is_subset = False + for j in range(len(sets)): + if i != j and sets[i].issubset(sets[j]): + is_subset = True + break + if not is_subset: + result.append(i) + + return result diff --git a/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.py2 b/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.py2 new file mode 100644 index 00000000..1873f942 --- /dev/null +++ b/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.py2 @@ -0,0 +1,19 @@ +class Solution(object): + def peopleIndexes(self, favoriteCompanies): + """ + :type favoriteCompanies: List[List[str]] + :rtype: List[int] + """ + sets = [set(companies) for companies in favoriteCompanies] + result = [] + + for i in range(len(sets)): + is_subset = False + for j in range(len(sets)): + if i != j and sets[i].issubset(sets[j]): + is_subset = True + break + if not is_subset: + result.append(i) + + return result diff --git a/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.rb b/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.rb new file mode 100644 index 00000000..ebdd1a52 --- /dev/null +++ b/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.rb @@ -0,0 +1,19 @@ +# @param {String[][]} favorite_companies +# @return {Integer[]} +def people_indexes(favorite_companies) + sets = favorite_companies.map { |companies| companies.to_set } + result = [] + + sets.each_with_index do |s, i| + is_subset = false + sets.each_with_index do |t, j| + if i != j && s.subset?(t) + is_subset = true + break + end + end + result << i unless is_subset + end + + result +end diff --git a/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.rs b/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.rs new file mode 100644 index 00000000..fdeeb4c7 --- /dev/null +++ b/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.rs @@ -0,0 +1,27 @@ +impl Solution { + pub fn people_indexes(favorite_companies: Vec>) -> Vec { + use std::collections::HashSet; + + let sets: Vec> = favorite_companies + .into_iter() + .map(|companies| companies.into_iter().collect()) + .collect(); + + let mut result = Vec::new(); + + for i in 0..sets.len() { + let mut is_subset = false; + for j in 0..sets.len() { + if i != j && sets[i].is_subset(&sets[j]) { + is_subset = true; + break; + } + } + if !is_subset { + result.push(i as i32); + } + } + + result + } +} diff --git a/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.swift b/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.swift new file mode 100644 index 00000000..3c6b7089 --- /dev/null +++ b/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.swift @@ -0,0 +1,21 @@ +class Solution { + func peopleIndexes(_ favoriteCompanies: [[String]]) -> [Int] { + let sets = favoriteCompanies.map { Set($0) } + var result: [Int] = [] + + for i in sets.indices { + var isSubset = false + for j in sets.indices { + if i != j && sets[i].isSubset(of: sets[j]) { + isSubset = true + break + } + } + if !isSubset { + result.append(i) + } + } + + return result + } +} diff --git a/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.ts b/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.ts new file mode 100644 index 00000000..b43de112 --- /dev/null +++ b/tests/1001-1500/1452. people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/sol.ts @@ -0,0 +1,30 @@ +function peopleIndexes(favoriteCompanies: string[][]): number[] { + const sets: Set[] = favoriteCompanies.map( + (companies) => new Set(companies), + ); + const result: number[] = []; + + for (let i = 0; i < sets.length; i++) { + let isSubset = false; + for (let j = 0; j < sets.length; j++) { + if (i !== j) { + let allFound = true; + for (const company of sets[i]) { + if (!sets[j].has(company)) { + allFound = false; + break; + } + } + if (allFound) { + isSubset = true; + break; + } + } + } + if (!isSubset) { + result.push(i); + } + } + + return result; +} diff --git a/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/manifest.yaml b/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/manifest.yaml new file mode 100644 index 00000000..27301107 --- /dev/null +++ b/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/manifest.yaml @@ -0,0 +1,643 @@ +entry: + id: 1453 + title: "maximum-number-of-darts-inside-of-a-circular-dartboard" + params: + darts: + type: array + items: + type: array + items: + type: int + r: + type: int + call: + cpp: "Solution().numPoints({darts}, {r})" + rust: "Solution::num_points({darts}, {r})" + python3: "Solution().numPoints({darts}, {r})" + python2: "Solution().numPoints({darts}, {r})" + ruby: "num_points({darts}, {r})" + java: "new Solution().numPoints({darts}, {r})" + csharp: "new Solution().NumPoints({darts}, {r})" + kotlin: "Solution().numPoints({darts}, {r})" + go: "numPoints({darts}, {r})" + dart: "Solution().numPoints({darts}, {r})" + swift: "Solution().numPoints({darts}, {r})" + typescript: "numPoints({darts}, {r})" +judge: + type: "exact" +limits: + time_ms: 1200 + memory_mb: 300 +oracle: + python3: + call: "Checker().numPoints(darts, r, {result})" + checker: | + class Checker: + def numPoints(self, darts, r, result): + from math import hypot, sqrt + centers = [(float(x), float(y)) for x, y in darts] + for i, (x1, y1) in enumerate(darts): + for x2, y2 in darts[i + 1:]: + dx = x2 - x1 + dy = y2 - y1 + distance = hypot(dx, dy) + if distance > 2 * r: + continue + mx = (x1 + x2) / 2.0 + my = (y1 + y2) / 2.0 + h = sqrt(max(0.0, r * r - distance * distance / 4.0)) + centers.append((mx - dy / distance * h, my + dx / distance * h)) + centers.append((mx + dy / distance * h, my - dx / distance * h)) + expected = max( + sum((x - cx) ** 2 + (y - cy) ** 2 <= r * r + 1e-7 for x, y in darts) + for cx, cy in centers + ) + return result == expected +seed: 1453 +tests: + - name: "official-cross" + in: + darts: + - [-2, 0] + - [2, 0] + - [0, 2] + - [0, -2] + r: 2 + out: 4 + - name: "official-wide-cloud" + in: + darts: + - [-3, 0] + - [3, 0] + - [2, 6] + - [5, 4] + - [0, 9] + - [7, 8] + r: 5 + out: 5 + - name: "single-point" + in: + darts: + - [0, 0] + r: 1 + out: 1 + - name: "two-close-points" + in: + darts: + - [0, 0] + - [2, 0] + r: 1 + out: 2 + - name: "two-far-points" + in: + darts: + - [0, 0] + - [3, 0] + r: 1 + out: 1 + - name: "three-collinear-close" + in: + darts: + - [-2, 0] + - [0, 0] + - [2, 0] + r: 2 + out: 3 + - name: "three-collinear-wide" + in: + darts: + - [-4, 0] + - [0, 0] + - [4, 0] + r: 2 + out: 2 + - name: "unit-square" + in: + darts: + - [0, 0] + - [1, 0] + - [0, 1] + - [1, 1] + r: 1 + out: 4 + - name: "diamond-radius-three" + in: + darts: + - [-3, 0] + - [3, 0] + - [0, -3] + - [0, 3] + r: 3 + out: 4 + - name: "diamond-too-small" + in: + darts: + - [-3, 0] + - [3, 0] + - [0, -3] + - [0, 3] + r: 2 + out: 1 + - name: "vertical-cluster" + in: + darts: + - [4, 1] + - [4, 2] + - [4, 3] + - [4, 4] + - [4, 5] + r: 2 + out: 5 + - name: "horizontal-cluster" + in: + darts: + - [-4, 7] + - [-3, 7] + - [-2, 7] + - [-1, 7] + - [0, 7] + r: 2 + out: 5 + - name: "two-clusters" + in: + darts: + - [0, 0] + - [1, 0] + - [0, 1] + - [10, 10] + - [11, 10] + - [10, 11] + r: 2 + out: 3 + - name: "negative-quadrant" + in: + darts: + - [-5, -5] + - [-4, -5] + - [-5, -4] + - [-4, -4] + r: 1 + out: 4 + - name: "large-coordinates-close" + in: + darts: + - [10000, 10000] + - [9999, 10000] + - [10000, 9999] + - [9999, 9999] + r: 1 + out: 4 + - name: "boundary-coordinate-mix" + in: + darts: + - [-10000, -10000] + - [-9999, -10000] + - [10000, 10000] + r: 1 + out: 2 + - name: "rectangle-corners" + in: + darts: + - [0, 0] + - [4, 0] + - [0, 3] + - [4, 3] + r: 2 + out: 2 + - name: "rectangle-large-radius" + in: + darts: + - [0, 0] + - [4, 0] + - [0, 3] + - [4, 3] + r: 3 + out: 4 + - name: "pentagon-small" + in: + darts: + - [0, 2] + - [2, 1] + - [1, -2] + - [-1, -2] + - [-2, 1] + r: 2 + out: 3 + - name: "star-shape" + in: + darts: + - [0, 0] + - [2, 0] + - [-2, 0] + - [0, 2] + - [0, -2] + - [1, 1] + - [-1, -1] + r: 2 + out: 7 + - name: "diagonal-line" + in: + darts: + - [0, 0] + - [1, 1] + - [2, 2] + - [3, 3] + - [4, 4] + r: 2 + out: 3 + - name: "diagonal-line-short-radius" + in: + darts: + - [0, 0] + - [1, 1] + - [2, 2] + - [3, 3] + - [4, 4] + r: 1 + out: 2 + - name: "irregular-positive" + in: + darts: + - [1, 4] + - [3, 5] + - [5, 2] + - [7, 6] + - [8, 1] + r: 3 + out: 3 + - name: "irregular-negative" + in: + darts: + - [-8, -1] + - [-7, -5] + - [-4, -2] + - [-2, -6] + - [0, -3] + r: 3 + out: 3 + - name: "dense-grid" + in: + darts: + - [0, 0] + - [1, 0] + - [2, 0] + - [0, 1] + - [1, 1] + - [2, 1] + - [0, 2] + - [1, 2] + - [2, 2] + r: 2 + out: 9 + - name: "grid-corners-only" + in: + darts: + - [0, 0] + - [2, 0] + - [0, 2] + - [2, 2] + - [1, 1] + r: 1 + out: 3 + - name: "one-outlier" + in: + darts: + - [0, 0] + - [1, 0] + - [0, 1] + - [1, 1] + - [20, 20] + r: 1 + out: 4 + - name: "two-outliers" + in: + darts: + - [0, 0] + - [1, 0] + - [0, 1] + - [20, 20] + - [-20, -20] + r: 1 + out: 3 + - name: "radius-one-chain" + in: + darts: + - [0, 0] + - [1, 0] + - [2, 0] + - [3, 0] + - [4, 0] + - [5, 0] + r: 1 + out: 3 + - name: "radius-five-chain" + in: + darts: + - [0, 0] + - [2, 0] + - [4, 0] + - [6, 0] + - [8, 0] + - [10, 0] + r: 5 + out: 6 + - name: "mixed-boundary" + in: + darts: + - [-10000, 0] + - [-9998, 0] + - [9998, 0] + - [10000, 0] + r: 2 + out: 2 + - name: "near-tangent-pair" + in: + darts: + - [0, 0] + - [6, 8] + - [3, 4] + r: 5 + out: 3 + - name: "off-axis-triangle" + in: + darts: + - [0, 0] + - [4, 0] + - [2, 3] + - [8, 8] + r: 3 + out: 3 + - name: "many-close-points" + in: + darts: + - [-1, -1] + - [0, -1] + - [1, -1] + - [-1, 0] + - [0, 0] + - [1, 0] + - [-1, 1] + - [0, 1] + - [1, 1] + r: 2 + out: 9 + - name: "offset-square" + in: + darts: + - [10, 10] + - [12, 10] + - [10, 12] + - [12, 12] + - [11, 11] + r: 2 + out: 5 + - name: "ten-by-ten-unit-grid" + in: + darts: + - [0, 0] + - [1, 0] + - [2, 0] + - [3, 0] + - [4, 0] + - [5, 0] + - [6, 0] + - [7, 0] + - [8, 0] + - [9, 0] + - [0, 1] + - [1, 1] + - [2, 1] + - [3, 1] + - [4, 1] + - [5, 1] + - [6, 1] + - [7, 1] + - [8, 1] + - [9, 1] + - [0, 2] + - [1, 2] + - [2, 2] + - [3, 2] + - [4, 2] + - [5, 2] + - [6, 2] + - [7, 2] + - [8, 2] + - [9, 2] + - [0, 3] + - [1, 3] + - [2, 3] + - [3, 3] + - [4, 3] + - [5, 3] + - [6, 3] + - [7, 3] + - [8, 3] + - [9, 3] + - [0, 4] + - [1, 4] + - [2, 4] + - [3, 4] + - [4, 4] + - [5, 4] + - [6, 4] + - [7, 4] + - [8, 4] + - [9, 4] + - [0, 5] + - [1, 5] + - [2, 5] + - [3, 5] + - [4, 5] + - [5, 5] + - [6, 5] + - [7, 5] + - [8, 5] + - [9, 5] + - [0, 6] + - [1, 6] + - [2, 6] + - [3, 6] + - [4, 6] + - [5, 6] + - [6, 6] + - [7, 6] + - [8, 6] + - [9, 6] + - [0, 7] + - [1, 7] + - [2, 7] + - [3, 7] + - [4, 7] + - [5, 7] + - [6, 7] + - [7, 7] + - [8, 7] + - [9, 7] + - [0, 8] + - [1, 8] + - [2, 8] + - [3, 8] + - [4, 8] + - [5, 8] + - [6, 8] + - [7, 8] + - [8, 8] + - [9, 8] + - [0, 9] + - [1, 9] + - [2, 9] + - [3, 9] + - [4, 9] + - [5, 9] + - [6, 9] + - [7, 9] + - [8, 9] + - [9, 9] + r: 3 + out: 32 + - name: "ten-by-ten-max-radius-grid" + in: + darts: + - [0, 0] + - [1, 0] + - [2, 0] + - [3, 0] + - [4, 0] + - [5, 0] + - [6, 0] + - [7, 0] + - [8, 0] + - [9, 0] + - [0, 1] + - [1, 1] + - [2, 1] + - [3, 1] + - [4, 1] + - [5, 1] + - [6, 1] + - [7, 1] + - [8, 1] + - [9, 1] + - [0, 2] + - [1, 2] + - [2, 2] + - [3, 2] + - [4, 2] + - [5, 2] + - [6, 2] + - [7, 2] + - [8, 2] + - [9, 2] + - [0, 3] + - [1, 3] + - [2, 3] + - [3, 3] + - [4, 3] + - [5, 3] + - [6, 3] + - [7, 3] + - [8, 3] + - [9, 3] + - [0, 4] + - [1, 4] + - [2, 4] + - [3, 4] + - [4, 4] + - [5, 4] + - [6, 4] + - [7, 4] + - [8, 4] + - [9, 4] + - [0, 5] + - [1, 5] + - [2, 5] + - [3, 5] + - [4, 5] + - [5, 5] + - [6, 5] + - [7, 5] + - [8, 5] + - [9, 5] + - [0, 6] + - [1, 6] + - [2, 6] + - [3, 6] + - [4, 6] + - [5, 6] + - [6, 6] + - [7, 6] + - [8, 6] + - [9, 6] + - [0, 7] + - [1, 7] + - [2, 7] + - [3, 7] + - [4, 7] + - [5, 7] + - [6, 7] + - [7, 7] + - [8, 7] + - [9, 7] + - [0, 8] + - [1, 8] + - [2, 8] + - [3, 8] + - [4, 8] + - [5, 8] + - [6, 8] + - [7, 8] + - [8, 8] + - [9, 8] + - [0, 9] + - [1, 9] + - [2, 9] + - [3, 9] + - [4, 9] + - [5, 9] + - [6, 9] + - [7, 9] + - [8, 9] + - [9, 9] + r: 5000 + out: 100 + - name: "axis-cross-with-far-corners" + in: + darts: + - [-5, 0] + - [-3, 0] + - [-1, 0] + - [1, 0] + - [3, 0] + - [5, 0] + - [0, 4] + - [0, -4] + - [20, 20] + - [-20, -20] + r: 5 + out: 8 + - name: "four-corner-boundary" + in: + darts: + - [-4, -3] + - [-4, 3] + - [4, -3] + - [4, 3] + - [0, 0] + - [0, 5] + - [0, -5] + r: 5 + out: 7 + - name: "separated-pairs" + in: + darts: + - [-10000, 10000] + - [-9999, 10000] + - [9999, -10000] + - [10000, -10000] + - [0, 0] + - [2, 0] + - [0, 2] + - [2, 2] + r: 1 + out: 2 diff --git a/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.cpp b/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.cpp new file mode 100644 index 00000000..77f0bcad --- /dev/null +++ b/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + int numPoints(vector>& darts, int r) { + int ans = 1; + double radius = r; + double radiusSq = radius * radius; + for (int i = 0; i < darts.size(); ++i) { + double x1 = darts[i][0], y1 = darts[i][1]; + for (int j = i + 1; j < darts.size(); ++j) { + double x2 = darts[j][0], y2 = darts[j][1]; + double dx = x2 - x1, dy = y2 - y1; + double distanceSq = dx * dx + dy * dy; + if (distanceSq > 4.0 * radiusSq) continue; + double distance = sqrt(distanceSq); + double midpointX = (x1 + x2) / 2.0; + double midpointY = (y1 + y2) / 2.0; + double offset = sqrt(max(0.0, radiusSq - distanceSq / 4.0)); + double normalX = -dy / distance; + double normalY = dx / distance; + for (double sign : {-1.0, 1.0}) { + double centerX = midpointX + sign * offset * normalX; + double centerY = midpointY + sign * offset * normalY; + int count = 0; + for (const auto& dart : darts) { + double ex = dart[0] - centerX; + double ey = dart[1] - centerY; + if (ex * ex + ey * ey <= radiusSq + 1e-9) ++count; + } + ans = max(ans, count); + } + } + } + return ans; + } +}; diff --git a/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.cs b/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.cs new file mode 100644 index 00000000..9c7409c8 --- /dev/null +++ b/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.cs @@ -0,0 +1,34 @@ +public class Solution { + public int NumPoints(int[][] darts, int r) { + int ans = 1; + double radius = r; + double radiusSq = radius * radius; + for (int i = 0; i < darts.Length; i++) { + double x1 = darts[i][0], y1 = darts[i][1]; + for (int j = i + 1; j < darts.Length; j++) { + double x2 = darts[j][0], y2 = darts[j][1]; + double dx = x2 - x1, dy = y2 - y1; + double distanceSq = dx * dx + dy * dy; + if (distanceSq > 4.0 * radiusSq) continue; + double distance = Math.Sqrt(distanceSq); + double midpointX = (x1 + x2) / 2.0; + double midpointY = (y1 + y2) / 2.0; + double offset = Math.Sqrt(Math.Max(0.0, radiusSq - distanceSq / 4.0)); + double normalX = -dy / distance; + double normalY = dx / distance; + foreach (double sign in new[] { -1.0, 1.0 }) { + double centerX = midpointX + sign * offset * normalX; + double centerY = midpointY + sign * offset * normalY; + int count = 0; + foreach (var dart in darts) { + double ex = dart[0] - centerX; + double ey = dart[1] - centerY; + if (ex * ex + ey * ey <= radiusSq + 1e-9) count++; + } + ans = Math.Max(ans, count); + } + } + } + return ans; + } +} diff --git a/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.dart b/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.dart new file mode 100644 index 00000000..6bdec67b --- /dev/null +++ b/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.dart @@ -0,0 +1,36 @@ +import 'dart:math'; + +class Solution { + int numPoints(List> darts, int r) { + int ans = 1; + double radius = r.toDouble(); + double radiusSq = radius * radius; + for (int i = 0; i < darts.length; i++) { + double x1 = darts[i][0].toDouble(), y1 = darts[i][1].toDouble(); + for (int j = i + 1; j < darts.length; j++) { + double x2 = darts[j][0].toDouble(), y2 = darts[j][1].toDouble(); + double dx = x2 - x1, dy = y2 - y1; + double distanceSq = dx * dx + dy * dy; + if (distanceSq > 4.0 * radiusSq) continue; + double distance = sqrt(distanceSq); + double midpointX = (x1 + x2) / 2.0; + double midpointY = (y1 + y2) / 2.0; + double offset = sqrt(max(0.0, radiusSq - distanceSq / 4.0)); + double normalX = -dy / distance; + double normalY = dx / distance; + for (double sign in [-1.0, 1.0]) { + double centerX = midpointX + sign * offset * normalX; + double centerY = midpointY + sign * offset * normalY; + int count = 0; + for (var dart in darts) { + double ex = dart[0] - centerX; + double ey = dart[1] - centerY; + if (ex * ex + ey * ey <= radiusSq + 1e-9) count++; + } + ans = max(ans, count); + } + } + } + return ans; + } +} diff --git a/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.go b/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.go new file mode 100644 index 00000000..a0f8f820 --- /dev/null +++ b/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.go @@ -0,0 +1,36 @@ +func numPoints(darts [][]int, r int) int { + ans := 1 + radius := float64(r) + radiusSq := radius * radius + for i := 0; i < len(darts); i++ { + x1, y1 := float64(darts[i][0]), float64(darts[i][1]) + for j := i + 1; j < len(darts); j++ { + x2, y2 := float64(darts[j][0]), float64(darts[j][1]) + dx, dy := x2-x1, y2-y1 + distanceSq := dx*dx + dy*dy + if distanceSq > 4.0*radiusSq { + continue + } + distance := math.Sqrt(distanceSq) + midpointX, midpointY := (x1+x2)/2.0, (y1+y2)/2.0 + offset := math.Sqrt(math.Max(0.0, radiusSq-distanceSq/4.0)) + normalX, normalY := -dy/distance, dx/distance + for _, sign := range []float64{-1.0, 1.0} { + centerX := midpointX + sign*offset*normalX + centerY := midpointY + sign*offset*normalY + count := 0 + for _, dart := range darts { + ex := float64(dart[0]) - centerX + ey := float64(dart[1]) - centerY + if ex*ex+ey*ey <= radiusSq+1e-9 { + count++ + } + } + if count > ans { + ans = count + } + } + } + } + return ans +} diff --git a/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.java b/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.java new file mode 100644 index 00000000..eba064da --- /dev/null +++ b/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.java @@ -0,0 +1,34 @@ +class Solution { + public int numPoints(int[][] darts, int r) { + int ans = 1; + double radius = r; + double radiusSq = radius * radius; + for (int i = 0; i < darts.length; i++) { + double x1 = darts[i][0], y1 = darts[i][1]; + for (int j = i + 1; j < darts.length; j++) { + double x2 = darts[j][0], y2 = darts[j][1]; + double dx = x2 - x1, dy = y2 - y1; + double distanceSq = dx * dx + dy * dy; + if (distanceSq > 4.0 * radiusSq) continue; + double distance = Math.sqrt(distanceSq); + double midpointX = (x1 + x2) / 2.0; + double midpointY = (y1 + y2) / 2.0; + double offset = Math.sqrt(Math.max(0.0, radiusSq - distanceSq / 4.0)); + double normalX = -dy / distance; + double normalY = dx / distance; + for (double sign : new double[]{-1.0, 1.0}) { + double centerX = midpointX + sign * offset * normalX; + double centerY = midpointY + sign * offset * normalY; + int count = 0; + for (int[] dart : darts) { + double ex = dart[0] - centerX; + double ey = dart[1] - centerY; + if (ex * ex + ey * ey <= radiusSq + 1e-9) count++; + } + ans = Math.max(ans, count); + } + } + } + return ans; + } +} diff --git a/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.kt b/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.kt new file mode 100644 index 00000000..46945741 --- /dev/null +++ b/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.kt @@ -0,0 +1,37 @@ +class Solution { + fun numPoints(darts: Array, r: Int): Int { + var ans = 1 + val radius = r.toDouble() + val radiusSq = radius * radius + for (i in darts.indices) { + val x1 = darts[i][0].toDouble() + val y1 = darts[i][1].toDouble() + for (j in i + 1 until darts.size) { + val x2 = darts[j][0].toDouble() + val y2 = darts[j][1].toDouble() + val dx = x2 - x1 + val dy = y2 - y1 + val distanceSq = dx * dx + dy * dy + if (distanceSq > 4.0 * radiusSq) continue + val distance = Math.sqrt(distanceSq) + val midpointX = (x1 + x2) / 2.0 + val midpointY = (y1 + y2) / 2.0 + val offset = Math.sqrt(maxOf(0.0, radiusSq - distanceSq / 4.0)) + val normalX = -dy / distance + val normalY = dx / distance + for (sign in doubleArrayOf(-1.0, 1.0)) { + val centerX = midpointX + sign * offset * normalX + val centerY = midpointY + sign * offset * normalY + var count = 0 + for (dart in darts) { + val ex = dart[0] - centerX + val ey = dart[1] - centerY + if (ex * ex + ey * ey <= radiusSq + 1e-9) count++ + } + ans = maxOf(ans, count) + } + } + } + return ans + } +} diff --git a/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.py b/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.py new file mode 100644 index 00000000..e50ad058 --- /dev/null +++ b/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.py @@ -0,0 +1,31 @@ +from math import acos, atan2, sqrt +from typing import List + + +class Solution: + def numPoints(self, points: List[List[int]], r: int) -> int: + ans = 1 + radius = float(r) + radius_sq = radius * radius + for i, (x1, y1) in enumerate(points): + for x2, y2 in points[i + 1 :]: + dx = x2 - x1 + dy = y2 - y1 + distance_sq = dx * dx + dy * dy + if distance_sq > 4 * radius_sq: + continue + distance = sqrt(distance_sq) + midpoint_x = (x1 + x2) / 2.0 + midpoint_y = (y1 + y2) / 2.0 + offset = sqrt(max(0.0, radius_sq - distance_sq / 4.0)) + normal_x = -dy / distance + normal_y = dx / distance + for sign in (-1.0, 1.0): + center_x = midpoint_x + sign * offset * normal_x + center_y = midpoint_y + sign * offset * normal_y + count = sum( + (x - center_x) ** 2 + (y - center_y) ** 2 <= radius_sq + 1e-9 + for x, y in points + ) + ans = max(ans, count) + return ans diff --git a/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.py2 b/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.py2 new file mode 100644 index 00000000..0242dcdb --- /dev/null +++ b/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.py2 @@ -0,0 +1,36 @@ +class Solution(object): + def numPoints(self, darts, r): + """ + :type darts: List[List[int]] + :type r: int + :rtype: int + """ + from math import acos, atan2, sqrt + ans = 1 + radius = float(r) + radius_sq = radius * radius + for i in range(len(darts)): + x1, y1 = darts[i] + for j in range(i + 1, len(darts)): + x2, y2 = darts[j] + dx = x2 - x1 + dy = y2 - y1 + distance_sq = dx * dx + dy * dy + if distance_sq > 4 * radius_sq: + continue + distance = sqrt(distance_sq) + midpoint_x = (x1 + x2) / 2.0 + midpoint_y = (y1 + y2) / 2.0 + offset = sqrt(max(0.0, radius_sq - distance_sq / 4.0)) + normal_x = -dy / distance + normal_y = dx / distance + for sign in (-1.0, 1.0): + center_x = midpoint_x + sign * offset * normal_x + center_y = midpoint_y + sign * offset * normal_y + count = 0 + for x, y in darts: + if ((x - center_x) ** 2 + (y - center_y) ** 2 + <= radius_sq + 1e-9): + count += 1 + ans = max(ans, count) + return ans diff --git a/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.rb b/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.rb new file mode 100644 index 00000000..0a009b09 --- /dev/null +++ b/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.rb @@ -0,0 +1,34 @@ +# @param {Integer[][]} darts +# @param {Integer} r +# @return {Integer} +def num_points(darts, r) + ans = 1 + radius = r.to_f + radius_sq = radius * radius + darts.each_with_index do |point1, i| + ((i + 1)...darts.length).each do |j| + point2 = darts[j] + x1, y1 = point1 + x2, y2 = point2 + dx = x2 - x1 + dy = y2 - y1 + distance_sq = dx * dx + dy * dy + next if distance_sq > 4.0 * radius_sq + distance = Math.sqrt(distance_sq) + midpoint_x = (x1 + x2) / 2.0 + midpoint_y = (y1 + y2) / 2.0 + offset = Math.sqrt([0.0, radius_sq - distance_sq / 4.0].max) + normal_x = -dy / distance + normal_y = dx / distance + [-1.0, 1.0].each do |sign| + center_x = midpoint_x + sign * offset * normal_x + center_y = midpoint_y + sign * offset * normal_y + count = darts.count do |x, y| + (x - center_x) ** 2 + (y - center_y) ** 2 <= radius_sq + 1e-9 + end + ans = count if count > ans + end + end + end + ans +end diff --git a/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.rs b/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.rs new file mode 100644 index 00000000..df93e332 --- /dev/null +++ b/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.rs @@ -0,0 +1,37 @@ +impl Solution { + pub fn num_points(darts: Vec>, r: i32) -> i32 { + let mut ans = 1; + let radius = r as f64; + let radius_sq = radius * radius; + for i in 0..darts.len() { + let x1 = darts[i][0] as f64; + let y1 = darts[i][1] as f64; + for j in (i + 1)..darts.len() { + let x2 = darts[j][0] as f64; + let y2 = darts[j][1] as f64; + let dx = x2 - x1; + let dy = y2 - y1; + let distance_sq = dx * dx + dy * dy; + if distance_sq > 4.0 * radius_sq { continue; } + let distance = distance_sq.sqrt(); + let midpoint_x = (x1 + x2) / 2.0; + let midpoint_y = (y1 + y2) / 2.0; + let offset = (radius_sq - distance_sq / 4.0).max(0.0).sqrt(); + let normal_x = -dy / distance; + let normal_y = dx / distance; + for sign in [-1.0, 1.0] { + let center_x = midpoint_x + sign * offset * normal_x; + let center_y = midpoint_y + sign * offset * normal_y; + let mut count = 0; + for dart in &darts { + let ex = dart[0] as f64 - center_x; + let ey = dart[1] as f64 - center_y; + if ex * ex + ey * ey <= radius_sq + 1e-9 { count += 1; } + } + ans = ans.max(count); + } + } + } + ans + } +} diff --git a/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.swift b/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.swift new file mode 100644 index 00000000..85e4a2c7 --- /dev/null +++ b/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.swift @@ -0,0 +1,37 @@ +import Foundation + +class Solution { + func numPoints(_ darts: [[Int]], _ r: Int) -> Int { + var ans = 1 + let radius = Double(r) + let radiusSq = radius * radius + for i in 0..= darts.count { continue } + for j in (i + 1).. 4.0 * radiusSq { continue } + let distance = sqrt(distanceSq) + let midpointX = (x1 + x2) / 2.0 + let midpointY = (y1 + y2) / 2.0 + let offset = sqrt(max(0.0, radiusSq - distanceSq / 4.0)) + let normalX = -dy / distance + let normalY = dx / distance + for sign in [-1.0, 1.0] { + let centerX = midpointX + sign * offset * normalX + let centerY = midpointY + sign * offset * normalY + var count = 0 + for dart in darts { + let ex = Double(dart[0]) - centerX + let ey = Double(dart[1]) - centerY + if ex * ex + ey * ey <= radiusSq + 1e-9 { count += 1 } + } + ans = max(ans, count) + } + } + } + return ans + } +} diff --git a/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.ts b/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.ts new file mode 100644 index 00000000..1d7b7fc1 --- /dev/null +++ b/tests/1001-1500/1453. maximum-number-of-darts-inside-of-a-circular-dartboard/sol.ts @@ -0,0 +1,33 @@ +function numPoints(darts: number[][], r: number): number { + let ans = 1; + const radius = r; + const radiusSq = radius * radius; + for (let i = 0; i < darts.length; i++) { + const [x1, y1] = darts[i]; + for (let j = i + 1; j < darts.length; j++) { + const [x2, y2] = darts[j]; + const dx = x2 - x1; + const dy = y2 - y1; + const distanceSq = dx * dx + dy * dy; + if (distanceSq > 4 * radiusSq) continue; + const distance = Math.sqrt(distanceSq); + const midpointX = (x1 + x2) / 2; + const midpointY = (y1 + y2) / 2; + const offset = Math.sqrt(Math.max(0, radiusSq - distanceSq / 4)); + const normalX = -dy / distance; + const normalY = dx / distance; + for (const sign of [-1, 1]) { + const centerX = midpointX + sign * offset * normalX; + const centerY = midpointY + sign * offset * normalY; + let count = 0; + for (const [x, y] of darts) { + const ex = x - centerX; + const ey = y - centerY; + if (ex * ex + ey * ey <= radiusSq + 1e-9) count++; + } + ans = Math.max(ans, count); + } + } + } + return ans; +} diff --git a/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/manifest.yaml b/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/manifest.yaml new file mode 100644 index 00000000..de4eb02e --- /dev/null +++ b/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/manifest.yaml @@ -0,0 +1,283 @@ +entry: + id: 1455 + title: "check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence" + params: + sentence: + type: string + searchWord: + type: string + call: + cpp: "Solution().isPrefixOfWord({sentence}, {searchWord})" + rust: "Solution::is_prefix_of_word({sentence}, {searchWord})" + python3: "Solution().isPrefixOfWord({sentence}, {searchWord})" + python2: "Solution().isPrefixOfWord({sentence}, {searchWord})" + ruby: "is_prefix_of_word({sentence}, {searchWord})" + java: "new Solution().isPrefixOfWord({sentence}, {searchWord})" + csharp: "new Solution().IsPrefixOfWord({sentence}, {searchWord})" + kotlin: "Solution().isPrefixOfWord({sentence}, {searchWord})" + go: "isPrefixOfWord({sentence}, {searchWord})" + dart: "Solution().isPrefixOfWord({sentence}, {searchWord})" + swift: "Solution().isPrefixOfWord({sentence}, {searchWord})" + typescript: "isPrefixOfWord({sentence}, {searchWord})" +judge: + type: exact +limits: + time_ms: 300 + memory_mb: 300 +oracle: + python3: + call: "Checker().isPrefixOfWord(sentence, searchWord, {result})" + checker: | + class Checker: + def isPrefixOfWord(self, sentence, searchWord, result): + for index, word in enumerate(sentence.split(' '), 1): + if word.startswith(searchWord): + return result == index + return result == -1 +seed: 1455 +tests: + - name: example_burger + in: + sentence: i love eating burger + searchWord: burg + out: 4 + - name: example_repeated_problem + in: + sentence: this problem is an easy problem + searchWord: pro + out: 2 + - name: example_absent + in: + sentence: i am tired + searchWord: you + out: -1 + - name: prefix_first_word + in: + sentence: hello world + searchWord: he + out: 1 + - name: prefix_last_word + in: + sentence: one two three + searchWord: thr + out: 3 + - name: absent_between_matches + in: + sentence: one two three + searchWord: four + out: -1 + - name: one_word_prefix + in: + sentence: apple + searchWord: app + out: 1 + - name: one_word_absent + in: + sentence: apple + searchWord: pea + out: -1 + - name: repeated_prefix_first + in: + sentence: alpha alphabet alps + searchWord: alp + out: 1 + - name: single_letter_prefix + in: + sentence: a ab abc + searchWord: a + out: 1 + - name: maximum_search_exact + in: + sentence: abcdefghij abc + searchWord: abcdefghij + out: 1 + - name: middle_word_prefix + in: + sentence: red green blue yellow + searchWord: blu + out: 3 + - name: first_matching_after_nonmatch + in: + sentence: zebra apple mango + searchWord: a + out: 2 + - name: third_word_prefix + in: + sentence: zebra apple mango + searchWord: man + out: 3 + - name: brown_prefix + in: + sentence: quick brown fox jumps + searchWord: bro + out: 2 + - name: jumps_prefix + in: + sentence: quick brown fox jumps + searchWord: jum + out: 4 + - name: first_letter_match + in: + sentence: quick brown fox jumps + searchWord: q + out: 1 + - name: letter_only_absent + in: + sentence: quick brown fox jumps + searchWord: x + out: -1 + - name: exact_final_short_word + in: + sentence: programming is fun + searchWord: fun + out: 3 + - name: long_prefix + in: + sentence: programming is fun + searchWord: program + out: 1 + - name: progress_prefix + in: + sentence: coding makes progress + searchWord: pro + out: 3 + - name: makes_prefix + in: + sentence: coding makes progress + searchWord: mak + out: 2 + - name: coding_prefix + in: + sentence: coding makes progress + searchWord: cod + out: 1 + - name: repeated_late_word + in: + sentence: words can repeat repeat + searchWord: rep + out: 3 + - name: matter_prefix + in: + sentence: small words matter + searchWord: mat + out: 3 + - name: small_prefix + in: + sentence: small words matter + searchWord: sm + out: 1 + - name: delta_prefix + in: + sentence: alpha beta gamma delta + searchWord: del + out: 4 + - name: gamma_prefix + in: + sentence: alpha beta gamma delta + searchWord: gam + out: 3 + - name: matching_prefix_later + in: + sentence: find the matching word + searchWord: mat + out: 3 + - name: word_exact_last + in: + sentence: find the matching word + searchWord: word + out: 4 + - name: prefix_after_single_letter_word + in: + sentence: a brave new world + searchWord: new + out: 3 + - name: no_match_same_letters_later + in: + sentence: cat scatter catalog + searchWord: at + out: -1 + - name: earliest_among_many + in: + sentence: preface prepare present prevent + searchWord: pre + out: 1 + - name: maximum_length_sentence + in: + sentence: aaaaaaaaaa bbbbbbbbbb cccccccccc dddddddddd eeeeeeeeee ffffffffff gggggggggg hhhhhhhhhh iiiiiiiiii + searchWord: iiiii + out: 9 + - name: maximum_length_late_match + in: + sentence: aa ab ac ad ae af ag ah ai aj ak al am an ao ap aq ar as at au av aw ax ay az ba bb bc bd be bf bg + searchWord: bg + out: 33 + - name: generated_max_lowercase_1 + seed: 145501 + in: + sentence: + gen: "str" + len: 100 + alphabet: "abcdefghijklmnopqrstuvwxyz" + searchWord: + gen: "str" + len: + gen: "int" + min: 1 + max: 10 + alphabet: "abcdefghijklmnopqrstuvwxyz" + - name: generated_max_lowercase_2 + seed: 145502 + in: + sentence: + gen: "str" + len: 100 + alphabet: "abcdefghijklmnopqrstuvwxyz" + searchWord: + gen: "str" + len: + gen: "int" + min: 1 + max: 10 + alphabet: "abcdefghijklmnopqrstuvwxyz" + - name: generated_max_lowercase_3 + seed: 145503 + in: + sentence: + gen: "str" + len: 100 + alphabet: "abcdefghijklmnopqrstuvwxyz" + searchWord: + gen: "str" + len: + gen: "int" + min: 1 + max: 10 + alphabet: "abcdefghijklmnopqrstuvwxyz" + - name: generated_max_lowercase_4 + seed: 145504 + in: + sentence: + gen: "str" + len: 100 + alphabet: "abcdefghijklmnopqrstuvwxyz" + searchWord: + gen: "str" + len: + gen: "int" + min: 1 + max: 10 + alphabet: "abcdefghijklmnopqrstuvwxyz" + - name: generated_max_lowercase_5 + seed: 145505 + in: + sentence: + gen: "str" + len: 100 + alphabet: "abcdefghijklmnopqrstuvwxyz" + searchWord: + gen: "str" + len: + gen: "int" + min: 1 + max: 10 + alphabet: "abcdefghijklmnopqrstuvwxyz" diff --git a/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.cpp b/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.cpp new file mode 100644 index 00000000..ed3c51fa --- /dev/null +++ b/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int isPrefixOfWord(string sentence, string searchWord) { + istringstream iss(sentence); + string word; + int index = 1; + while (iss >> word) { + if (word.substr(0, searchWord.length()) == searchWord) { + return index; + } + index++; + } + return -1; + } +}; diff --git a/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.cs b/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.cs new file mode 100644 index 00000000..d8818209 --- /dev/null +++ b/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.cs @@ -0,0 +1,11 @@ +public class Solution { + public int IsPrefixOfWord(string sentence, string searchWord) { + string[] words = sentence.Split(" "); + for (int i = 0; i < words.Length; i++) { + if (words[i].StartsWith(searchWord)) { + return i + 1; + } + } + return -1; + } +} diff --git a/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.dart b/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.dart new file mode 100644 index 00000000..1c9ddab0 --- /dev/null +++ b/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.dart @@ -0,0 +1,11 @@ +class Solution { + int isPrefixOfWord(String sentence, String searchWord) { + List words = sentence.split(" "); + for (int i = 0; i < words.length; i++) { + if (words[i].startsWith(searchWord)) { + return i + 1; + } + } + return -1; + } +} diff --git a/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.go b/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.go new file mode 100644 index 00000000..108aa327 --- /dev/null +++ b/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.go @@ -0,0 +1,9 @@ +func isPrefixOfWord(sentence string, searchWord string) int { + words := strings.Split(sentence, " ") + for i, word := range words { + if strings.HasPrefix(word, searchWord) { + return i + 1 + } + } + return -1 +} diff --git a/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.java b/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.java new file mode 100644 index 00000000..f79d3582 --- /dev/null +++ b/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.java @@ -0,0 +1,11 @@ +class Solution { + public int isPrefixOfWord(String sentence, String searchWord) { + String[] words = sentence.split(" "); + for (int i = 0; i < words.length; i++) { + if (words[i].startsWith(searchWord)) { + return i + 1; + } + } + return -1; + } +} diff --git a/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.kt b/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.kt new file mode 100644 index 00000000..cae079fb --- /dev/null +++ b/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.kt @@ -0,0 +1,11 @@ +class Solution { + fun isPrefixOfWord(sentence: String, searchWord: String): Int { + val words = sentence.split(" ") + for (i in words.indices) { + if (words[i].startsWith(searchWord)) { + return i + 1 + } + } + return -1 + } +} diff --git a/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.py b/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.py new file mode 100644 index 00000000..4b1ed710 --- /dev/null +++ b/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.py @@ -0,0 +1,7 @@ +class Solution: + def isPrefixOfWord(self, sentence: str, searchWord: str) -> int: + words = sentence.split(" ") + for i in words: + if searchWord == i[: len(searchWord)]: + return words.index(i) + 1 + return -1 diff --git a/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.py2 b/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.py2 new file mode 100644 index 00000000..f339040b --- /dev/null +++ b/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.py2 @@ -0,0 +1,12 @@ +class Solution(object): + def isPrefixOfWord(self, sentence, searchWord): + """ + :type sentence: str + :type searchWord: str + :rtype: int + """ + words = sentence.split(" ") + for i in words: + if searchWord == i[:len(searchWord)]: + return words.index(i) + 1 + return -1 diff --git a/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.rb b/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.rb new file mode 100644 index 00000000..d0e119e3 --- /dev/null +++ b/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.rb @@ -0,0 +1,12 @@ +# @param {String} sentence +# @param {String} search_word +# @return {Integer} +def is_prefix_of_word(sentence, search_word) + words = sentence.split(" ") + words.each do |i| + if search_word == i[0, search_word.length] + return words.index(i) + 1 + end + end + -1 +end diff --git a/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.rs b/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.rs new file mode 100644 index 00000000..2840a6dc --- /dev/null +++ b/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.rs @@ -0,0 +1,11 @@ +impl Solution { + pub fn is_prefix_of_word(sentence: String, search_word: String) -> i32 { + let words: Vec<&str> = sentence.split_whitespace().collect(); + for i in 0..words.len() { + if words[i].starts_with(&search_word) { + return (i + 1) as i32; + } + } + -1 + } +} diff --git a/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.swift b/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.swift new file mode 100644 index 00000000..ae5632b6 --- /dev/null +++ b/tests/1001-1500/1455. check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/sol.swift @@ -0,0 +1,11 @@ +class Solution { + func isPrefixOfWord(_ sentence: String, _ searchWord: String) -> Int { + let words = sentence.split(separator: " ") + for i in 0.. maxVowel) { + maxVowel = vowel; + } + if (isVowel(s[left])) { + vowel--; + } + left++; + } + } + + return maxVowel; + } +} diff --git a/tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.go b/tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.go new file mode 100644 index 00000000..79cbb38a --- /dev/null +++ b/tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.go @@ -0,0 +1,27 @@ +func isVowel(c byte) bool { + return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' +} + +func maxVowels(s string, k int) int { + maxVowel := 0 + left := 0 + vowel := 0 + + for right := 0; right < len(s); right++ { + if isVowel(s[right]) { + vowel++ + } + + if (right - left + 1) == k { + if vowel > maxVowel { + maxVowel = vowel + } + if isVowel(s[left]) { + vowel-- + } + left++ + } + } + + return maxVowel +} diff --git a/tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.java b/tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.java new file mode 100644 index 00000000..099f3fed --- /dev/null +++ b/tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.java @@ -0,0 +1,27 @@ +class Solution { + private boolean isVowel(char c) { + return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; + } + + public int maxVowels(String s, int k) { + int maxVowel = 0; + int left = 0; + int vowel = 0; + + for (int right = 0; right < s.length(); right++) { + if (isVowel(s.charAt(right))) { + vowel++; + } + + if ((right - left + 1) == k) { + maxVowel = Math.max(maxVowel, vowel); + if (isVowel(s.charAt(left))) { + vowel--; + } + left++; + } + } + + return maxVowel; + } +} diff --git a/tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.kt b/tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.kt new file mode 100644 index 00000000..0f34b290 --- /dev/null +++ b/tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.kt @@ -0,0 +1,27 @@ +class Solution { + private fun isVowel(c: Char): Boolean { + return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' + } + + fun maxVowels(s: String, k: Int): Int { + var maxVowel = 0 + var left = 0 + var vowel = 0 + + for (right in s.indices) { + if (isVowel(s[right])) { + vowel++ + } + + if ((right - left + 1) == k) { + maxVowel = maxOf(maxVowel, vowel) + if (isVowel(s[left])) { + vowel-- + } + left++ + } + } + + return maxVowel + } +} diff --git a/tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.py b/tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.py new file mode 100644 index 00000000..d96bad17 --- /dev/null +++ b/tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.py @@ -0,0 +1,20 @@ +class Solution: + def is_vowel(self, c: str) -> bool: + return c in {"a", "e", "i", "o", "u"} + + def maxVowels(self, s: str, k: int) -> int: + max_vowel = 0 + left = 0 + vowel = 0 + + for right in range(len(s)): + if self.is_vowel(s[right]): + vowel += 1 + + if (right - left + 1) == k: + max_vowel = max(max_vowel, vowel) + if self.is_vowel(s[left]): + vowel -= 1 + left += 1 + + return max_vowel diff --git a/tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.py2 b/tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.py2 new file mode 100644 index 00000000..f30812b3 --- /dev/null +++ b/tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.py2 @@ -0,0 +1,25 @@ +class Solution(object): + def is_vowel(self, c): + return c in {'a', 'e', 'i', 'o', 'u'} + + def maxVowels(self, s, k): + """ + :type s: str + :type k: int + :rtype: int + """ + max_vowel = 0 + left = 0 + vowel = 0 + + for right in range(len(s)): + if self.is_vowel(s[right]): + vowel += 1 + + if (right - left + 1) == k: + max_vowel = max(max_vowel, vowel) + if self.is_vowel(s[left]): + vowel -= 1 + left += 1 + + return max_vowel diff --git a/tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.rb b/tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.rb new file mode 100644 index 00000000..23774cbd --- /dev/null +++ b/tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.rb @@ -0,0 +1,28 @@ +# @param {String} s +# @param {Integer} k +# @return {Integer} +def is_vowel(c) + 'aeiou'.include?(c) +end + +def max_vowels(s, k) + max_vowel = 0 + left = 0 + vowel = 0 + + (0...s.length).each do |right| + if is_vowel(s[right]) + vowel += 1 + end + + if (right - left + 1) == k + max_vowel = [max_vowel, vowel].max + if is_vowel(s[left]) + vowel -= 1 + end + left += 1 + end + end + + max_vowel +end diff --git a/tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.rs b/tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.rs new file mode 100644 index 00000000..580cf50e --- /dev/null +++ b/tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.rs @@ -0,0 +1,29 @@ +impl Solution { + fn is_vowel(c: char) -> bool { + c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' + } + + pub fn max_vowels(s: String, k: i32) -> i32 { + let s_chars: Vec = s.chars().collect(); + let k = k as usize; + let mut max_vowel = 0; + let mut left = 0; + let mut vowel = 0; + + for right in 0..s_chars.len() { + if Self::is_vowel(s_chars[right]) { + vowel += 1; + } + + if (right - left + 1) == k { + max_vowel = max_vowel.max(vowel); + if Self::is_vowel(s_chars[left]) { + vowel -= 1; + } + left += 1; + } + } + + max_vowel + } +} diff --git a/tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.swift b/tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.swift new file mode 100644 index 00000000..56f231fe --- /dev/null +++ b/tests/1001-1500/1456. maximum-number-of-vowels-in-a-substring-of-given-length/sol.swift @@ -0,0 +1,28 @@ +class Solution { + private func isVowel(_ c: Character) -> Bool { + return c == "a" || c == "e" || c == "i" || c == "o" || c == "u" + } + + func maxVowels(_ s: String, _ k: Int) -> Int { + var maxVowel = 0 + var left = 0 + var vowel = 0 + let chars = Array(s) + + for right in 0.. 1) return false; + } + } + return true; + }; + + function dfs = [&](TreeNode* node) { + if (!node) return; + + counter[node->val]++; + + if (!node->left && !node->right) { + if (checkPalindromic()) count++; + } else { + dfs(node->left); + dfs(node->right); + } + + counter[node->val]--; + }; + + dfs(root); + return count; + } +}; diff --git a/tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.cs b/tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.cs new file mode 100644 index 00000000..5afddca6 --- /dev/null +++ b/tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.cs @@ -0,0 +1,48 @@ +/** + * 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 { + private int count = 0; + private int[] counter = new int[10]; + + public int PseudoPalindromicPaths (TreeNode root) { + DFS(root); + return count; + } + + private void DFS(TreeNode node) { + if (node == null) return; + + counter[node.val]++; + + if (node.left == null && node.right == null) { + if (CheckPalindromic()) count++; + } else { + DFS(node.left); + DFS(node.right); + } + + counter[node.val]--; + } + + private bool CheckPalindromic() { + int odd = 0; + for (int i = 1; i <= 9; i++) { + if (counter[i] % 2 == 1) { + odd++; + if (odd > 1) return false; + } + } + return true; + } +} diff --git a/tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.dart b/tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.dart new file mode 100644 index 00000000..e78bc88a --- /dev/null +++ b/tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.dart @@ -0,0 +1,44 @@ +/** + * 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 count = 0; + List counter = List.filled(10, 0); + + int pseudoPalindromicPaths (TreeNode? root) { + dfs(root); + return count; + } + + void dfs(TreeNode? node) { + if (node == null) return; + + counter[node.val]++; + + if (node.left == null && node.right == null) { + if (checkPalindromic()) count++; + } else { + dfs(node.left); + dfs(node.right); + } + + counter[node.val]--; + } + + bool checkPalindromic() { + int odd = 0; + for (int i = 1; i <= 9; i++) { + if (counter[i] % 2 == 1) { + odd++; + if (odd > 1) return false; + } + } + return true; + } +} diff --git a/tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.go b/tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.go new file mode 100644 index 00000000..55a3918f --- /dev/null +++ b/tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.go @@ -0,0 +1,49 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func pseudoPalindromicPaths (root *TreeNode) int { + count := 0 + counter := [10]int{} + + var checkPalindromic func() bool + checkPalindromic = func() bool { + odd := 0 + for i := 1; i <= 9; i++ { + if counter[i] % 2 == 1 { + odd++ + if odd > 1 { + return false + } + } + } + return true + } + + var dfs func(*TreeNode) + dfs = func(node *TreeNode) { + if node == nil { + return + } + + counter[node.Val]++ + + if node.Left == nil && node.Right == nil { + if checkPalindromic() { + count++ + } + } else { + dfs(node.Left) + dfs(node.Right) + } + + counter[node.Val]-- + } + + dfs(root) + return count +} diff --git a/tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.java b/tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.java new file mode 100644 index 00000000..f3ecae31 --- /dev/null +++ b/tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.java @@ -0,0 +1,50 @@ +/** + * 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 { + private int[] counter = new int[10]; + private int count = 0; + + public int pseudoPalindromicPaths (TreeNode root) { + dfs(root); + return count; + } + + private void dfs(TreeNode node) { + if (node == null) return; + + counter[node.val]++; + + if (node.left == null && node.right == null) { + if (checkPalindromic()) count++; + } else { + dfs(node.left); + dfs(node.right); + } + + counter[node.val]--; + } + + private boolean checkPalindromic() { + int odd = 0; + for (int i = 1; i <= 9; i++) { + if (counter[i] % 2 == 1) { + odd++; + if (odd > 1) return false; + } + } + return true; + } +} diff --git a/tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.kt b/tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.kt new file mode 100644 index 00000000..905705ab --- /dev/null +++ b/tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.kt @@ -0,0 +1,45 @@ +/** + * 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 { + private var count = 0 + private val counter = IntArray(10) + + fun pseudoPalindromicPaths (root: TreeNode?): Int { + dfs(root) + return count + } + + private fun dfs(node: TreeNode?) { + if (node == null) return + + counter[node.`val`]++ + + if (node.left == null && node.right == null) { + if (checkPalindromic()) count++ + } else { + dfs(node.left) + dfs(node.right) + } + + counter[node.`val`]-- + } + + private fun checkPalindromic(): Boolean { + var odd = 0 + for (i in 1..9) { + if (counter[i] % 2 == 1) { + odd++ + if (odd > 1) return false + } + } + return true + } +} diff --git a/tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.py b/tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.py new file mode 100644 index 00000000..e838133b --- /dev/null +++ b/tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.py @@ -0,0 +1,39 @@ +# 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 pseudoPalindromicPaths(self, root: Optional[TreeNode]) -> int: + def check_palindromic(num): + odd = 0 + for i in range(1, 10): + if counter[i] % 2 == 1: + odd += 1 + if odd > 1: + return False + return True + + def dfs(root, counter): + nonlocal count + if not root: + return + + counter[root.val] += 1 + + if not root.left and not root.right: + if check_palindromic(counter): + count += 1 + + else: + dfs(root.left, counter) + dfs(root.right, counter) + + counter[root.val] -= 1 + + count = 0 + counter = [0] * 10 + dfs(root, counter) + + return count diff --git a/tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.py2 b/tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.py2 new file mode 100644 index 00000000..e30e59c6 --- /dev/null +++ b/tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.py2 @@ -0,0 +1,40 @@ +# 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 pseudoPalindromicPaths (self, root): + """ + :type root: Optional[TreeNode] + :rtype: int + """ + def check_palindromic(): + odd = 0 + for i in range(1, 10): + if counter[i] % 2 == 1: + odd += 1 + if odd > 1: + return False + return True + + def dfs(node): + if not node: + return + + counter[node.val] += 1 + + if not node.left and not node.right: + if check_palindromic(): + count[0] += 1 + else: + dfs(node.left) + dfs(node.right) + + counter[node.val] -= 1 + + count = [0] + counter = [0] * 10 + dfs(root) + return count[0] diff --git a/tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.rb b/tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.rb new file mode 100644 index 00000000..a23da8af --- /dev/null +++ b/tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.rb @@ -0,0 +1,43 @@ +# 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 {Integer} +def pseudo_palindromic_paths (root) + def check_palindromic(counter) + odd = 0 + (1..9).each do |i| + if counter[i] % 2 == 1 + odd += 1 + return false if odd > 1 + end + end + true + end + + def dfs(node, counter, count) + return if node.nil? + + counter[node.val] += 1 + + if node.left.nil? && node.right.nil? + count[0] += 1 if check_palindromic(counter) + else + dfs(node.left, counter, count) + dfs(node.right, counter, count) + end + + counter[node.val] -= 1 + end + + count = [0] + counter = [0] * 10 + dfs(root, counter, count) + count[0] +end diff --git a/tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.rs b/tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.rs new file mode 100644 index 00000000..900f8b77 --- /dev/null +++ b/tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.rs @@ -0,0 +1,58 @@ +// 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 pseudo_palindromic_paths (root: Option>>) -> i32 { + let mut count = 0; + let mut counter = [0; 10]; + + fn check_palindromic(counter: &[i32; 10]) -> bool { + let mut odd = 0; + for i in 1..=9 { + if counter[i] % 2 == 1 { + odd += 1; + if odd > 1 { + return false; + } + } + } + true + } + + fn dfs(node: Option>>, counter: &mut [i32; 10], count: &mut i32) { + if let Some(node) = node { + let node = node.borrow(); + counter[node.val as usize] += 1; + + if node.left.is_none() && node.right.is_none() { + if check_palindromic(counter) { + *count += 1; + } + } else { + dfs(node.left.clone(), counter, count); + dfs(node.right.clone(), counter, count); + } + + counter[node.val as usize] -= 1; + } + } + + dfs(root, &mut counter, &mut count); + count + } +} diff --git a/tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.swift b/tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.swift new file mode 100644 index 00000000..d4ed8949 --- /dev/null +++ b/tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.swift @@ -0,0 +1,54 @@ +/** + * 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 { + var count = 0 + var counter = [Int](repeating: 0, count: 10) + + func pseudoPalindromicPaths (_ root: TreeNode?) -> Int { + dfs(root) + return count + } + + func dfs(_ node: TreeNode?) { + guard let node = node else { return } + + counter[node.val] += 1 + + if node.left == nil && node.right == nil { + if checkPalindromic() { + count += 1 + } + } else { + dfs(node.left) + dfs(node.right) + } + + counter[node.val] -= 1 + } + + func checkPalindromic() -> Bool { + var odd = 0 + for i in 1...9 { + if counter[i] % 2 == 1 { + odd += 1 + if odd > 1 { + return false + } + } + } + return true + } +} diff --git a/tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.ts b/tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.ts new file mode 100644 index 00000000..e3ad1d23 --- /dev/null +++ b/tests/1001-1500/1457. pseudo-palindromic-paths-in-a-binary-tree/sol.ts @@ -0,0 +1,47 @@ +/** + * 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 pseudoPalindromicPaths(root: TreeNode | null): number { + let count = 0; + const counter = new Array(10).fill(0); + + function checkPalindromic(): boolean { + let odd = 0; + for (let i = 1; i <= 9; i++) { + if (counter[i] % 2 === 1) { + odd++; + if (odd > 1) return false; + } + } + return true; + } + + function dfs(node: TreeNode | null): void { + if (node === null) return; + + counter[node.val]++; + + if (node.left === null && node.right === null) { + if (checkPalindromic()) count++; + } else { + dfs(node.left); + dfs(node.right); + } + + counter[node.val]--; + } + + dfs(root); + return count; +} diff --git a/tests/1001-1500/1458. max-dot-product-of-two-subsequences/manifest.yaml b/tests/1001-1500/1458. max-dot-product-of-two-subsequences/manifest.yaml new file mode 100644 index 00000000..f1d990b6 --- /dev/null +++ b/tests/1001-1500/1458. max-dot-product-of-two-subsequences/manifest.yaml @@ -0,0 +1,367 @@ +entry: + id: 1458 + title: "max-dot-product-of-two-subsequences" + params: + nums1: + type: array + items: + type: int + nums2: + type: array + items: + type: int + call: + cpp: "Solution().maxDotProduct({nums1}, {nums2})" + rust: "Solution::max_dot_product({nums1}, {nums2})" + python3: "Solution().maxDotProduct({nums1}, {nums2})" + python2: "Solution().maxDotProduct({nums1}, {nums2})" + ruby: "max_dot_product({nums1}, {nums2})" + java: "new Solution().maxDotProduct({nums1}, {nums2})" + csharp: "new Solution().MaxDotProduct({nums1}, {nums2})" + kotlin: "Solution().maxDotProduct({nums1}, {nums2})" + go: "maxDotProduct({nums1}, {nums2})" + dart: "Solution().maxDotProduct({nums1}, {nums2})" + swift: "Solution().maxDotProduct({nums1}, {nums2})" + typescript: "maxDotProduct({nums1}, {nums2})" +judge: + type: "exact" +limits: + time_ms: 900 + memory_mb: 256 +oracle: + python3: + call: "Checker().maxDotProduct(nums1, nums2, {result})" + checker: | + class Checker: + def maxDotProduct(self, nums1, nums2, result): + n = len(nums1) + m = len(nums2) + neg = -10 ** 18 + dp = [[neg] * (m + 1) for _ in range(n + 1)] + for i in range(n - 1, -1, -1): + for j in range(m - 1, -1, -1): + product = nums1[i] * nums2[j] + dp[i][j] = max(product, product + dp[i + 1][j + 1], dp[i + 1][j], dp[i][j + 1]) + return result == dp[0][0] +seed: 1458 +tests: + - name: "official-one" + in: + nums1: [2, 1, -2, 5] + nums2: [3, 0, -6] + out: 18 + - name: "official-two" + in: + nums1: [3, -2] + nums2: [2, -6, 7] + out: 21 + - name: "official-three" + in: + nums1: [-1, -1] + nums2: [1, 1] + out: -1 + - name: "single-positive" + in: + nums1: [5] + nums2: [4] + out: 20 + - name: "single-negative" + in: + nums1: [-5] + nums2: [4] + out: -20 + - name: "single-both-negative" + in: + nums1: [-5] + nums2: [-4] + out: 20 + - name: "zero-only" + in: + nums1: [0, 0] + nums2: [0, 0, 0] + out: 0 + - name: "positive-aligned" + in: + nums1: [1, 2, 3] + nums2: [4, 5, 6] + out: 32 + - name: "negative-aligned" + in: + nums1: [-1, -2, -3] + nums2: [-4, -5, -6] + out: 32 + - name: "mixed-signs" + in: + nums1: [-2, 4, -3, 5] + nums2: [3, -1, 6] + out: 45 + - name: "all-negative-first" + in: + nums1: [-1, -2, -3] + nums2: [2, 4, 1] + out: -1 + - name: "all-negative-second" + in: + nums1: [1, 2, 3] + nums2: [-2, -4, -1] + out: -1 + - name: "need-skip-first" + in: + nums1: [1, 10] + nums2: [1, 1] + out: 11 + - name: "need-skip-second" + in: + nums1: [1, 1] + nums2: [1, 10] + out: 11 + - name: "matching-subsequence" + in: + nums1: [5, -10, 5] + nums2: [5, 5, -10] + out: 125 + - name: "alternating-values" + in: + nums1: [7, -7, 7, -7] + nums2: [-3, 3, -3, 3] + out: 63 + - name: "longer-first" + in: + nums1: [1, 2, 3, 4, 5] + nums2: [5, 4] + out: 40 + - name: "longer-second" + in: + nums1: [5, 4] + nums2: [1, 2, 3, 4, 5] + out: 40 + - name: "large-positive" + in: + nums1: [1000, 999] + nums2: [1000, 999] + out: 1998001 + - name: "large-negative-pair" + in: + nums1: [-1000, -999] + nums2: [-1000, -999] + out: 1998001 + - name: "large-opposite-sign" + in: + nums1: [-1000, 1000] + nums2: [1000, -1000] + out: 1000000 + - name: "zeros-between" + in: + nums1: [0, 8, 0, -2] + nums2: [5, 0, 4, -3] + out: 46 + - name: "repeated-positive" + in: + nums1: [3, 3, 3, 3] + nums2: [2, 2, 2] + out: 18 + - name: "repeated-negative" + in: + nums1: [-3, -3, -3] + nums2: [-2, -2, -2, -2] + out: 18 + - name: "alternating-zero" + in: + nums1: [0, 1, 0, 1, 0] + nums2: [1, 0, 1, 0] + out: 2 + - name: "best-late-pair" + in: + nums1: [-100, -100, 9] + nums2: [1, 1, 10] + out: 90 + - name: "best-early-pair" + in: + nums1: [9, -100, -100] + nums2: [10, 1, 1] + out: 90 + - name: "crossing-order" + in: + nums1: [8, 1, 7] + nums2: [1, 9, 2] + out: 86 + - name: "four-by-four" + in: + nums1: [2, -1, 4, -3] + nums2: [-2, 5, -4, 3] + out: 34 + - name: "five-by-three" + in: + nums1: [6, -2, 1, 8, -5] + nums2: [3, -7, 4] + out: 64 + - name: "three-by-five" + in: + nums1: [-6, 2, 9] + nums2: [4, -8, 1, 7, -3] + out: 113 + - name: "boundary-minus-one" + in: + nums1: [-1000, -1] + nums2: [1, -1000] + out: 1000000 + - name: "boundary-plus-one" + in: + nums1: [1000, 1] + nums2: [1, 1000] + out: 1000000 + - name: "sign-switching" + in: + nums1: [4, -5, 6, -7] + nums2: [-8, 9, -10, 11] + out: 164 + - name: "stress-balanced" + in: + nums1: + gen: "array" + len: + gen: "int" + min: 450 + max: 500 + of: + gen: "int" + min: -1000 + max: 1000 + distinct: false + sorted: false + elemType: "int" + nums2: + gen: "array" + len: + gen: "int" + min: 450 + max: 500 + of: + gen: "int" + min: -1000 + max: 1000 + distinct: false + sorted: false + elemType: "int" + seed: 145801 + - name: "stress-positive-heavy" + in: + nums1: + gen: "array" + len: 500 + of: + gen: "int" + min: 0 + max: 1000 + distinct: false + sorted: false + elemType: "int" + nums2: + gen: "array" + len: 500 + of: + gen: "int" + min: 0 + max: 1000 + distinct: false + sorted: false + elemType: "int" + seed: 145802 + - name: "stress-negative-heavy" + in: + nums1: + gen: "array" + len: 500 + of: + gen: "int" + min: -1000 + max: 0 + distinct: false + sorted: false + elemType: "int" + nums2: + gen: "array" + len: 500 + of: + gen: "int" + min: -1000 + max: 0 + distinct: false + sorted: false + elemType: "int" + seed: 145803 + - name: "stress-zero-mixed" + in: + nums1: + gen: "array" + len: + gen: "int" + min: 490 + max: 500 + of: + gen: "int" + min: -10 + max: 10 + distinct: false + sorted: false + elemType: "int" + nums2: + gen: "array" + len: + gen: "int" + min: 490 + max: 500 + of: + gen: "int" + min: -10 + max: 10 + distinct: false + sorted: false + elemType: "int" + seed: 145804 + - name: "stress-asymmetric" + in: + nums1: + gen: "array" + len: 500 + of: + gen: "int" + min: -1000 + max: 1000 + distinct: false + sorted: false + elemType: "int" + nums2: + gen: "array" + len: 450 + of: + gen: "int" + min: -1000 + max: 1000 + distinct: false + sorted: false + elemType: "int" + seed: 145805 + - name: "stress-shorter-first" + in: + nums1: + gen: "array" + len: 450 + of: + gen: "int" + min: -1000 + max: 1000 + distinct: false + sorted: false + elemType: "int" + nums2: + gen: "array" + len: 500 + of: + gen: "int" + min: -1000 + max: 1000 + distinct: false + sorted: false + elemType: "int" + seed: 145806 diff --git a/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.cpp b/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.cpp new file mode 100644 index 00000000..cad238eb --- /dev/null +++ b/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + int maxDotProduct(vector& nums1, vector& nums2) { + int n = nums1.size(), m = nums2.size(); + vector> memo(n, vector(m, INT_MIN)); + + function dp = [&](int i, int j) -> int { + if (i == n || j == m) { + return INT_MIN; + } + if (memo[i][j] != INT_MIN) { + return memo[i][j]; + } + + int take = nums1[i] * nums2[j]; + int res = take; + int takeAndContinue = dp(i + 1, j + 1); + if (takeAndContinue != INT_MIN) { + res = max(res, take + takeAndContinue); + } + res = max(res, dp(i + 1, j)); + res = max(res, dp(i, j + 1)); + + memo[i][j] = res; + return res; + }; + + return dp(0, 0); + } +}; diff --git a/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.cs b/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.cs new file mode 100644 index 00000000..5f68b3cc --- /dev/null +++ b/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.cs @@ -0,0 +1,34 @@ +public class Solution { + public int MaxDotProduct(int[] nums1, int[] nums2) { + int n = nums1.Length, m = nums2.Length; + int[,] memo = new int[n, m]; + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + memo[i, j] = int.MinValue; + } + } + + int Dp(int i, int j) { + if (i == n || j == m) { + return int.MinValue; + } + if (memo[i, j] != int.MinValue) { + return memo[i, j]; + } + + int take = nums1[i] * nums2[j]; + int res = take; + int takeAndContinue = Dp(i + 1, j + 1); + if (takeAndContinue != int.MinValue) { + res = Math.Max(res, take + takeAndContinue); + } + res = Math.Max(res, Dp(i + 1, j)); + res = Math.Max(res, Dp(i, j + 1)); + + memo[i, j] = res; + return res; + } + + return Dp(0, 0); + } +} diff --git a/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.dart b/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.dart new file mode 100644 index 00000000..b3c51998 --- /dev/null +++ b/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.dart @@ -0,0 +1,33 @@ +class Solution { + int maxDotProduct(List nums1, List nums2) { + List> memo = List.generate( + nums1.length + 1, + (_) => List.filled(nums2.length + 1, -2147483648), + ); + + int dp(int i, int j) { + if (i == nums1.length || j == nums2.length) { + return -2147483648; + } + if (memo[i][j] != -2147483648) { + return memo[i][j]; + } + + int take = nums1[i] * nums2[j]; + int res = take; + int takeAndContinue = dp(i + 1, j + 1); + if (takeAndContinue != -2147483648) { + res = max(res, take + takeAndContinue); + } + res = max(res, dp(i + 1, j)); + res = max(res, dp(i, j + 1)); + + memo[i][j] = res; + return res; + } + + return dp(0, 0); + } + + int max(int a, int b) => a > b ? a : b; +} diff --git a/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.go b/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.go new file mode 100644 index 00000000..870161a8 --- /dev/null +++ b/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.go @@ -0,0 +1,40 @@ +func maxDotProduct(nums1 []int, nums2 []int) int { + memo := make([][]int, len(nums1)) + for i := range memo { + memo[i] = make([]int, len(nums2)) + for j := range memo[i] { + memo[i][j] = math.MinInt32 + } + } + + var dp func(i, j int) int + dp = func(i, j int) int { + if i == len(nums1) || j == len(nums2) { + return math.MinInt32 + } + if memo[i][j] != math.MinInt32 { + return memo[i][j] + } + + take := nums1[i] * nums2[j] + res := take + takeAndContinue := dp(i+1, j+1) + if takeAndContinue != math.MinInt32 { + res = max(res, take + takeAndContinue) + } + res = max(res, dp(i+1, j)) + res = max(res, dp(i, j+1)) + + memo[i][j] = res + return res + } + + return dp(0, 0) +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} diff --git a/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.java b/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.java new file mode 100644 index 00000000..e818086b --- /dev/null +++ b/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.java @@ -0,0 +1,39 @@ +class Solution { + private int[][] memo; + private int[] nums1; + private int[] nums2; + + public int maxDotProduct(int[] nums1, int[] nums2) { + this.nums1 = nums1; + this.nums2 = nums2; + memo = new int[nums1.length][nums2.length]; + for (int i = 0; i < nums1.length; i++) { + java.util.Arrays.fill(memo[i], Integer.MIN_VALUE); + } + return dp(0, 0); + } + + private int dp(int i, int j) { + if (i == nums1.length || j == nums2.length) { + return Integer.MIN_VALUE; + } + if (memo[i][j] != Integer.MIN_VALUE) { + return memo[i][j]; + } + + int take = nums1[i] * nums2[j]; + int takeAndContinue = dp(i+1, j+1); + int res; + if (takeAndContinue == Integer.MIN_VALUE) { + res = take; + } else { + res = take + takeAndContinue; + } + res = Math.max(res, take); + res = Math.max(res, dp(i+1, j)); + res = Math.max(res, dp(i, j+1)); + + memo[i][j] = res; + return res; + } +} diff --git a/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.kt b/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.kt new file mode 100644 index 00000000..30524565 --- /dev/null +++ b/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.kt @@ -0,0 +1,33 @@ +class Solution { + private lateinit var memo: Array + private lateinit var nums1: IntArray + private lateinit var nums2: IntArray + + fun maxDotProduct(nums1: IntArray, nums2: IntArray): Int { + this.nums1 = nums1 + this.nums2 = nums2 + memo = Array(nums1.size) { IntArray(nums2.size) { Int.MIN_VALUE } } + return dp(0, 0) + } + + private fun dp(i: Int, j: Int): Int { + if (i == nums1.size || j == nums2.size) { + return Int.MIN_VALUE + } + if (memo[i][j] != Int.MIN_VALUE) { + return memo[i][j] + } + + val take = nums1[i] * nums2[j] + var res = take + val takeAndContinue = dp(i+1, j+1) + if (takeAndContinue != Int.MIN_VALUE) { + res = maxOf(res, take + takeAndContinue) + } + res = maxOf(res, dp(i+1, j)) + res = maxOf(res, dp(i, j+1)) + + memo[i][j] = res + return res + } +} diff --git a/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.py b/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.py new file mode 100644 index 00000000..f7ff8252 --- /dev/null +++ b/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.py @@ -0,0 +1,33 @@ +class Solution: + def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int: + + memo = {} + + # max dot product of two subsequences starting at i,j + def dp(i, j): + + if i == len(nums1) or j == len(nums2): + return float( + "-inf" + ) # if we are passed the boundary, dont pick anything from there. + + if (i, j) in memo: + return memo[(i, j)] + + take = nums1[i] * nums2[j] + res = max( + # take i,j. move forward + take + dp(i + 1, j + 1), + # take this subsequence and just end. + take, + # skip i: i+1,j + dp(i + 1, j), + # skip j: i,j+1 + dp(i, j + 1), + ) + + memo[(i, j)] = res + + return memo[(i, j)] + + return dp(0, 0) diff --git a/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.py2 b/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.py2 new file mode 100644 index 00000000..1e65d8f4 --- /dev/null +++ b/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.py2 @@ -0,0 +1,26 @@ +class Solution(object): + def maxDotProduct(self, nums1, nums2): + """ + :type nums1: List[int] + :type nums2: List[int] + :rtype: int + """ + memo = {} + + def dp(i, j): + if i == len(nums1) or j == len(nums2): + return float("-inf") + if (i, j) in memo: + return memo[(i, j)] + + take = nums1[i] * nums2[j] + res = max( + take + dp(i+1, j+1), + take, + dp(i+1, j), + dp(i, j+1), + ) + memo[(i, j)] = res + return memo[(i, j)] + + return dp(0, 0) diff --git a/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.rb b/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.rb new file mode 100644 index 00000000..d45c8d4f --- /dev/null +++ b/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.rb @@ -0,0 +1,24 @@ +# @param {Integer[]} nums1 +# @param {Integer[]} nums2 +# @return {Integer} +def max_dot_product(nums1, nums2) + negative_infinity = -Float::INFINITY + dp = Array.new(nums2.length + 1, negative_infinity) + + nums1.each do |value1| + previous_diagonal = negative_infinity + 1.upto(nums2.length) do |j| + previous_row = dp[j] + product = value1 * nums2[j - 1] + left = dp[j - 1] + + best = product + best = [best, previous_diagonal + product].max unless previous_diagonal == negative_infinity + best = [best, previous_row, left].max + dp[j] = best + previous_diagonal = previous_row + end + end + + dp[nums2.length] +end diff --git a/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.rs b/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.rs new file mode 100644 index 00000000..91c8535d --- /dev/null +++ b/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.rs @@ -0,0 +1,35 @@ +impl Solution { + pub fn max_dot_product(nums1: Vec, nums2: Vec) -> i32 { + use std::collections::HashMap; + + fn dp( + i: usize, + j: usize, + nums1: &Vec, + nums2: &Vec, + memo: &mut HashMap<(usize, usize), i32>, + ) -> i32 { + if i == nums1.len() || j == nums2.len() { + return i32::MIN; + } + if let Some(&val) = memo.get(&(i, j)) { + return val; + } + + let take = nums1[i] * nums2[j]; + let mut res = take; + let take_and_continue = dp(i + 1, j + 1, nums1, nums2, memo); + if take_and_continue != i32::MIN { + res = res.max(take + take_and_continue); + } + res = res.max(dp(i + 1, j, nums1, nums2, memo)); + res = res.max(dp(i, j + 1, nums1, nums2, memo)); + + memo.insert((i, j), res); + res + } + + let mut memo = HashMap::new(); + dp(0, 0, &nums1, &nums2, &mut memo) + } +} diff --git a/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.swift b/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.swift new file mode 100644 index 00000000..c04690f4 --- /dev/null +++ b/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.swift @@ -0,0 +1,28 @@ +class Solution { + func maxDotProduct(_ nums1: [Int], _ nums2: [Int]) -> Int { + var memo = Array(repeating: Array(repeating: Int.min, count: nums2.count), count: nums1.count) + + func dp(_ i: Int, _ j: Int) -> Int { + if i == nums1.count || j == nums2.count { + return Int.min + } + if memo[i][j] != Int.min { + return memo[i][j] + } + + let take = nums1[i] * nums2[j] + var res = take + let takeAndContinue = dp(i+1, j+1) + if takeAndContinue != Int.min { + res = max(res, take + takeAndContinue) + } + res = max(res, dp(i+1, j)) + res = max(res, dp(i, j+1)) + + memo[i][j] = res + return res + } + + return dp(0, 0) + } +} diff --git a/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.ts b/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.ts new file mode 100644 index 00000000..efadbc45 --- /dev/null +++ b/tests/1001-1500/1458. max-dot-product-of-two-subsequences/sol.ts @@ -0,0 +1,28 @@ +function maxDotProduct(nums1: number[], nums2: number[]): number { + const memo: number[][] = Array.from({ length: nums1.length }, () => + Array(nums2.length).fill(-Infinity), + ); + + function dp(i: number, j: number): number { + if (i === nums1.length || j === nums2.length) { + return -Infinity; + } + if (memo[i][j] !== -Infinity) { + return memo[i][j]; + } + + const take = nums1[i] * nums2[j]; + let res = take; + const takeAndContinue = dp(i + 1, j + 1); + if (takeAndContinue !== -Infinity) { + res = Math.max(res, take + takeAndContinue); + } + res = Math.max(res, dp(i + 1, j)); + res = Math.max(res, dp(i, j + 1)); + + memo[i][j] = res; + return res; + } + + return dp(0, 0); +} diff --git a/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/manifest.yaml b/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/manifest.yaml new file mode 100644 index 00000000..324ff8d1 --- /dev/null +++ b/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/manifest.yaml @@ -0,0 +1,295 @@ +entry: + id: 1460 + title: "make-two-arrays-equal-by-reversing-subarrays" + params: + target: + type: array + items: + type: int + arr: + type: array + items: + type: int + call: + cpp: "Solution().canBeEqual({target}, {arr})" + rust: "Solution::can_be_equal({target}, {arr})" + python3: "Solution().canBeEqual({target}, {arr})" + python2: "Solution().canBeEqual({target}, {arr})" + ruby: "can_be_equal({target}, {arr})" + java: "new Solution().canBeEqual({target}, {arr})" + csharp: "new Solution().CanBeEqual({target}, {arr})" + kotlin: "Solution().canBeEqual({target}, {arr})" + go: "canBeEqual({target}, {arr})" + dart: "Solution().canBeEqual({target}, {arr})" + swift: "Solution().canBeEqual({target}, {arr})" + typescript: "canBeEqual({target}, {arr})" +judge: + type: exact +limits: + time_ms: 300 + memory_mb: 300 +oracle: + python3: + call: "Checker().canBeEqual(target, arr, {result})" + checker: | + from collections import Counter + class Checker: + def canBeEqual(self, target, arr, result): + return isinstance(result, bool) and result == (Counter(target) == Counter(arr)) +seed: 1460 +tests: + - name: ex1 + in: + target: [1, 2, 3, 4] + arr: [2, 4, 1, 3] + out: true + - name: ex2 + in: + target: [7] + arr: [7] + out: true + - name: ex3 + in: + target: [3, 7, 9] + arr: [3, 7, 11] + out: false + - name: equal_pair + in: + target: [1, 2] + arr: [1, 2] + out: true + - name: reverse_pair + in: + target: [1, 2] + arr: [2, 1] + out: true + - name: all_equal + in: + target: [5, 5, 5, 5] + arr: [5, 5, 5, 5] + out: true + - name: duplicate_match + in: + target: [1, 1, 2, 2] + arr: [2, 1, 2, 1] + out: true + - name: duplicate_mismatch + in: + target: [1, 1, 2, 2] + arr: [1, 2, 2, 2] + out: false + - name: ascending_reverse + in: + target: [1, 2, 3, 4, 5] + arr: [5, 4, 3, 2, 1] + out: true + - name: descending_target + in: + target: [5, 4, 3, 2, 1] + arr: [1, 3, 5, 2, 4] + out: true + - name: mismatch_single_value + in: + target: [1, 2, 3] + arr: [1, 2, 4] + out: false + - name: high_values + in: + target: [1000, 999, 998] + arr: [998, 1000, 999] + out: true + - name: low_values + in: + target: [1, 1, 1] + arr: [1, 1, 2] + out: false + - name: mixed_a + in: + target: [10, 20, 30, 40] + arr: [40, 10, 30, 20] + out: true + - name: mixed_b + in: + target: [7, 8, 9, 10, 11] + arr: [11, 9, 7, 10, 8] + out: true + - name: mixed_c + in: + target: [2, 4, 6, 8, 10] + arr: [2, 4, 6, 8, 11] + out: false + - name: mixed_d + in: + target: [3, 3, 4, 5, 5] + arr: [5, 4, 3, 5, 3] + out: true + - name: mixed_e + in: + target: [12, 1, 12, 2, 3] + arr: [3, 12, 2, 1, 12] + out: true + - name: length_six + in: + target: [1, 2, 3, 4, 5, 6] + arr: [6, 5, 4, 3, 2, 1] + out: true + - name: length_seven + in: + target: [1, 2, 2, 3, 3, 4, 5] + arr: [3, 5, 2, 1, 4, 3, 2] + out: true + - name: length_eight + in: + target: [8, 7, 6, 5, 4, 3, 2, 1] + arr: [1, 2, 3, 4, 5, 6, 7, 8] + out: true + - name: length_nine + in: + target: [1, 3, 5, 7, 9, 2, 4, 6, 8] + arr: [9, 8, 7, 6, 5, 4, 3, 2, 1] + out: true + - name: length_ten + in: + target: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] + arr: [100, 90, 80, 70, 60, 50, 40, 30, 20, 10] + out: true + - name: repeated_a + in: + target: [1, 2, 1, 2, 1, 2] + arr: [2, 1, 2, 1, 2, 1] + out: true + - name: repeated_b + in: + target: [4, 4, 4, 5, 5, 6] + arr: [5, 4, 6, 4, 5, 4] + out: true + - name: repeated_c + in: + target: [9, 9, 8, 8, 7, 7] + arr: [7, 8, 9, 7, 8, 9] + out: true + - name: mismatch_a + in: + target: [1, 2, 3, 4, 5] + arr: [1, 2, 3, 4, 4] + out: false + - name: mismatch_b + in: + target: [6, 6, 7, 8] + arr: [6, 7, 7, 8] + out: false + - name: mismatch_c + in: + target: [100, 200, 300] + arr: [100, 200, 301] + out: false + - name: boundary_a + in: + target: [1000, 1, 500, 250] + arr: [250, 500, 1, 1000] + out: true + - name: boundary_b + in: + target: [1000, 1000, 999] + arr: [1000, 999, 998] + out: false + - name: patterned_a + in: + target: [2, 4, 6, 8, 10, 12] + arr: [12, 10, 8, 6, 4, 2] + out: true + - name: patterned_b + in: + target: [11, 22, 33, 44, 55] + arr: [33, 55, 11, 44, 22] + out: true + - name: patterned_c + in: + target: [13, 13, 14, 15, 15] + arr: [15, 14, 13, 15, 13] + out: true + - name: final_case + in: + target: [17, 3, 29, 11, 5, 23] + arr: [23, 5, 11, 29, 3, 17] + out: true + - name: stress_all_one_thousand + in: + target: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 1 + arr: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 1 + - name: stress_all_max_value + in: + target: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1000 + max: 1000 + arr: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1000 + max: 1000 + - name: stress_distinct_low_value_mismatch + in: + target: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 1 + arr: + gen: "array" + len: 1000 + of: + gen: "int" + min: 2 + max: 2 + - name: stress_boundary_mismatch + in: + target: + gen: "array" + len: 1000 + of: + gen: "int" + min: 999 + max: 999 + arr: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1000 + max: 1000 + - name: stress_mid_value_mismatch + in: + target: + gen: "array" + len: 1000 + of: + gen: "int" + min: 500 + max: 500 + arr: + gen: "array" + len: 1000 + of: + gen: "int" + min: 501 + max: 501 diff --git a/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.cpp b/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.cpp new file mode 100644 index 00000000..0d065419 --- /dev/null +++ b/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + bool canBeEqual(vector& target, vector& arr) { + vector counts(1001, 0); + + for (int i = 0; i < target.size(); i++) { + counts[target[i]]++; + counts[arr[i]]--; + } + + for (int c : counts) { + if (c != 0) return false; + } + return true; + } +}; diff --git a/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.cs b/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.cs new file mode 100644 index 00000000..22a8bdcd --- /dev/null +++ b/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.cs @@ -0,0 +1,15 @@ +public class Solution { + public bool CanBeEqual(int[] target, int[] arr) { + int[] counts = new int[1001]; + + for (int i = 0; i < target.Length; i++) { + counts[target[i]]++; + counts[arr[i]]--; + } + + foreach (int c in counts) { + if (c != 0) return false; + } + return true; + } +} diff --git a/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.dart b/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.dart new file mode 100644 index 00000000..3f45850b --- /dev/null +++ b/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.dart @@ -0,0 +1,12 @@ +class Solution { + bool canBeEqual(List target, List arr) { + List counts = List.filled(1001, 0); + + for (int i = 0; i < target.length; i++) { + counts[target[i]]++; + counts[arr[i]]--; + } + + return counts.every((c) => c == 0); + } +} diff --git a/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.go b/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.go new file mode 100644 index 00000000..3225936c --- /dev/null +++ b/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.go @@ -0,0 +1,15 @@ +func canBeEqual(target []int, arr []int) bool { + counts := make([]int, 1001) + + for i := 0; i < len(target); i++ { + counts[target[i]]++ + counts[arr[i]]-- + } + + for _, c := range counts { + if c != 0 { + return false + } + } + return true +} diff --git a/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.java b/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.java new file mode 100644 index 00000000..5d1823b8 --- /dev/null +++ b/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.java @@ -0,0 +1,15 @@ +class Solution { + public boolean canBeEqual(int[] target, int[] arr) { + int[] counts = new int[1001]; + + for (int i = 0; i < target.length; i++) { + counts[target[i]]++; + counts[arr[i]]--; + } + + for (int c : counts) { + if (c != 0) return false; + } + return true; + } +} diff --git a/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.kt b/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.kt new file mode 100644 index 00000000..4f86ed9b --- /dev/null +++ b/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.kt @@ -0,0 +1,12 @@ +class Solution { + fun canBeEqual(target: IntArray, arr: IntArray): Boolean { + val counts = IntArray(1001) + + for (i in target.indices) { + counts[target[i]]++ + counts[arr[i]]-- + } + + return counts.all { it == 0 } + } +} diff --git a/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.py b/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.py new file mode 100644 index 00000000..ce6a396b --- /dev/null +++ b/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.py @@ -0,0 +1,9 @@ +class Solution: + def canBeEqual(self, target: List[int], arr: List[int]) -> bool: + counts = [0] * 1001 + + for t, a in zip(target, arr): + counts[t] += 1 + counts[a] -= 1 + + return not any(counts) diff --git a/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.py2 b/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.py2 new file mode 100644 index 00000000..81714632 --- /dev/null +++ b/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.py2 @@ -0,0 +1,14 @@ +class Solution(object): + def canBeEqual(self, target, arr): + """ + :type target: List[int] + :type arr: List[int] + :rtype: bool + """ + counts = [0] * 1001 + + for t, a in zip(target, arr): + counts[t] += 1 + counts[a] -= 1 + + return not any(counts) diff --git a/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.rb b/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.rb new file mode 100644 index 00000000..7f247226 --- /dev/null +++ b/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.rb @@ -0,0 +1,13 @@ +# @param {Integer[]} target +# @param {Integer[]} arr +# @return {Boolean} +def can_be_equal(target, arr) + counts = Array.new(1001, 0) + + target.zip(arr).each do |t, a| + counts[t] += 1 + counts[a] -= 1 + end + + counts.all? { |c| c == 0 } +end diff --git a/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.rs b/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.rs new file mode 100644 index 00000000..40e93db8 --- /dev/null +++ b/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.rs @@ -0,0 +1,12 @@ +impl Solution { + pub fn can_be_equal(target: Vec, arr: Vec) -> bool { + let mut counts = vec![0i32; 1001]; + + for i in 0..target.len() { + counts[target[i] as usize] += 1; + counts[arr[i] as usize] -= 1; + } + + counts.iter().all(|&c| c == 0) + } +} diff --git a/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.swift b/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.swift new file mode 100644 index 00000000..d6923edf --- /dev/null +++ b/tests/1001-1500/1460. make-two-arrays-equal-by-reversing-subarrays/sol.swift @@ -0,0 +1,12 @@ +class Solution { + func canBeEqual(_ target: [Int], _ arr: [Int]) -> Bool { + var counts = [Int](repeating: 0, count: 1001) + + for i in 0.. c === 0); +} diff --git a/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/manifest.yaml b/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/manifest.yaml new file mode 100644 index 00000000..350b1d3e --- /dev/null +++ b/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/manifest.yaml @@ -0,0 +1,255 @@ +entry: + id: 1461 + title: "check-if-a-string-contains-all-binary-codes-of-size-k" + params: + s: + type: string + k: + type: int + call: + cpp: "Solution().hasAllCodes({s}, {k})" + rust: "Solution::has_all_codes({s}, {k})" + python3: "Solution().hasAllCodes({s}, {k})" + python2: "Solution().hasAllCodes({s}, {k})" + ruby: "has_all_codes({s}, {k})" + java: "new Solution().hasAllCodes({s}, {k})" + csharp: "new Solution().HasAllCodes({s}, {k})" + kotlin: "Solution().hasAllCodes({s}, {k})" + go: "hasAllCodes({s}, {k})" + dart: "Solution().hasAllCodes({s}, {k})" + swift: "Solution().hasAllCodes({s}, {k})" + typescript: "hasAllCodes({s}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().hasAllCodes(s, k, {result})" + checker: | + class Checker: + def hasAllCodes(self, s, k, result): + required = {format(value, '0{}b'.format(k)) for value in range(1 << k)} + present = {s[index:index + k] for index in range(len(s) - k + 1)} + return result == required.issubset(present) + +seed: 1461 + +tests: + - name: "example-one" + in: + s: "00110110" + k: 2 + out: true + - name: "example-two" + in: + s: "0110" + k: 1 + out: true + - name: "example-three" + in: + s: "0110" + k: 2 + out: false + - name: "single-zero-k1" + in: + s: "0" + k: 1 + out: false + - name: "single-one-k1" + in: + s: "1" + k: 1 + out: false + - name: "both-bits" + in: + s: "01" + k: 1 + out: true + - name: "repeated-zero" + in: + s: "00000" + k: 1 + out: false + - name: "repeated-one" + in: + s: "11111" + k: 1 + out: false + - name: "all-four-codes" + in: + s: "0011" + k: 2 + out: false + - name: "four-codes-cyclic" + in: + s: "00011011" + k: 2 + out: true + - name: "missing-zero-zero" + in: + s: "010101" + k: 2 + out: false + - name: "missing-one-one" + in: + s: "101010" + k: 2 + out: false + - name: "three-bit-debruijn" + in: + s: "00010111" + k: 3 + out: false + - name: "three-bit-too-short" + in: + s: "0101010" + k: 3 + out: false + - name: "three-bit-single-pattern" + in: + s: "11111111" + k: 3 + out: false + - name: "four-bit-all-codes" + in: + s: "0000100110101111" + k: 4 + out: false + - name: "four-bit-short" + in: + s: "000011110000" + k: 4 + out: false + - name: "five-bit-debruijn-like" + in: + s: "00000100011001010011101011011111" + k: 5 + out: false + - name: "five-bit-too-short" + in: + s: "010101010101010" + k: 5 + out: false + - name: "six-bit-pattern" + in: + s: "00000010000110001010001110010010100110101011101111011111" + k: 6 + out: false + - name: "six-bit-zeros" + in: + s: "000000000000000000" + k: 6 + out: false + - name: "seven-bit-alternating" + in: + s: "010101010101010101010101" + k: 7 + out: false + - name: "eight-bit-single-window" + in: + s: "01010101" + k: 8 + out: false + - name: "eight-bit-repeated" + in: + s: "111111111111111111" + k: 8 + out: false + - name: "nine-bit-random" + in: + s: "001011010110100101101001011010" + k: 9 + out: false + - name: "ten-bit-too-short" + in: + s: "0101010101010101010" + k: 10 + out: false + - name: "ten-bit-mixed" + in: + s: "000001111100000111110000011111" + k: 10 + out: false + - name: "twelve-bit-zeros-ones" + in: + s: "000000000000111111111111" + k: 12 + out: false + - name: "thirteen-bit-alternating" + in: + s: "0101010101010101010101010101" + k: 13 + out: false + - name: "fifteen-bit-pattern" + in: + s: "00110011001100110011001100110011" + k: 15 + out: false + - name: "twenty-bit-short" + in: + s: "0101010101010101010101010101010101010101" + k: 20 + out: false + - name: "boundary-length-one" + in: + s: "0" + k: 20 + out: false + - name: "large-generated-binary" + in: + s: + gen: "str" + len: 500000 + alphabet: "01" + k: 1 + - name: "large-generated-unary" + in: + s: + gen: "str" + len: 500000 + alphabet: "0" + k: 20 + - name: "two-bit-all-codes-minimal" + in: + s: "00110" + k: 2 + out: true + - name: "large-generated-random-k10" + seed: 21461 + in: + s: + gen: "str" + len: 500000 + alphabet: "01" + k: 10 + - name: "large-generated-random-k19" + seed: 31461 + in: + s: + gen: "str" + len: 500000 + alphabet: "01" + k: 19 + - name: "large-generated-alternating-k20" + seed: 41461 + in: + s: + gen: "str" + len: 500000 + alphabet: "01" + k: 20 + - name: "three-bit-debruijn-linear" + in: + s: "0001011100" + k: 3 + out: true + - name: "four-bit-debruijn-linear" + in: + s: "0000100110101111000" + k: 4 + out: true diff --git a/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.cpp b/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.cpp new file mode 100644 index 00000000..1d9da348 --- /dev/null +++ b/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + bool hasAllCodes(string s, int k) { + int req = 1 << k; + vector seen(req, false); + int mask = req - 1; + int h = 0; + + for (int i = 0; i < s.length(); i++) { + h = ((h << 1) & mask) | (s[i] & 1); + + if (i >= k - 1 && !seen[h]) { + seen[h] = true; + req--; + if (req == 0) return true; + } + } + + return false; + } +}; diff --git a/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.cs b/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.cs new file mode 100644 index 00000000..c2ad2b68 --- /dev/null +++ b/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.cs @@ -0,0 +1,20 @@ +public class Solution { + public bool HasAllCodes(string s, int k) { + int req = 1 << k; + bool[] seen = new bool[req]; + int mask = req - 1; + int h = 0; + + for (int i = 0; i < s.Length; i++) { + h = ((h << 1) & mask) | (s[i] & 1); + + if (i >= k - 1 && !seen[h]) { + seen[h] = true; + req--; + if (req == 0) return true; + } + } + + return false; + } +} diff --git a/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.dart b/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.dart new file mode 100644 index 00000000..ac08d19a --- /dev/null +++ b/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.dart @@ -0,0 +1,20 @@ +class Solution { + bool hasAllCodes(String s, int k) { + int req = 1 << k; + List seen = List.filled(req, false); + int mask = req - 1; + int h = 0; + + for (int i = 0; i < s.length; i++) { + h = ((h << 1) & mask) | (s.codeUnitAt(i) & 1); + + if (i >= k - 1 && !seen[h]) { + seen[h] = true; + req--; + if (req == 0) return true; + } + } + + return false; + } +} diff --git a/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.go b/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.go new file mode 100644 index 00000000..ef93e50a --- /dev/null +++ b/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.go @@ -0,0 +1,20 @@ +func hasAllCodes(s string, k int) bool { + req := 1 << k + seen := make([]bool, req) + mask := req - 1 + h := 0 + + for i := 0; i < len(s); i++ { + h = ((h << 1) & mask) | (int(s[i]) & 1) + + if i >= k-1 && !seen[h] { + seen[h] = true + req-- + if req == 0 { + return true + } + } + } + + return false +} diff --git a/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.java b/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.java new file mode 100644 index 00000000..65e5decf --- /dev/null +++ b/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.java @@ -0,0 +1,20 @@ +class Solution { + public boolean hasAllCodes(String s, int k) { + int req = 1 << k; + boolean[] seen = new boolean[req]; + int mask = req - 1; + int h = 0; + + for (int i = 0; i < s.length(); i++) { + h = ((h << 1) & mask) | (s.charAt(i) & 1); + + if (i >= k - 1 && !seen[h]) { + seen[h] = true; + req--; + if (req == 0) return true; + } + } + + return false; + } +} diff --git a/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.kt b/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.kt new file mode 100644 index 00000000..34b40561 --- /dev/null +++ b/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.kt @@ -0,0 +1,20 @@ +class Solution { + fun hasAllCodes(s: String, k: Int): Boolean { + var req = 1 shl k + val seen = BooleanArray(req) + val mask = req - 1 + var h = 0 + + for (i in s.indices) { + h = ((h shl 1) and mask) or (s[i].code and 1) + + if (i >= k - 1 && !seen[h]) { + seen[h] = true + req-- + if (req == 0) return true + } + } + + return false + } +} diff --git a/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.py b/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.py new file mode 100644 index 00000000..14ddb0dd --- /dev/null +++ b/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.py @@ -0,0 +1,17 @@ +class Solution: + def hasAllCodes(self, s: str, k: int) -> bool: + req = 1 << k + seen = [False] * req + mask = req - 1 + h = 0 + + for i, ch in enumerate(s): + h = ((h << 1) & mask) | (ord(ch) & 1) + + if i >= k - 1 and not seen[h]: + seen[h] = True + req -= 1 + if req == 0: + return True + + return False diff --git a/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.py2 b/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.py2 new file mode 100644 index 00000000..4d4f0fa8 --- /dev/null +++ b/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.py2 @@ -0,0 +1,22 @@ +class Solution(object): + def hasAllCodes(self, s, k): + """ + :type s: str + :type k: int + :rtype: bool + """ + req = 1 << k + seen = [False] * req + mask = req - 1 + h = 0 + + for i, ch in enumerate(s): + h = ((h << 1) & mask) | (ord(ch) & 1) + + if i >= k - 1 and not seen[h]: + seen[h] = True + req -= 1 + if req == 0: + return True + + return False diff --git a/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.rb b/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.rb new file mode 100644 index 00000000..e893c01a --- /dev/null +++ b/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.rb @@ -0,0 +1,21 @@ +# @param {String} s +# @param {Integer} k +# @return {Boolean} +def has_all_codes(s, k) + req = 1 << k + seen = Array.new(req, false) + mask = req - 1 + h = 0 + + s.each_char.with_index do |ch, i| + h = ((h << 1) & mask) | (ch.ord & 1) + + if i >= k - 1 && !seen[h] + seen[h] = true + req -= 1 + return true if req == 0 + end + end + + false +end diff --git a/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.rs b/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.rs new file mode 100644 index 00000000..e0b5ad4c --- /dev/null +++ b/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.rs @@ -0,0 +1,24 @@ +impl Solution { + pub fn has_all_codes(s: String, k: i32) -> bool { + let k = k as usize; + let req = 1 << k; + let mut seen = vec![false; req]; + let mask = req - 1; + let mut h = 0; + let mut remaining = req; + + for (i, ch) in s.chars().enumerate() { + h = ((h << 1) & mask) | ((ch as usize) & 1); + + if i >= k - 1 && !seen[h] { + seen[h] = true; + remaining -= 1; + if remaining == 0 { + return true; + } + } + } + + false + } +} diff --git a/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.swift b/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.swift new file mode 100644 index 00000000..210f6e05 --- /dev/null +++ b/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.swift @@ -0,0 +1,22 @@ +class Solution { + func hasAllCodes(_ s: String, _ k: Int) -> Bool { + let req = 1 << k + var seen = [Bool](repeating: false, count: req) + let mask = req - 1 + var h = 0 + var remaining = req + let chars = Array(s) + + for i in 0..= k - 1 && !seen[h] { + seen[h] = true + remaining -= 1 + if remaining == 0 { return true } + } + } + + return false + } +} diff --git a/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.ts b/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.ts new file mode 100644 index 00000000..4658b983 --- /dev/null +++ b/tests/1001-1500/1461. check-if-a-string-contains-all-binary-codes-of-size-k/sol.ts @@ -0,0 +1,18 @@ +function hasAllCodes(s: string, k: number): boolean { + let req = 1 << k; + const seen: boolean[] = new Array(req).fill(false); + const mask = req - 1; + let h = 0; + + for (let i = 0; i < s.length; i++) { + h = ((h << 1) & mask) | (s.charCodeAt(i) & 1); + + if (i >= k - 1 && !seen[h]) { + seen[h] = true; + req--; + if (req === 0) return true; + } + } + + return false; +} diff --git a/tests/1001-1500/1462. course-schedule-iv/manifest.yaml b/tests/1001-1500/1462. course-schedule-iv/manifest.yaml new file mode 100644 index 00000000..702e7fd0 --- /dev/null +++ b/tests/1001-1500/1462. course-schedule-iv/manifest.yaml @@ -0,0 +1,844 @@ +entry: + id: 1462 + title: "course-schedule-iv" + params: + numCourses: + type: int + prerequisites: + type: array + items: + type: array + items: + type: int + queries: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().checkIfPrerequisite({numCourses}, {prerequisites}, {queries})" + rust: "Solution::check_if_prerequisite({numCourses}, {prerequisites}, {queries})" + python3: "Solution().checkIfPrerequisite({numCourses}, {prerequisites}, {queries})" + python2: "Solution().checkIfPrerequisite({numCourses}, {prerequisites}, {queries})" + ruby: "check_if_prerequisite({numCourses}, {prerequisites}, {queries})" + java: "new Solution().checkIfPrerequisite({numCourses}, {prerequisites}, {queries})" + csharp: "new Solution().CheckIfPrerequisite({numCourses}, {prerequisites}, {queries})" + kotlin: "Solution().checkIfPrerequisite({numCourses}, {prerequisites}, {queries})" + go: "checkIfPrerequisite({numCourses}, {prerequisites}, {queries})" + dart: "Solution().checkIfPrerequisite({numCourses}, {prerequisites}, {queries})" + swift: "Solution().checkIfPrerequisite({numCourses}, {prerequisites}, {queries})" + typescript: "checkIfPrerequisite({numCourses}, {prerequisites}, {queries})" +judge: + type: "exact" +limits: + time_ms: 900 + memory_mb: 300 +oracle: + python3: + call: "Checker().checkIfPrerequisite(numCourses, prerequisites, queries, {result})" + checker: | + class Checker: + def checkIfPrerequisite(self, numCourses, prerequisites, queries, result): + graph = [[] for _ in range(numCourses)] + for source, target in prerequisites: + graph[source].append(target) + answer = [] + for source, target in queries: + seen = [False] * numCourses + stack = [source] + while stack: + node = stack.pop() + if node == target: + break + if seen[node]: + continue + seen[node] = True + stack.extend(graph[node]) + answer.append(seen[target]) + return result == answer +seed: 1462 +tests: + - name: "official-direct" + in: + numCourses: 2 + prerequisites: + - [1, 0] + queries: + - [0, 1] + - [1, 0] + out: [false, true] + - name: "official-independent" + in: + numCourses: 2 + prerequisites: [] + queries: + - [1, 0] + - [0, 1] + out: [false, false] + - name: "official-chain" + in: + numCourses: 3 + prerequisites: + - [1, 2] + - [1, 0] + - [2, 0] + queries: + - [1, 0] + - [1, 2] + out: [true, true] + - name: "two-course-reverse" + in: + numCourses: 2 + prerequisites: + - [0, 1] + queries: + - [0, 1] + - [1, 0] + out: [true, false] + - name: "empty-graph" + in: + numCourses: 5 + prerequisites: [] + queries: + - [0, 1] + - [1, 2] + - [4, 0] + - [3, 2] + out: [false, false, false, false] + - name: "three-chain" + in: + numCourses: 4 + prerequisites: + - [0, 1] + - [1, 2] + - [2, 3] + queries: + - [0, 3] + - [0, 2] + - [3, 0] + - [1, 3] + out: [true, true, false, true] + - name: "diamond" + in: + numCourses: 4 + prerequisites: + - [0, 1] + - [0, 2] + - [1, 3] + - [2, 3] + queries: + - [0, 3] + - [1, 2] + - [2, 3] + - [3, 0] + out: [true, false, true, false] + - name: "two-components" + in: + numCourses: 6 + prerequisites: + - [0, 1] + - [2, 3] + - [3, 4] + queries: + - [0, 1] + - [2, 4] + - [0, 4] + - [5, 0] + out: [true, true, false, false] + - name: "long-chain" + in: + numCourses: 7 + prerequisites: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + queries: + - [0, 6] + - [2, 5] + - [6, 0] + - [4, 6] + out: [true, true, false, true] + - name: "sink-queries" + in: + numCourses: 5 + prerequisites: + - [0, 4] + - [1, 4] + - [2, 4] + - [3, 4] + queries: + - [0, 4] + - [4, 0] + - [1, 3] + out: [true, false, false] + - name: "source-queries" + in: + numCourses: 5 + prerequisites: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + queries: + - [0, 3] + - [3, 0] + - [1, 4] + out: [true, false, false] + - name: "nested-diamond" + in: + numCourses: 6 + prerequisites: + - [0, 1] + - [0, 2] + - [1, 3] + - [2, 3] + - [3, 4] + - [3, 5] + queries: + - [0, 4] + - [0, 5] + - [1, 5] + - [4, 5] + out: [true, true, true, false] + - name: "interleaved-components" + in: + numCourses: 8 + prerequisites: + - [0, 2] + - [2, 4] + - [1, 3] + - [3, 5] + - [6, 7] + queries: + - [0, 4] + - [1, 5] + - [0, 5] + - [6, 7] + out: [true, true, false, true] + - name: "direct-many" + in: + numCourses: 6 + prerequisites: + - [0, 1] + - [0, 2] + - [0, 3] + - [1, 4] + - [2, 5] + queries: + - [0, 1] + - [0, 4] + - [0, 5] + - [3, 4] + out: [true, true, true, false] + - name: "isolated-middle" + in: + numCourses: 7 + prerequisites: + - [0, 1] + - [1, 2] + - [4, 5] + queries: + - [0, 2] + - [2, 0] + - [3, 6] + - [4, 5] + out: [true, false, false, true] + - name: "wide-layered" + in: + numCourses: 9 + prerequisites: + - [0, 3] + - [0, 4] + - [1, 4] + - [1, 5] + - [2, 5] + - [2, 6] + - [3, 7] + - [4, 7] + - [5, 8] + - [6, 8] + queries: + - [0, 7] + - [1, 8] + - [2, 7] + - [3, 8] + out: [true, true, false, false] + - name: "reverse-numbering" + in: + numCourses: 5 + prerequisites: + - [4, 3] + - [3, 2] + - [2, 1] + - [1, 0] + queries: + - [4, 0] + - [0, 4] + - [3, 1] + out: [true, false, true] + - name: "sparse-high-index" + in: + numCourses: 10 + prerequisites: + - [8, 9] + - [7, 8] + - [2, 7] + queries: + - [2, 9] + - [7, 9] + - [9, 2] + - [1, 9] + out: [true, true, false, false] + - name: "three-branches" + in: + numCourses: 7 + prerequisites: + - [0, 1] + - [0, 2] + - [0, 3] + - [1, 4] + - [2, 5] + - [3, 6] + queries: + - [0, 4] + - [0, 5] + - [0, 6] + - [1, 5] + out: [true, true, true, false] + - name: "two-long-chains" + in: + numCourses: 10 + prerequisites: + - [0, 1] + - [1, 2] + - [2, 3] + - [4, 5] + - [5, 6] + - [6, 7] + queries: + - [0, 3] + - [4, 7] + - [0, 7] + - [7, 4] + out: [true, true, false, false] + - name: "converging-sources" + in: + numCourses: 7 + prerequisites: + - [0, 6] + - [1, 6] + - [2, 6] + - [3, 6] + - [4, 5] + - [5, 6] + queries: + - [4, 6] + - [0, 6] + - [6, 0] + - [1, 5] + out: [true, true, false, false] + - name: "long-branch" + in: + numCourses: 8 + prerequisites: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [2, 6] + - [6, 7] + queries: + - [0, 7] + - [1, 5] + - [6, 5] + - [2, 4] + out: [true, true, false, true] + - name: "ten-course-chain" + in: + numCourses: 10 + prerequisites: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + queries: + - [0, 9] + - [4, 9] + - [9, 0] + out: [true, true, false] + - name: "ten-course-no-edges" + in: + numCourses: 10 + prerequisites: [] + queries: + - [0, 9] + - [9, 0] + - [3, 7] + out: [false, false, false] + - name: "diamond-with-tail" + in: + numCourses: 8 + prerequisites: + - [0, 1] + - [0, 2] + - [1, 3] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + queries: + - [0, 6] + - [2, 5] + - [1, 2] + - [7, 6] + out: [true, true, false, false] + - name: "mixed-queries" + in: + numCourses: 6 + prerequisites: + - [0, 2] + - [2, 3] + - [1, 3] + - [3, 5] + queries: + - [0, 5] + - [1, 5] + - [2, 5] + - [4, 5] + out: [true, true, true, false] + - name: "low-to-high" + in: + numCourses: 8 + prerequisites: + - [0, 7] + - [1, 6] + - [2, 5] + - [3, 4] + queries: + - [0, 7] + - [1, 7] + - [3, 4] + - [7, 0] + out: [true, false, true, false] + - name: "branching-depth" + in: + numCourses: 9 + prerequisites: + - [0, 1] + - [0, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [2, 6] + - [3, 7] + - [4, 8] + queries: + - [0, 7] + - [0, 8] + - [2, 8] + - [1, 6] + out: [true, true, false, false] + - name: "isolated-endpoints" + in: + numCourses: 6 + prerequisites: + - [1, 2] + - [2, 3] + - [3, 4] + queries: + - [1, 4] + - [0, 4] + - [4, 5] + out: [true, false, false] + - name: "dense-small-dag" + in: + numCourses: 5 + prerequisites: + - [0, 1] + - [0, 2] + - [0, 3] + - [1, 2] + - [1, 3] + - [2, 3] + - [3, 4] + queries: + - [0, 4] + - [1, 4] + - [2, 4] + - [4, 0] + out: [true, true, true, false] + - name: "disjoint-pairs" + in: + numCourses: 8 + prerequisites: + - [0, 1] + - [2, 3] + - [4, 5] + - [6, 7] + queries: + - [0, 1] + - [2, 3] + - [0, 3] + - [7, 6] + out: [true, true, false, false] + - name: "alternating-chain" + in: + numCourses: 9 + prerequisites: + - [0, 2] + - [2, 4] + - [4, 6] + - [6, 8] + - [1, 3] + - [3, 5] + - [5, 7] + queries: + - [0, 8] + - [1, 7] + - [0, 7] + - [4, 8] + out: [true, true, false, true] + - name: "many-sinks" + in: + numCourses: 8 + prerequisites: + - [0, 4] + - [0, 5] + - [1, 5] + - [1, 6] + - [2, 6] + - [2, 7] + - [3, 7] + queries: + - [0, 5] + - [1, 7] + - [2, 4] + - [3, 6] + out: [true, false, false, false] + - name: "single-branch-extra" + in: + numCourses: 5 + prerequisites: + - [0, 1] + - [1, 4] + - [2, 3] + queries: + - [0, 4] + - [2, 4] + - [3, 2] + out: [true, false, false] + - name: "three-level-extra" + in: + numCourses: 6 + prerequisites: + - [0, 2] + - [0, 3] + - [2, 5] + - [3, 4] + queries: + - [0, 5] + - [0, 4] + - [2, 4] + - [5, 0] + out: [true, true, false, false] + - name: "maximum-course-chain" + in: + numCourses: 100 + prerequisites: + - [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] + - [49, 50] + - [50, 51] + - [51, 52] + - [52, 53] + - [53, 54] + - [54, 55] + - [55, 56] + - [56, 57] + - [57, 58] + - [58, 59] + - [59, 60] + - [60, 61] + - [61, 62] + - [62, 63] + - [63, 64] + - [64, 65] + - [65, 66] + - [66, 67] + - [67, 68] + - [68, 69] + - [69, 70] + - [70, 71] + - [71, 72] + - [72, 73] + - [73, 74] + - [74, 75] + - [75, 76] + - [76, 77] + - [77, 78] + - [78, 79] + - [79, 80] + - [80, 81] + - [81, 82] + - [82, 83] + - [83, 84] + - [84, 85] + - [85, 86] + - [86, 87] + - [87, 88] + - [88, 89] + - [89, 90] + - [90, 91] + - [91, 92] + - [92, 93] + - [93, 94] + - [94, 95] + - [95, 96] + - [96, 97] + - [97, 98] + - [98, 99] + queries: + - [0, 99] + - [49, 99] + - [99, 0] + - [0, 50] + - [50, 51] + - [51, 50] + - [98, 99] + - [1, 98] + - [97, 99] + - [10, 90] + out: [true, true, false, true, true, false, true, true, true, true] + - name: "maximum-course-fan" + in: + numCourses: 100 + prerequisites: + - [0, 50] + - [1, 50] + - [2, 50] + - [3, 50] + - [4, 50] + - [5, 50] + - [6, 50] + - [7, 50] + - [8, 50] + - [9, 50] + - [10, 50] + - [11, 50] + - [12, 50] + - [13, 50] + - [14, 50] + - [15, 50] + - [16, 50] + - [17, 50] + - [18, 50] + - [19, 50] + - [20, 50] + - [21, 50] + - [22, 50] + - [23, 50] + - [24, 50] + - [25, 50] + - [26, 50] + - [27, 50] + - [28, 50] + - [29, 50] + - [30, 50] + - [31, 50] + - [32, 50] + - [33, 50] + - [34, 50] + - [35, 50] + - [36, 50] + - [37, 50] + - [38, 50] + - [39, 50] + - [40, 50] + - [41, 50] + - [42, 50] + - [43, 50] + - [44, 50] + - [45, 50] + - [46, 50] + - [47, 50] + - [48, 50] + - [49, 50] + - [50, 51] + - [50, 52] + - [50, 53] + - [50, 54] + - [50, 55] + - [50, 56] + - [50, 57] + - [50, 58] + - [50, 59] + - [50, 60] + - [50, 61] + - [50, 62] + - [50, 63] + - [50, 64] + - [50, 65] + - [50, 66] + - [50, 67] + - [50, 68] + - [50, 69] + - [50, 70] + - [50, 71] + - [50, 72] + - [50, 73] + - [50, 74] + - [50, 75] + - [50, 76] + - [50, 77] + - [50, 78] + - [50, 79] + - [50, 80] + - [50, 81] + - [50, 82] + - [50, 83] + - [50, 84] + - [50, 85] + - [50, 86] + - [50, 87] + - [50, 88] + - [50, 89] + - [50, 90] + - [50, 91] + - [50, 92] + - [50, 93] + - [50, 94] + - [50, 95] + - [50, 96] + - [50, 97] + - [50, 98] + - [50, 99] + queries: + - [0, 50] + - [49, 99] + - [0, 99] + - [50, 99] + - [99, 50] + - [1, 49] + - [51, 99] + out: [true, true, true, true, false, false, false] + - name: "duplicate-queries" + in: + numCourses: 6 + prerequisites: + - [0, 2] + - [2, 4] + - [1, 3] + - [3, 4] + - [4, 5] + queries: + - [0, 5] + - [0, 5] + - [4, 5] + - [5, 4] + - [1, 4] + - [1, 4] + out: [true, true, true, false, true, true] + - name: "isolated-and-components" + in: + numCourses: 12 + prerequisites: + - [0, 1] + - [1, 2] + - [3, 4] + - [4, 5] + - [6, 8] + - [7, 8] + - [8, 9] + queries: + - [0, 2] + - [3, 5] + - [6, 9] + - [7, 9] + - [0, 5] + - [10, 11] + - [11, 10] + out: [true, true, true, true, false, false, false] + - name: "dense-six-course-dag" + in: + numCourses: 6 + prerequisites: + - [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] + queries: + - [0, 5] + - [1, 4] + - [2, 5] + - [3, 5] + - [5, 0] + - [4, 2] + out: [true, true, true, true, false, false] diff --git a/tests/1001-1500/1462. course-schedule-iv/sol.cpp b/tests/1001-1500/1462. course-schedule-iv/sol.cpp new file mode 100644 index 00000000..43e2c7df --- /dev/null +++ b/tests/1001-1500/1462. course-schedule-iv/sol.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + vector checkIfPrerequisite(int n, vector>& prerequisites, vector>& queries) { + vector> reach(n, vector(n)); + for (const auto& edge : prerequisites) reach[edge[0]][edge[1]] = true; + for (int k = 0; k < n; ++k) + for (int i = 0; i < n; ++i) + if (reach[i][k]) + for (int j = 0; j < n; ++j) reach[i][j] = reach[i][j] || reach[k][j]; + vector answer; + for (const auto& query : queries) answer.push_back(reach[query[0]][query[1]]); + return answer; + } +}; diff --git a/tests/1001-1500/1462. course-schedule-iv/sol.cs b/tests/1001-1500/1462. course-schedule-iv/sol.cs new file mode 100644 index 00000000..b123ad34 --- /dev/null +++ b/tests/1001-1500/1462. course-schedule-iv/sol.cs @@ -0,0 +1,13 @@ +public class Solution { + public IList CheckIfPrerequisite(int n, int[][] prerequisites, int[][] queries) { + var reach = new bool[n, n]; + foreach (var edge in prerequisites) reach[edge[0], edge[1]] = true; + for (int k = 0; k < n; k++) + for (int i = 0; i < n; i++) + if (reach[i, k]) + for (int j = 0; j < n; j++) reach[i, j] |= reach[k, j]; + var answer = new List(); + foreach (var query in queries) answer.Add(reach[query[0], query[1]]); + return answer; + } +} diff --git a/tests/1001-1500/1462. course-schedule-iv/sol.dart b/tests/1001-1500/1462. course-schedule-iv/sol.dart new file mode 100644 index 00000000..e5f4aa8a --- /dev/null +++ b/tests/1001-1500/1462. course-schedule-iv/sol.dart @@ -0,0 +1,13 @@ +class Solution { + List checkIfPrerequisite(int n, List> prerequisites, List> queries) { + final reach = List.generate(n, (_) => List.filled(n, false)); + for (final edge in prerequisites) reach[edge[0]][edge[1]] = true; + for (var k = 0; k < n; k++) { + for (var i = 0; i < n; i++) { + if (!reach[i][k]) continue; + for (var j = 0; j < n; j++) reach[i][j] = reach[i][j] || reach[k][j]; + } + } + return queries.map((query) => reach[query[0]][query[1]]).toList(); + } +} diff --git a/tests/1001-1500/1462. course-schedule-iv/sol.go b/tests/1001-1500/1462. course-schedule-iv/sol.go new file mode 100644 index 00000000..d8f42ae3 --- /dev/null +++ b/tests/1001-1500/1462. course-schedule-iv/sol.go @@ -0,0 +1,14 @@ +func checkIfPrerequisite(n int, prerequisites [][]int, queries [][]int) []bool { + reach := make([][]bool, n) + for i := range reach { reach[i] = make([]bool, n) } + for _, edge := range prerequisites { reach[edge[0]][edge[1]] = true } + for k := 0; k < n; k++ { + for i := 0; i < n; i++ { + if !reach[i][k] { continue } + for j := 0; j < n; j++ { reach[i][j] = reach[i][j] || reach[k][j] } + } + } + answer := make([]bool, len(queries)) + for i, query := range queries { answer[i] = reach[query[0]][query[1]] } + return answer +} diff --git a/tests/1001-1500/1462. course-schedule-iv/sol.java b/tests/1001-1500/1462. course-schedule-iv/sol.java new file mode 100644 index 00000000..fd8c2c25 --- /dev/null +++ b/tests/1001-1500/1462. course-schedule-iv/sol.java @@ -0,0 +1,13 @@ +class Solution { + public List checkIfPrerequisite(int n, int[][] prerequisites, int[][] queries) { + boolean[][] reach = new boolean[n][n]; + for (int[] edge : prerequisites) reach[edge[0]][edge[1]] = true; + for (int k = 0; k < n; k++) + for (int i = 0; i < n; i++) + if (reach[i][k]) + for (int j = 0; j < n; j++) reach[i][j] |= reach[k][j]; + List answer = new ArrayList<>(); + for (int[] query : queries) answer.add(reach[query[0]][query[1]]); + return answer; + } +} diff --git a/tests/1001-1500/1462. course-schedule-iv/sol.kt b/tests/1001-1500/1462. course-schedule-iv/sol.kt new file mode 100644 index 00000000..c2901e19 --- /dev/null +++ b/tests/1001-1500/1462. course-schedule-iv/sol.kt @@ -0,0 +1,11 @@ +class Solution { + fun checkIfPrerequisite(n: Int, prerequisites: Array, queries: Array): List { + val reach = Array(n) { BooleanArray(n) } + for (edge in prerequisites) reach[edge[0]][edge[1]] = true + for (k in 0 until n) + for (i in 0 until n) + if (reach[i][k]) + for (j in 0 until n) reach[i][j] = reach[i][j] || reach[k][j] + return queries.map { reach[it[0]][it[1]] } + } +} diff --git a/tests/1001-1500/1462. course-schedule-iv/sol.py b/tests/1001-1500/1462. course-schedule-iv/sol.py new file mode 100644 index 00000000..cb1f7de2 --- /dev/null +++ b/tests/1001-1500/1462. course-schedule-iv/sol.py @@ -0,0 +1,34 @@ +from collections import deque + + +class Solution(object): + def checkIfPrerequisite(self, numCourses, prerequisites, queries): + adj = [[] for _ in range(numCourses)] + prereq = [0] * numCourses # Bitmask for prerequisites + in_degree = [0] * numCourses + + # Build graph and initialize direct prerequisites + for a, b in prerequisites: + adj[a].append(b) + prereq[b] |= 1 << a # Set the a-th bit for course b + in_degree[b] += 1 + + # Topological sort using Kahn's algorithm + q = deque() + for i in range(numCourses): + if in_degree[i] == 0: + q.append(i) + + while q: + u = q.popleft() + for v in adj[u]: + prereq[v] |= prereq[u] # Merge u's prerequisites into v's + in_degree[v] -= 1 + if in_degree[v] == 0: + q.append(v) + + # Answer queries using bitmask checks + ans = [] + for u, v in queries: + ans.append((prereq[v] & (1 << u)) != 0) + return ans diff --git a/tests/1001-1500/1462. course-schedule-iv/sol.py2 b/tests/1001-1500/1462. course-schedule-iv/sol.py2 new file mode 100644 index 00000000..562cfcda --- /dev/null +++ b/tests/1001-1500/1462. course-schedule-iv/sol.py2 @@ -0,0 +1,29 @@ +class Solution(object): + def checkIfPrerequisite(self, numCourses, prerequisites, queries): + adj = [[] for _ in range(numCourses)] + prereq = [0] * numCourses + in_degree = [0] * numCourses + + for a, b in prerequisites: + adj[a].append(b) + prereq[b] |= 1 << a + in_degree[b] += 1 + + from collections import deque + q = deque() + for i in range(numCourses): + if in_degree[i] == 0: + q.append(i) + + while q: + u = q.popleft() + for v in adj[u]: + prereq[v] |= prereq[u] + in_degree[v] -= 1 + if in_degree[v] == 0: + q.append(v) + + ans = [] + for u, v in queries: + ans.append((prereq[v] & (1 << u)) != 0) + return ans diff --git a/tests/1001-1500/1462. course-schedule-iv/sol.rb b/tests/1001-1500/1462. course-schedule-iv/sol.rb new file mode 100644 index 00000000..5f2e21d0 --- /dev/null +++ b/tests/1001-1500/1462. course-schedule-iv/sol.rb @@ -0,0 +1,33 @@ +# @param {Integer} num_courses +# @param {Integer[][]} prerequisites +# @param {Integer[][]} queries +# @return {Boolean[]} +def check_if_prerequisite(num_courses, prerequisites, queries) + adj = Array.new(num_courses) { [] } + prereq = Array.new(num_courses, 0) + in_degree = Array.new(num_courses, 0) + + prerequisites.each do |a, b| + adj[a] << b + prereq[b] |= (1 << a) + in_degree[b] += 1 + end + + q = [] + (0...num_courses).each do |i| + q.push(i) if in_degree[i] == 0 + end + + while !q.empty? + u = q.shift + adj[u].each do |v| + prereq[v] |= prereq[u] + in_degree[v] -= 1 + if in_degree[v] == 0 + q.push(v) + end + end + end + + queries.map { |u, v| (prereq[v] & (1 << u)) != 0 } +end diff --git a/tests/1001-1500/1462. course-schedule-iv/sol.rs b/tests/1001-1500/1462. course-schedule-iv/sol.rs new file mode 100644 index 00000000..f9654348 --- /dev/null +++ b/tests/1001-1500/1462. course-schedule-iv/sol.rs @@ -0,0 +1,14 @@ +impl Solution { + pub fn check_if_prerequisite(n: i32, prerequisites: Vec>, queries: Vec>) -> Vec { + let n = n as usize; + let mut reach = vec![vec![false; n]; n]; + for edge in prerequisites { reach[edge[0] as usize][edge[1] as usize] = true; } + for k in 0..n { + for i in 0..n { + if !reach[i][k] { continue; } + for j in 0..n { reach[i][j] |= reach[k][j]; } + } + } + queries.into_iter().map(|query| reach[query[0] as usize][query[1] as usize]).collect() + } +} diff --git a/tests/1001-1500/1462. course-schedule-iv/sol.swift b/tests/1001-1500/1462. course-schedule-iv/sol.swift new file mode 100644 index 00000000..26ffaf63 --- /dev/null +++ b/tests/1001-1500/1462. course-schedule-iv/sol.swift @@ -0,0 +1,12 @@ +class Solution { + func checkIfPrerequisite(_ n: Int, _ prerequisites: [[Int]], _ queries: [[Int]]) -> [Bool] { + var reach = Array(repeating: Array(repeating: false, count: n), count: n) + for edge in prerequisites { reach[edge[0]][edge[1]] = true } + for k in 0.. Array(n).fill(false)); + for (const [from, to] of prerequisites) reach[from][to] = true; + for (let k = 0; k < n; k++) + for (let i = 0; i < n; i++) + if (reach[i][k]) for (let j = 0; j < n; j++) reach[i][j] ||= reach[k][j]; + return queries.map(([from, to]) => reach[from][to]); +} diff --git a/tests/1001-1500/1463. cherry-pickup-ii/manifest.yaml b/tests/1001-1500/1463. cherry-pickup-ii/manifest.yaml new file mode 100644 index 00000000..e0e3ae9e --- /dev/null +++ b/tests/1001-1500/1463. cherry-pickup-ii/manifest.yaml @@ -0,0 +1,535 @@ +entry: + id: 1463 + title: cherry-pickup-ii + params: + grid: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().cherryPickup({grid})" + rust: "Solution::cherry_pickup({grid})" + python3: "Solution().cherryPickup({grid})" + python2: "Solution().cherryPickup({grid})" + ruby: "cherry_pickup({grid})" + java: "new Solution().cherryPickup({grid})" + csharp: "new Solution().CherryPickup({grid})" + kotlin: "Solution().cherryPickup({grid})" + go: "cherryPickup({grid})" + dart: "Solution().cherryPickup({grid})" + swift: "Solution().cherryPickup({grid})" + typescript: "cherryPickup({grid})" +judge: + type: exact +limits: + time_ms: 4000 + memory_mb: 256 +oracle: + python3: + call: "Checker().cherryPickup(grid, {result})" + checker: | + class Checker: + def cherryPickup(self, grid, result): + if type(result) is not int or not grid or not grid[0]: + return False + rows, cols = len(grid), len(grid[0]) + dp = {(0, cols - 1): grid[0][0] + grid[0][cols - 1]} + for row in range(1, rows): + nxt = {} + for (left, right), score in dp.items(): + for nl in (left - 1, left, left + 1): + for nr in (right - 1, right, right + 1): + if 0 <= nl < cols and 0 <= nr < cols: + gain = grid[row][nl] + if nr != nl: + gain += grid[row][nr] + key = (min(nl, nr), max(nl, nr)) + nxt[key] = max(nxt.get(key, -1), score + gain) + dp = nxt + return result == max(dp.values()) +seed: 1463 +tests: + - name: prompt-example-one + in: + grid: + elemType: int + value: + - [3, 1, 1] + - [2, 5, 1] + - [1, 5, 5] + - [2, 1, 1] + out: 24 + + - name: prompt-example-two + in: + grid: + elemType: int + value: + - [1, 0, 0, 0, 0, 0, 1] + - [2, 0, 0, 0, 0, 3, 0] + - [2, 0, 9, 0, 0, 0, 0] + - [0, 3, 0, 5, 4, 0, 0] + - [1, 0, 2, 3, 0, 0, 6] + out: 28 + + - name: minimum-two-by-two + in: + grid: + elemType: int + value: + - [1, 2] + - [3, 4] + out: 10 + + - name: minimum-all-zero + in: + grid: + elemType: int + value: + - [0, 0] + - [0, 0] + out: 0 + + - name: minimum-high-values + in: + grid: + elemType: int + value: + - [100, 99] + - [98, 97] + out: 394 + + - name: two-by-three + in: + grid: + elemType: int + value: + - [5, 1, 5] + - [1, 9, 1] + out: 20 + + - name: two-by-four + in: + grid: + elemType: int + value: + - [1, 2, 3, 4] + - [4, 3, 2, 1] + out: 11 + + - name: two-by-five-center + in: + grid: + elemType: int + value: + - [0, 0, 100, 0, 0] + - [0, 100, 0, 100, 0] + out: 200 + + - name: three-by-three + in: + grid: + elemType: int + value: + - [1, 2, 3] + - [4, 5, 6] + - [7, 8, 9] + out: 32 + + - name: three-by-four + in: + grid: + elemType: int + value: + - [9, 0, 0, 9] + - [0, 8, 8, 0] + - [7, 0, 0, 7] + out: 48 + + - name: three-by-five + in: + grid: + elemType: int + value: + - [1, 0, 0, 0, 1] + - [0, 50, 0, 50, 0] + - [1, 0, 100, 0, 1] + out: 203 + + - name: three-by-seven + in: + grid: + elemType: int + value: + - [3, 1, 4, 1, 5, 9, 2] + - [6, 5, 3, 5, 8, 9, 7] + - [9, 3, 2, 3, 8, 4, 6] + out: 37 + + - name: four-by-two + in: + grid: + elemType: int + value: + - [1, 1] + - [2, 2] + - [3, 3] + - [4, 4] + out: 20 + + - name: four-by-four-diagonal + in: + grid: + elemType: int + value: + - [10, 0, 0, 10] + - [0, 20, 20, 0] + - [0, 30, 30, 0] + - [40, 0, 0, 40] + out: 200 + + - name: four-by-five + in: + grid: + elemType: int + value: + - [2, 7, 1, 8, 2] + - [8, 1, 8, 2, 8] + - [1, 8, 2, 8, 1] + - [8, 2, 8, 1, 8] + out: 52 + + - name: four-by-six + in: + grid: + elemType: int + value: + - [0, 1, 0, 1, 0, 1] + - [1, 0, 1, 0, 1, 0] + - [0, 10, 0, 10, 0, 10] + - [10, 0, 10, 0, 10, 0] + out: 43 + + - name: five-by-three + in: + grid: + elemType: int + value: + - [9, 1, 9] + - [1, 9, 1] + - [9, 1, 9] + - [1, 9, 1] + - [9, 1, 9] + out: 74 + + - name: five-by-four + in: + grid: + elemType: int + value: + - [4, 0, 0, 4] + - [0, 3, 3, 0] + - [0, 2, 2, 0] + - [0, 1, 1, 0] + - [5, 5, 5, 5] + out: 30 + + - name: five-by-five + in: + grid: + elemType: int + value: + - [5, 4, 3, 2, 1] + - [1, 2, 3, 4, 5] + - [9, 9, 0, 9, 9] + - [5, 4, 3, 2, 1] + - [1, 2, 3, 4, 5] + out: 45 + + - name: five-by-seven + in: + grid: + elemType: int + value: + - [1, 1, 1, 1, 1, 1, 1] + - [0, 2, 0, 2, 0, 2, 0] + - [3, 0, 3, 0, 3, 0, 3] + - [0, 4, 0, 4, 0, 4, 0] + - [5, 5, 5, 5, 5, 5, 5] + out: 30 + + - name: six-by-two + in: + grid: + elemType: int + value: + - [1, 2] + - [2, 1] + - [3, 4] + - [4, 3] + - [5, 6] + - [6, 5] + out: 42 + + - name: six-by-three-spikes + in: + grid: + elemType: int + value: + - [0, 0, 100] + - [0, 90, 0] + - [80, 0, 0] + - [0, 70, 0] + - [0, 0, 60] + - [50, 0, 0] + out: 450 + + - name: six-by-four + in: + grid: + elemType: int + value: + - [6, 0, 0, 6] + - [0, 5, 5, 0] + - [4, 0, 0, 4] + - [0, 3, 3, 0] + - [2, 0, 0, 2] + - [0, 1, 1, 0] + out: 42 + + - name: six-by-six + in: + grid: + elemType: int + value: + - [1, 2, 3, 4, 5, 6] + - [6, 5, 4, 3, 2, 1] + - [2, 4, 6, 8, 10, 12] + - [12, 10, 8, 6, 4, 2] + - [3, 6, 9, 12, 15, 18] + - [18, 15, 12, 9, 6, 3] + out: 95 + + - name: seven-by-three + in: + grid: + elemType: int + value: + - [10, 0, 10] + - [0, 20, 0] + - [10, 0, 10] + - [0, 30, 0] + - [10, 0, 10] + - [0, 40, 0] + - [10, 0, 10] + out: 170 + + - name: seven-by-seven-zeros + in: + grid: + 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] + out: 0 + + - name: seven-by-seven-high + in: + grid: + elemType: int + value: + - [100, 100, 100, 100, 100, 100, 100] + - [99, 99, 99, 99, 99, 99, 99] + - [98, 98, 98, 98, 98, 98, 98] + - [97, 97, 97, 97, 97, 97, 97] + - [96, 96, 96, 96, 96, 96, 96] + - [95, 95, 95, 95, 95, 95, 95] + - [94, 94, 94, 94, 94, 94, 94] + out: 1358 + + - name: eight-by-four + in: + grid: + elemType: int + value: + - [1, 3, 5, 7] + - [2, 4, 6, 8] + - [9, 7, 5, 3] + - [8, 6, 4, 2] + - [1, 0, 1, 0] + - [0, 1, 0, 1] + - [10, 20, 30, 40] + - [40, 30, 20, 10] + out: 172 + + - name: eight-by-five + in: + grid: + elemType: int + value: + - [0, 5, 0, 5, 0] + - [5, 0, 5, 0, 5] + - [10, 0, 0, 0, 10] + - [0, 20, 0, 20, 0] + - [30, 0, 30, 0, 30] + - [0, 40, 0, 40, 0] + - [50, 50, 50, 50, 50] + - [1, 2, 3, 4, 5] + out: 319 + + - name: nine-by-six + in: + grid: + elemType: int + value: + - [3, 1, 4, 1, 5, 9] + - [2, 6, 5, 3, 5, 8] + - [9, 7, 9, 3, 2, 3] + - [8, 4, 6, 2, 6, 4] + - [3, 3, 8, 3, 2, 7] + - [9, 5, 0, 5, 0, 5] + - [8, 9, 7, 9, 3, 2] + - [3, 8, 4, 6, 2, 6] + - [4, 3, 3, 8, 3, 2] + out: 118 + + - name: ten-by-three-alternating + in: + grid: + elemType: int + value: + - [1, 0, 1] + - [0, 2, 0] + - [3, 0, 3] + - [0, 4, 0] + - [5, 0, 5] + - [0, 6, 0] + - [7, 0, 7] + - [0, 8, 0] + - [9, 0, 9] + - [0, 10, 0] + out: 80 + + - name: ten-by-ten-pattern + in: + grid: + elemType: int + value: + - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + - [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + - [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] + - [20, 18, 16, 14, 12, 10, 8, 6, 4, 2] + - [3, 6, 9, 12, 15, 18, 21, 24, 27, 30] + - [30, 27, 24, 21, 18, 15, 12, 9, 6, 3] + - [4, 8, 12, 16, 20, 24, 28, 32, 36, 40] + - [40, 36, 32, 28, 24, 20, 16, 12, 8, 4] + - [5, 10, 15, 20, 25, 30, 35, 40, 45, 50] + - [50, 45, 40, 35, 30, 25, 20, 15, 10, 5] + out: 359 + + - name: extra-two-by-three-low + in: + grid: + elemType: int + value: + - [2, 0, 4] + - [5, 1, 3] + out: 14 + + - name: extra-three-by-four-peak + in: + grid: + elemType: int + value: + - [1, 1, 1, 1] + - [0, 100, 100, 0] + - [1, 1, 1, 1] + out: 204 + + - name: extra-four-by-three-corners + in: + grid: + elemType: int + value: + - [9, 0, 9] + - [0, 8, 0] + - [7, 0, 7] + - [0, 6, 0] + out: 46 + + - name: stress-70x70-low + seed: 146301 + in: + grid: + gen: array + len: 70 + of: + gen: array + len: 70 + of: + gen: int + min: 0 + max: 1 + + - name: stress-70x70-mid + seed: 146302 + in: + grid: + gen: array + len: 70 + of: + gen: array + len: 70 + of: + gen: int + min: 0 + max: 100 + + - name: stress-70x70-high + seed: 146303 + in: + grid: + gen: array + len: 70 + of: + gen: array + len: 70 + of: + gen: int + min: 99 + max: 100 + + - name: stress-70x2-boundary + seed: 146304 + in: + grid: + gen: array + len: 70 + of: + gen: array + len: 2 + of: + gen: int + min: 0 + max: 100 + + - name: stress-2x70-boundary + seed: 146305 + in: + grid: + gen: array + len: 2 + of: + gen: array + len: 70 + of: + gen: int + min: 0 + max: 100 diff --git a/tests/1001-1500/1463. cherry-pickup-ii/sol.cpp b/tests/1001-1500/1463. cherry-pickup-ii/sol.cpp new file mode 100644 index 00000000..3f10faae --- /dev/null +++ b/tests/1001-1500/1463. cherry-pickup-ii/sol.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + int cherryPickup(vector>& grid) { + int m = grid.size(); + int n = grid[0].size(); + vector>> dp(m, vector>(n, vector(n, -1))); + dp[0][0][n-1] = grid[0][0] + grid[0][n-1]; + + for (int i = 1; i < m; i++) { + for (int j = 0; j < n; j++) { + for (int k = j+1; k < n; k++) { + for (int x = -1; x <= 1; x++) { + for (int y = -1; y <= 1; y++) { + int nj = j + x; + int nk = k + y; + if (nj >= 0 && nj < n && nk >= 0 && nk < n) { + int prev = dp[i-1][nj][nk]; + if (prev != -1) { + int add = grid[i][j]; + if (j != k) add += grid[i][k]; + dp[i][j][k] = max(dp[i][j][k], prev + add); + } + } + } + } + } + } + } + + int ans = -1; + for (auto& row : dp[m-1]) + for (int v : row) + ans = max(ans, v); + return ans != -1 ? ans : 0; + } +}; diff --git a/tests/1001-1500/1463. cherry-pickup-ii/sol.cs b/tests/1001-1500/1463. cherry-pickup-ii/sol.cs new file mode 100644 index 00000000..3e9123c6 --- /dev/null +++ b/tests/1001-1500/1463. cherry-pickup-ii/sol.cs @@ -0,0 +1,46 @@ +public class Solution { + public int CherryPickup(int[][] grid) { + int m = grid.Length; + int n = grid[0].Length; + int[][][] dp = new int[m][][]; + for (int i = 0; i < m; i++) { + dp[i] = new int[n][]; + for (int j = 0; j < n; j++) { + dp[i][j] = new int[n]; + for (int k = 0; k < n; k++) { + dp[i][j][k] = -1; + } + } + } + dp[0][0][n-1] = grid[0][0] + grid[0][n-1]; + + for (int i = 1; i < m; i++) { + for (int j = 0; j < n; j++) { + for (int k = j+1; k < n; k++) { + for (int x = -1; x <= 1; x++) { + for (int y = -1; y <= 1; y++) { + int nj = j + x; + int nk = k + y; + if (nj >= 0 && nj < n && nk >= 0 && nk < n) { + int prev = dp[i-1][nj][nk]; + if (prev != -1) { + int add = grid[i][j]; + if (j != k) add += grid[i][k]; + dp[i][j][k] = Math.Max(dp[i][j][k], prev + add); + } + } + } + } + } + } + } + + int ans = -1; + for (int j = 0; j < n; j++) { + for (int k = 0; k < n; k++) { + if (dp[m-1][j][k] > ans) ans = dp[m-1][j][k]; + } + } + return ans != -1 ? ans : 0; + } +} diff --git a/tests/1001-1500/1463. cherry-pickup-ii/sol.dart b/tests/1001-1500/1463. cherry-pickup-ii/sol.dart new file mode 100644 index 00000000..08b8d76f --- /dev/null +++ b/tests/1001-1500/1463. cherry-pickup-ii/sol.dart @@ -0,0 +1,39 @@ +class Solution { + int cherryPickup(List> grid) { + int m = grid.length; + int n = grid[0].length; + List>> dp = List.generate(m, (_) => List.generate(n, (_) => List.filled(n, -1))); + dp[0][0][n-1] = grid[0][0] + grid[0][n-1]; + + for (int i = 1; i < m; i++) { + for (int j = 0; j < n; j++) { + for (int k = j+1; k < n; k++) { + for (int x = -1; x <= 1; x++) { + for (int y = -1; y <= 1; y++) { + int nj = j + x; + int nk = k + y; + if (nj >= 0 && nj < n && nk >= 0 && nk < n) { + int prev = dp[i-1][nj][nk]; + if (prev != -1) { + int add = grid[i][j]; + if (j != k) add += grid[i][k]; + dp[i][j][k] = max(dp[i][j][k], prev + add); + } + } + } + } + } + } + } + + int ans = -1; + for (var row in dp[m-1]) { + for (var v in row) { + if (v > ans) ans = v; + } + } + return ans != -1 ? ans : 0; + } + + int max(int a, int b) => a > b ? a : b; +} diff --git a/tests/1001-1500/1463. cherry-pickup-ii/sol.go b/tests/1001-1500/1463. cherry-pickup-ii/sol.go new file mode 100644 index 00000000..c1d96251 --- /dev/null +++ b/tests/1001-1500/1463. cherry-pickup-ii/sol.go @@ -0,0 +1,52 @@ +func cherryPickup(grid [][]int) int { + m := len(grid) + n := len(grid[0]) + dp := make([][][]int, m) + for i := range dp { + dp[i] = make([][]int, n) + for j := range dp[i] { + dp[i][j] = make([]int, n) + for k := range dp[i][j] { + dp[i][j][k] = -1 + } + } + } + dp[0][0][n-1] = grid[0][0] + grid[0][n-1] + + for i := 1; i < m; i++ { + for j := 0; j < n; j++ { + for k := j+1; k < n; k++ { + for x := -1; x <= 1; x++ { + for y := -1; y <= 1; y++ { + nj, nk := j+x, k+y + if nj >= 0 && nj < n && nk >= 0 && nk < n { + prev := dp[i-1][nj][nk] + if prev != -1 { + add := grid[i][j] + if j != k { + add += grid[i][k] + } + if prev+add > dp[i][j][k] { + dp[i][j][k] = prev + add + } + } + } + } + } + } + } + } + + ans := -1 + for _, row := range dp[m-1] { + for _, v := range row { + if v > ans { + ans = v + } + } + } + if ans != -1 { + return ans + } + return 0 +} diff --git a/tests/1001-1500/1463. cherry-pickup-ii/sol.java b/tests/1001-1500/1463. cherry-pickup-ii/sol.java new file mode 100644 index 00000000..03ae7af1 --- /dev/null +++ b/tests/1001-1500/1463. cherry-pickup-ii/sol.java @@ -0,0 +1,39 @@ +class Solution { + public int cherryPickup(int[][] grid) { + int m = grid.length; + int n = grid[0].length; + int[][][] dp = new int[m][n][n]; + for (int i = 0; i < m; i++) + for (int j = 0; j < n; j++) + for (int k = 0; k < n; k++) + dp[i][j][k] = -1; + dp[0][0][n-1] = grid[0][0] + grid[0][n-1]; + + for (int i = 1; i < m; i++) { + for (int j = 0; j < n; j++) { + for (int k = j+1; k < n; k++) { + for (int x = -1; x <= 1; x++) { + for (int y = -1; y <= 1; y++) { + int nj = j + x; + int nk = k + y; + if (nj >= 0 && nj < n && nk >= 0 && nk < n) { + int prev = dp[i-1][nj][nk]; + if (prev != -1) { + int add = grid[i][j]; + if (j != k) add += grid[i][k]; + dp[i][j][k] = Math.max(dp[i][j][k], prev + add); + } + } + } + } + } + } + } + + int ans = -1; + for (int[] row : dp[m-1]) + for (int val : row) + ans = Math.max(ans, val); + return ans != -1 ? ans : 0; + } +} diff --git a/tests/1001-1500/1463. cherry-pickup-ii/sol.kt b/tests/1001-1500/1463. cherry-pickup-ii/sol.kt new file mode 100644 index 00000000..10d019a7 --- /dev/null +++ b/tests/1001-1500/1463. cherry-pickup-ii/sol.kt @@ -0,0 +1,35 @@ +class Solution { + fun cherryPickup(grid: Array): Int { + val m = grid.size + val n = grid[0].size + val dp = Array(m) { Array(n) { IntArray(n) { -1 } } } + dp[0][0][n-1] = grid[0][0] + grid[0][n-1] + + for (i in 1 until m) { + for (j in 0 until n) { + for (k in j+1 until n) { + for (x in -1..1) { + for (y in -1..1) { + val nj = j + x + val nk = k + y + if (nj in 0 until n && nk in 0 until n) { + val prev = dp[i-1][nj][nk] + if (prev != -1) { + var add = grid[i][j] + if (j != k) add += grid[i][k] + dp[i][j][k] = maxOf(dp[i][j][k], prev + add) + } + } + } + } + } + } + } + + var ans = -1 + for (row in dp[m-1]) + for (v in row) + ans = maxOf(ans, v) + return if (ans != -1) ans else 0 + } +} diff --git a/tests/1001-1500/1463. cherry-pickup-ii/sol.py b/tests/1001-1500/1463. cherry-pickup-ii/sol.py new file mode 100644 index 00000000..90d2ad0b --- /dev/null +++ b/tests/1001-1500/1463. cherry-pickup-ii/sol.py @@ -0,0 +1,23 @@ +class Solution: + def cherryPickup(self, grid: List[List[int]]) -> int: + m, n = len(grid), len(grid[0]) + dp = [[[-1] * n for _ in range(n)] for _ in range(m)] + dp[0][0][n - 1] = grid[0][0] + grid[0][n - 1] + + for i in range(1, m): + for j in range(n): + for k in range(j + 1, n): + for x in range(-1, 2): + for y in range(-1, 2): + if 0 <= j + x < n and 0 <= k + y < n: + prev = dp[i - 1][j + x][k + y] + if prev != -1: + dp[i][j][k] = max( + dp[i][j][k], + prev + + grid[i][j] + + (grid[i][k] if j != k else 0), + ) + + ans = max(max(row) for row in dp[m - 1]) + return ans if ans != -1 else 0 diff --git a/tests/1001-1500/1463. cherry-pickup-ii/sol.py2 b/tests/1001-1500/1463. cherry-pickup-ii/sol.py2 new file mode 100644 index 00000000..8aee4828 --- /dev/null +++ b/tests/1001-1500/1463. cherry-pickup-ii/sol.py2 @@ -0,0 +1,22 @@ +class Solution(object): + def cherryPickup(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + m, n = len(grid), len(grid[0]) + dp = [[[-1] * n for _ in range(n)] for _ in range(m)] + dp[0][0][n-1] = grid[0][0] + grid[0][n-1] + + for i in range(1, m): + for j in range(n): + for k in range(j+1, n): + for x in range(-1, 2): + for y in range(-1, 2): + if 0 <= j+x < n and 0 <= k+y < n: + prev = dp[i-1][j+x][k+y] + if prev != -1: + dp[i][j][k] = max(dp[i][j][k], prev + grid[i][j] + (grid[i][k] if j != k else 0)) + + ans = max(max(row) for row in dp[m-1]) + return ans if ans != -1 else 0 diff --git a/tests/1001-1500/1463. cherry-pickup-ii/sol.rb b/tests/1001-1500/1463. cherry-pickup-ii/sol.rb new file mode 100644 index 00000000..a5d25db0 --- /dev/null +++ b/tests/1001-1500/1463. cherry-pickup-ii/sol.rb @@ -0,0 +1,30 @@ +# @param {Integer[][]} grid +# @return {Integer} +def cherry_pickup(grid) + m = grid.length + n = grid[0].length + dp = Array.new(m) { Array.new(n) { Array.new(n, -1) } } + dp[0][0][n-1] = grid[0][0] + grid[0][n-1] + + (1...m).each do |i| + (0...n).each do |j| + (j+1...n).each do |k| + (-1..1).each do |x| + (-1..1).each do |y| + if j+x >= 0 && j+x < n && k+y >= 0 && k+y < n + prev = dp[i-1][j+x][k+y] + if prev != -1 + add = grid[i][j] + add += grid[i][k] if j != k + dp[i][j][k] = [dp[i][j][k], prev + add].max + end + end + end + end + end + end + end + + ans = dp[m-1].flatten.max + ans != -1 ? ans : 0 +end diff --git a/tests/1001-1500/1463. cherry-pickup-ii/sol.rs b/tests/1001-1500/1463. cherry-pickup-ii/sol.rs new file mode 100644 index 00000000..9da4ead2 --- /dev/null +++ b/tests/1001-1500/1463. cherry-pickup-ii/sol.rs @@ -0,0 +1,39 @@ +impl Solution { + pub fn cherry_pickup(grid: Vec>) -> i32 { + let m = grid.len(); + let n = grid[0].len(); + let mut dp = vec![vec![vec![-1; n]; n]; m]; + dp[0][0][n-1] = grid[0][0] + grid[0][n-1]; + + for i in 1..m { + for j in 0..n { + for k in j+1..n { + for x in -1..=1 { + for y in -1..=1 { + let nj = j as i32 + x; + let nk = k as i32 + y; + if nj >= 0 && nj < n as i32 && nk >= 0 && nk < n as i32 { + let prev = dp[i-1][nj as usize][nk as usize]; + if prev != -1 { + let mut add = grid[i][j]; + if j != k { + add += grid[i][k]; + } + dp[i][j][k] = dp[i][j][k].max(prev + add); + } + } + } + } + } + } + } + + let mut ans = -1; + for row in &dp[m-1] { + for &v in row { + ans = ans.max(v); + } + } + if ans != -1 { ans } else { 0 } + } +} diff --git a/tests/1001-1500/1463. cherry-pickup-ii/sol.swift b/tests/1001-1500/1463. cherry-pickup-ii/sol.swift new file mode 100644 index 00000000..7e272581 --- /dev/null +++ b/tests/1001-1500/1463. cherry-pickup-ii/sol.swift @@ -0,0 +1,37 @@ +class Solution { + func cherryPickup(_ grid: [[Int]]) -> Int { + let m = grid.count + let n = grid[0].count + var dp = Array(repeating: Array(repeating: Array(repeating: -1, count: n), count: n), count: m) + dp[0][0][n-1] = grid[0][0] + grid[0][n-1] + + for i in 1..= 0 && nj < n && nk >= 0 && nk < n { + let prev = dp[i-1][nj][nk] + if prev != -1 { + var add = grid[i][j] + if j != k { add += grid[i][k] } + dp[i][j][k] = max(dp[i][j][k], prev + add) + } + } + } + } + } + } + } + + var ans = -1 + for row in dp[m-1] { + for v in row { + ans = max(ans, v) + } + } + return ans != -1 ? ans : 0 + } +} diff --git a/tests/1001-1500/1463. cherry-pickup-ii/sol.ts b/tests/1001-1500/1463. cherry-pickup-ii/sol.ts new file mode 100644 index 00000000..863a2599 --- /dev/null +++ b/tests/1001-1500/1463. cherry-pickup-ii/sol.ts @@ -0,0 +1,37 @@ +function cherryPickup(grid: number[][]): number { + const m = grid.length; + const n = grid[0].length; + const dp: number[][][] = Array.from({ length: m }, () => + Array.from({ length: n }, () => Array(n).fill(-1)), + ); + dp[0][0][n - 1] = grid[0][0] + grid[0][n - 1]; + + for (let i = 1; i < m; i++) { + for (let j = 0; j < n; j++) { + for (let k = j + 1; k < n; k++) { + for (let x = -1; x <= 1; x++) { + for (let y = -1; y <= 1; y++) { + const nj = j + x; + const nk = k + y; + if (nj >= 0 && nj < n && nk >= 0 && nk < n) { + const prev = dp[i - 1][nj][nk]; + if (prev !== -1) { + let add = grid[i][j]; + if (j !== k) add += grid[i][k]; + dp[i][j][k] = Math.max(dp[i][j][k], prev + add); + } + } + } + } + } + } + } + + let ans = -1; + for (const row of dp[m - 1]) { + for (const v of row) { + ans = Math.max(ans, v); + } + } + return ans !== -1 ? ans : 0; +} diff --git a/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/manifest.yaml b/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/manifest.yaml new file mode 100644 index 00000000..e64aa2d6 --- /dev/null +++ b/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/manifest.yaml @@ -0,0 +1,1248 @@ +entry: + id: 1464 + title: "maximum-product-of-two-elements-in-an-array" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().maxProduct({nums})" + rust: "Solution::max_product({nums})" + python3: "Solution().maxProduct({nums})" + python2: "Solution().maxProduct({nums})" + ruby: "max_product({nums})" + java: "new Solution().maxProduct({nums})" + csharp: "new Solution().MaxProduct({nums})" + kotlin: "Solution().maxProduct({nums})" + go: "maxProduct({nums})" + dart: "Solution().maxProduct({nums})" + swift: "Solution().maxProduct({nums})" + typescript: "maxProduct({nums})" +judge: + type: exact +limits: + time_ms: 300 + memory_mb: 300 +oracle: + python3: + call: "Checker().maxProduct(nums, {result})" + checker: | + class Checker: + def maxProduct(self, nums, result): + largest = max(nums) + second = max(value for value in nums if value != largest) + if nums.count(largest) >= 2: + second = largest + return result == (largest - 1) * (second - 1) +seed: 1464 +tests: + - name: ex1 + in: + nums: [3, 4, 5, 2] + out: 12 + - name: ex2 + in: + nums: [1, 5, 4, 5] + out: 16 + - name: ex3 + in: + nums: [3, 7] + out: 12 + - name: two_small + in: + nums: [1, 2] + out: 0 + - name: two_large + in: + nums: [999, 1000] + out: 997002 + - name: equal + in: + nums: [5, 5, 5, 5] + out: 16 + - name: ascending + in: + nums: [1, 2, 3, 4, 5] + out: 12 + - name: descending + in: + nums: [5, 4, 3, 2, 1] + out: 12 + - name: repeated_max + in: + nums: [1, 2, 10, 10] + out: 81 + - name: repeated_min + in: + nums: [2, 2, 3, 4] + out: 6 + - name: one_max + in: + nums: [1, 2, 3, 100] + out: 198 + - name: close_values + in: + nums: [98, 99, 100] + out: 9702 + - name: all_one + in: + nums: [1, 1, 1] + out: 0 + - name: all_hundred + in: + nums: [100, 100, 100] + out: 9801 + - name: boundary + in: + nums: [1, 1000, 999, 998] + out: 997002 + - name: generated_uniform_max + seed: 146401 + in: + nums: + gen: "array" + len: 500 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + sorted: false + elemType: "int" + - name: generated_low_values + seed: 146402 + in: + nums: + gen: "array" + len: 500 + of: + gen: "int" + min: 1 + max: 10 + distinct: false + sorted: false + elemType: "int" + - name: generated_high_values + seed: 146403 + in: + nums: + gen: "array" + len: 500 + of: + gen: "int" + min: 990 + max: 1000 + distinct: false + sorted: false + elemType: "int" + - name: generated_midrange_values + seed: 146404 + in: + nums: + gen: "array" + len: 500 + of: + gen: "int" + min: 400 + max: 600 + distinct: false + sorted: false + elemType: "int" + - name: generated_full_range + seed: 146405 + in: + nums: + gen: "array" + len: 500 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + sorted: false + elemType: "int" + - name: length_six + in: + nums: [1, 8, 2, 7, 3, 6] + out: 42 + - name: length_seven + in: + nums: [9, 1, 8, 2, 7, 3, 6] + out: 56 + - name: length_eight + in: + nums: [4, 14, 2, 12, 6, 10, 8, 1] + out: 143 + - name: length_nine + in: + nums: [11, 5, 19, 3, 17, 7, 13, 2, 23] + out: 396 + - name: length_ten + in: + nums: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] + out: 8811 + - name: duplicates_a + in: + nums: [4, 4, 8, 8, 2, 2] + out: 49 + - name: duplicates_b + in: + nums: [12, 12, 11, 11, 1, 1] + out: 121 + - name: duplicates_c + in: + nums: [3, 9, 3, 9, 3, 9] + out: 64 + - name: max_pair + in: + nums: [1000, 1000, 1, 1] + out: 998001 + - name: near_max_pair + in: + nums: [997, 998, 999, 1000] + out: 997002 + - name: balanced_a + in: + nums: [25, 25, 24, 24, 23, 23] + out: 576 + - name: balanced_b + in: + nums: [51, 2, 50, 3, 49, 4] + out: 2450 + - name: patterned_a + in: + nums: [2, 4, 6, 8, 10, 12, 14] + out: 143 + - name: patterned_b + in: + nums: [100, 1, 99, 2, 98, 3, 97] + out: 9702 + - name: final_case + in: + nums: [17, 31, 9, 27, 12, 44, 5] + out: 1290 + - name: minimum_pair_duplicates + in: + nums: [1, 1, 2, 2] + out: 1 + - name: middle_boundary_pair + in: + nums: [250, 251, 252, 253] + out: 63252 + - name: late_maxima + in: + nums: [2, 50, 500, 999, 1000, 1] + out: 997002 + - name: large_ascending_500 + 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, + 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, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 210, + 211, + 212, + 213, + 214, + 215, + 216, + 217, + 218, + 219, + 220, + 221, + 222, + 223, + 224, + 225, + 226, + 227, + 228, + 229, + 230, + 231, + 232, + 233, + 234, + 235, + 236, + 237, + 238, + 239, + 240, + 241, + 242, + 243, + 244, + 245, + 246, + 247, + 248, + 249, + 250, + 251, + 252, + 253, + 254, + 255, + 256, + 257, + 258, + 259, + 260, + 261, + 262, + 263, + 264, + 265, + 266, + 267, + 268, + 269, + 270, + 271, + 272, + 273, + 274, + 275, + 276, + 277, + 278, + 279, + 280, + 281, + 282, + 283, + 284, + 285, + 286, + 287, + 288, + 289, + 290, + 291, + 292, + 293, + 294, + 295, + 296, + 297, + 298, + 299, + 300, + 301, + 302, + 303, + 304, + 305, + 306, + 307, + 308, + 309, + 310, + 311, + 312, + 313, + 314, + 315, + 316, + 317, + 318, + 319, + 320, + 321, + 322, + 323, + 324, + 325, + 326, + 327, + 328, + 329, + 330, + 331, + 332, + 333, + 334, + 335, + 336, + 337, + 338, + 339, + 340, + 341, + 342, + 343, + 344, + 345, + 346, + 347, + 348, + 349, + 350, + 351, + 352, + 353, + 354, + 355, + 356, + 357, + 358, + 359, + 360, + 361, + 362, + 363, + 364, + 365, + 366, + 367, + 368, + 369, + 370, + 371, + 372, + 373, + 374, + 375, + 376, + 377, + 378, + 379, + 380, + 381, + 382, + 383, + 384, + 385, + 386, + 387, + 388, + 389, + 390, + 391, + 392, + 393, + 394, + 395, + 396, + 397, + 398, + 399, + 400, + 401, + 402, + 403, + 404, + 405, + 406, + 407, + 408, + 409, + 410, + 411, + 412, + 413, + 414, + 415, + 416, + 417, + 418, + 419, + 420, + 421, + 422, + 423, + 424, + 425, + 426, + 427, + 428, + 429, + 430, + 431, + 432, + 433, + 434, + 435, + 436, + 437, + 438, + 439, + 440, + 441, + 442, + 443, + 444, + 445, + 446, + 447, + 448, + 449, + 450, + 451, + 452, + 453, + 454, + 455, + 456, + 457, + 458, + 459, + 460, + 461, + 462, + 463, + 464, + 465, + 466, + 467, + 468, + 469, + 470, + 471, + 472, + 473, + 474, + 475, + 476, + 477, + 478, + 479, + 480, + 481, + 482, + 483, + 484, + 485, + 486, + 487, + 488, + 489, + 490, + 491, + 492, + 493, + 494, + 495, + 496, + 497, + 498, + 499, + 500, + ] + out: 248502 + - name: large_extremes_500 + 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, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 999, + 1000, + ] + out: 997002 diff --git a/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.cpp b/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.cpp new file mode 100644 index 00000000..438ef263 --- /dev/null +++ b/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int maxProduct(vector& nums) { + int max1 = 0, max2 = 0; + for (int num : nums) { + if (num > max1) { + max2 = max1; + max1 = num; + } else if (num > max2) { + max2 = num; + } + } + return (max1 - 1) * (max2 - 1); + } +}; diff --git a/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.cs b/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.cs new file mode 100644 index 00000000..160af082 --- /dev/null +++ b/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.cs @@ -0,0 +1,14 @@ +public class Solution { + public int MaxProduct(int[] nums) { + int max1 = 0, max2 = 0; + foreach (int num in nums) { + if (num > max1) { + max2 = max1; + max1 = num; + } else if (num > max2) { + max2 = num; + } + } + return (max1 - 1) * (max2 - 1); + } +} diff --git a/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.dart b/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.dart new file mode 100644 index 00000000..8c221461 --- /dev/null +++ b/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.dart @@ -0,0 +1,14 @@ +class Solution { + int maxProduct(List nums) { + int max1 = 0, max2 = 0; + for (int num in nums) { + if (num > max1) { + max2 = max1; + max1 = num; + } else if (num > max2) { + max2 = num; + } + } + return (max1 - 1) * (max2 - 1); + } +} diff --git a/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.go b/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.go new file mode 100644 index 00000000..d046174a --- /dev/null +++ b/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.go @@ -0,0 +1,12 @@ +func maxProduct(nums []int) int { + max1, max2 := 0, 0 + for _, num := range nums { + if num > max1 { + max2 = max1 + max1 = num + } else if num > max2 { + max2 = num + } + } + return (max1 - 1) * (max2 - 1) +} diff --git a/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.java b/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.java new file mode 100644 index 00000000..7d475a8a --- /dev/null +++ b/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.java @@ -0,0 +1,14 @@ +class Solution { + public int maxProduct(int[] nums) { + int max1 = 0, max2 = 0; + for (int num : nums) { + if (num > max1) { + max2 = max1; + max1 = num; + } else if (num > max2) { + max2 = num; + } + } + return (max1 - 1) * (max2 - 1); + } +} diff --git a/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.kt b/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.kt new file mode 100644 index 00000000..13abbfbb --- /dev/null +++ b/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.kt @@ -0,0 +1,15 @@ +class Solution { + fun maxProduct(nums: IntArray): Int { + var max1 = 0 + var max2 = 0 + for (num in nums) { + if (num > max1) { + max2 = max1 + max1 = num + } else if (num > max2) { + max2 = num + } + } + return (max1 - 1) * (max2 - 1) + } +} diff --git a/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.py b/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.py new file mode 100644 index 00000000..713f91c7 --- /dev/null +++ b/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.py @@ -0,0 +1,12 @@ +class Solution: + def maxProduct(self, nums): + max1, max2 = 0, 0 + + for num in nums: + if num > max1: + max2 = max1 + max1 = num + elif num > max2: + max2 = num + + return (max1 - 1) * (max2 - 1) diff --git a/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.py2 b/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.py2 new file mode 100644 index 00000000..c941cc18 --- /dev/null +++ b/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.py2 @@ -0,0 +1,14 @@ +class Solution(object): + def maxProduct(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + max1, max2 = 0, 0 + for num in nums: + if num > max1: + max2 = max1 + max1 = num + elif num > max2: + max2 = num + return (max1 - 1) * (max2 - 1) diff --git a/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.rb b/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.rb new file mode 100644 index 00000000..507195c6 --- /dev/null +++ b/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.rb @@ -0,0 +1,14 @@ +# @param {Integer[]} nums +# @return {Integer} +def max_product(nums) + max1, max2 = 0, 0 + nums.each do |num| + if num > max1 + max2 = max1 + max1 = num + elsif num > max2 + max2 = num + end + end + (max1 - 1) * (max2 - 1) +end diff --git a/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.rs b/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.rs new file mode 100644 index 00000000..e6c7b2cc --- /dev/null +++ b/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn max_product(nums: Vec) -> i32 { + let mut max1 = 0; + let mut max2 = 0; + for &num in &nums { + if num > max1 { + max2 = max1; + max1 = num; + } else if num > max2 { + max2 = num; + } + } + (max1 - 1) * (max2 - 1) + } +} diff --git a/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.swift b/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.swift new file mode 100644 index 00000000..2e2bc528 --- /dev/null +++ b/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.swift @@ -0,0 +1,15 @@ +class Solution { + func maxProduct(_ nums: [Int]) -> Int { + var max1 = 0 + var max2 = 0 + for num in nums { + if num > max1 { + max2 = max1 + max1 = num + } else if num > max2 { + max2 = num + } + } + return (max1 - 1) * (max2 - 1) + } +} diff --git a/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.ts b/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.ts new file mode 100644 index 00000000..106837cc --- /dev/null +++ b/tests/1001-1500/1464. maximum-product-of-two-elements-in-an-array/sol.ts @@ -0,0 +1,13 @@ +function maxProduct(nums: number[]): number { + let max1 = 0, + max2 = 0; + for (const num of nums) { + if (num > max1) { + max2 = max1; + max1 = num; + } else if (num > max2) { + max2 = num; + } + } + return (max1 - 1) * (max2 - 1); +} diff --git a/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/manifest.yaml b/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/manifest.yaml new file mode 100644 index 00000000..d2be7ead --- /dev/null +++ b/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/manifest.yaml @@ -0,0 +1,332 @@ +entry: + id: 1465 + title: "maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts" + params: + h: + type: int + w: + type: int + horizontalCuts: + type: array + items: + type: int + verticalCuts: + type: array + items: + type: int + call: + cpp: "Solution().maxArea({h}, {w}, {horizontalCuts}, {verticalCuts})" + rust: "Solution::max_area({h}, {w}, {horizontalCuts}, {verticalCuts})" + python3: "Solution().maxArea({h}, {w}, {horizontalCuts}, {verticalCuts})" + python2: "Solution().maxArea({h}, {w}, {horizontalCuts}, {verticalCuts})" + ruby: "max_area({h}, {w}, {horizontalCuts}, {verticalCuts})" + java: "new Solution().maxArea({h}, {w}, {horizontalCuts}, {verticalCuts})" + csharp: "new Solution().MaxArea({h}, {w}, {horizontalCuts}, {verticalCuts})" + kotlin: "Solution().maxArea({h}, {w}, {horizontalCuts}, {verticalCuts})" + go: "maxArea({h}, {w}, {horizontalCuts}, {verticalCuts})" + dart: "Solution().maxArea({h}, {w}, {horizontalCuts}, {verticalCuts})" + swift: "Solution().maxArea({h}, {w}, {horizontalCuts}, {verticalCuts})" + typescript: "maxArea({h}, {w}, {horizontalCuts}, {verticalCuts})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().maxArea(h, w, horizontalCuts, verticalCuts, {result})" + checker: | + class Checker: + def maxArea(self, h, w, horizontalCuts, verticalCuts, result): + hs = [0] + sorted(horizontalCuts) + [h] + vs = [0] + sorted(verticalCuts) + [w] + max_h = max(b - a for a, b in zip(hs, hs[1:])) + max_w = max(b - a for a, b in zip(vs, vs[1:])) + return result == (max_h * max_w) % (10 ** 9 + 7) + +seed: 1465 + +tests: + - name: "example-one" + in: + h: 5 + w: 4 + horizontalCuts: [1, 2, 4] + verticalCuts: [1, 3] + out: 4 + - name: "example-two" + in: + h: 5 + w: 4 + horizontalCuts: [3, 1] + verticalCuts: [1] + out: 6 + - name: "example-three" + in: + h: 5 + w: 4 + horizontalCuts: [3] + verticalCuts: [3] + out: 9 + - name: "minimal-cake" + in: + h: 2 + w: 2 + horizontalCuts: [1] + verticalCuts: [1] + out: 1 + - name: "single-middle-cuts" + in: + h: 10 + w: 10 + horizontalCuts: [5] + verticalCuts: [5] + out: 25 + - name: "edge-cuts" + in: + h: 10 + w: 12 + horizontalCuts: [1, 9] + verticalCuts: [1, 11] + out: 80 + - name: "unsorted-cuts" + in: + h: 20 + w: 15 + horizontalCuts: [14, 2, 9] + verticalCuts: [11, 3, 7] + out: 28 + - name: "equal-spacing" + in: + h: 12 + w: 12 + horizontalCuts: [3, 6, 9] + verticalCuts: [3, 6, 9] + out: 9 + - name: "wide-horizontal-gap" + in: + h: 100 + w: 20 + horizontalCuts: [10, 20, 30, 40] + verticalCuts: [5, 10, 15] + out: 300 + - name: "wide-vertical-gap" + in: + h: 20 + w: 100 + horizontalCuts: [5, 10, 15] + verticalCuts: [10, 20, 30, 40] + out: 300 + - name: "first-gap-largest" + in: + h: 50 + w: 50 + horizontalCuts: [20, 30, 40] + verticalCuts: [20, 30, 40] + out: 400 + - name: "last-gap-largest" + in: + h: 50 + w: 50 + horizontalCuts: [10, 20, 30] + verticalCuts: [10, 20, 30] + out: 400 + - name: "middle-gap-largest" + in: + h: 50 + w: 50 + horizontalCuts: [10, 40] + verticalCuts: [10, 40] + out: 900 + - name: "two-horizontal-cuts" + in: + h: 30 + w: 40 + horizontalCuts: [7, 23] + verticalCuts: [9, 31] + out: 352 + - name: "dense-small-gaps" + in: + h: 25 + w: 30 + horizontalCuts: [1, 2, 3, 4, 5, 6] + verticalCuts: [1, 2, 3, 4, 5, 6] + out: 456 + - name: "dense-near-end" + in: + h: 25 + w: 30 + horizontalCuts: [19, 20, 21, 22, 23] + verticalCuts: [24, 25, 26, 27, 28] + out: 456 + - name: "large-balanced" + in: + h: 1000000000 + w: 1000000000 + horizontalCuts: [250000000, 500000000, 750000000] + verticalCuts: [200000000, 400000000, 600000000, 800000000] + out: 650000007 + - name: "large-single-cuts" + in: + h: 1000000000 + w: 999999999 + horizontalCuts: [1] + verticalCuts: [999999998] + out: 72 + - name: "large-edge-gaps" + in: + h: 999999999 + w: 1000000000 + horizontalCuts: [100, 200, 300] + verticalCuts: [999999700, 999999800] + out: 94556 + - name: "modulo-product" + in: + h: 1000000000 + w: 1000000000 + horizontalCuts: [1] + verticalCuts: [1] + out: 64 + - name: "prime-dimensions" + in: + h: 997 + w: 991 + horizontalCuts: [101, 307, 701] + verticalCuts: [89, 443, 887] + out: 174936 + - name: "seven-by-eight" + in: + h: 7 + w: 8 + horizontalCuts: [1, 3, 6] + verticalCuts: [2, 5] + out: 9 + - name: "many-horizontal" + in: + h: 60 + w: 40 + horizontalCuts: [2, 5, 9, 14, 20, 27, 35, 44, 52] + verticalCuts: [10, 30] + out: 180 + - name: "many-vertical" + in: + h: 40 + w: 60 + horizontalCuts: [10, 30] + verticalCuts: [2, 5, 9, 14, 20, 27, 35, 44, 52] + out: 180 + - name: "alternating-gaps" + in: + h: 100 + w: 100 + horizontalCuts: [1, 50, 51, 99] + verticalCuts: [2, 48, 52, 98] + out: 2254 + - name: "asymmetric-gaps" + in: + h: 73 + w: 86 + horizontalCuts: [12, 13, 60] + verticalCuts: [4, 40, 41, 80] + out: 1833 + - name: "cuts-near-center" + in: + h: 101 + w: 103 + horizontalCuts: [49, 50, 51] + verticalCuts: [50, 51, 52] + out: 2550 + - name: "small-horizontal-large-vertical" + in: + h: 6 + w: 1000 + horizontalCuts: [1, 5] + verticalCuts: [1, 2, 3, 997, 998, 999] + out: 3976 + - name: "large-horizontal-small-vertical" + in: + h: 1000 + w: 6 + horizontalCuts: [1, 2, 3, 997, 998, 999] + verticalCuts: [1, 5] + out: 3976 + - name: "twenty-by-twenty-irregular" + in: + h: 20 + w: 20 + horizontalCuts: [2, 8, 9, 17] + verticalCuts: [1, 7, 15, 19] + out: 64 + - name: "thirty-by-thirty-irregular" + in: + h: 30 + w: 30 + horizontalCuts: [3, 4, 15, 27] + verticalCuts: [2, 10, 11, 28] + out: 204 + - name: "forty-by-fifty" + in: + h: 40 + w: 50 + horizontalCuts: [8, 16, 24, 32] + verticalCuts: [5, 15, 35, 45] + out: 160 + - name: "large-random-gaps" + in: + h: 123456789 + w: 987654321 + horizontalCuts: [123, 456789, 45670000, 90000000] + verticalCuts: [12, 3456789, 40000000, 800000000] + out: 119465720 + - name: "near-complete-horizontal" + in: + h: 15 + w: 17 + horizontalCuts: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] + verticalCuts: [4, 13] + out: 9 + - name: "near-complete-vertical" + in: + h: 17 + w: 15 + horizontalCuts: [4, 13] + verticalCuts: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] + out: 9 + - name: "max-dimensions-staggered" + in: + h: 1000000000 + w: 999999999 + horizontalCuts: [123456789, 234567890, 765432109, 876543210] + verticalCuts: [111111111, 222222222, 777777777, 888888888] + out: 751714604 + - name: "single-horizontal-many-vertical" + in: + h: 999999937 + w: 1000000000 + horizontalCuts: [499999968] + verticalCuts: [1, 250000000, 500000000, 750000000, 999999999] + out: 375000063 + - name: "single-vertical-many-horizontal" + in: + h: 1000000000 + w: 999999929 + horizontalCuts: [1, 200000000, 400000000, 600000000, 800000000, 999999999] + verticalCuts: [499999964] + out: 300000056 + - name: "dense-alternating-small" + in: + h: 101 + w: 103 + horizontalCuts: [1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 100] + verticalCuts: [2, 5, 9, 14, 20, 27, 35, 44, 54, 65, 77, 90, 102] + out: 169 + - name: "large-prime-gap-pattern" + in: + h: 999999893 + w: 999999883 + horizontalCuts: [2, 999999891] + verticalCuts: [3, 999999880] + out: 15340 diff --git a/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.cpp b/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.cpp new file mode 100644 index 00000000..de2a4424 --- /dev/null +++ b/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int maxArea(int h, int w, vector& horizontalCuts, vector& verticalCuts) { + const int MOD = 1'000'000'007; + + sort(horizontalCuts.begin(), horizontalCuts.end()); + sort(verticalCuts.begin(), verticalCuts.end()); + + long long maxH = max(horizontalCuts[0], h - horizontalCuts.back()); + for (int i = 1; i < horizontalCuts.size(); i++) { + maxH = max(maxH, (long long)horizontalCuts[i] - horizontalCuts[i - 1]); + } + + long long maxV = max(verticalCuts[0], w - verticalCuts.back()); + for (int i = 1; i < verticalCuts.size(); i++) { + maxV = max(maxV, (long long)verticalCuts[i] - verticalCuts[i - 1]); + } + + return (int)((maxH * maxV) % MOD); + } +}; diff --git a/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.cs b/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.cs new file mode 100644 index 00000000..f8c71dee --- /dev/null +++ b/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.cs @@ -0,0 +1,20 @@ +public class Solution { + public int MaxArea(int h, int w, int[] horizontalCuts, int[] verticalCuts) { + const int MOD = 1_000_000_007; + + Array.Sort(horizontalCuts); + Array.Sort(verticalCuts); + + long maxH = Math.Max(horizontalCuts[0], h - horizontalCuts[horizontalCuts.Length - 1]); + for (int i = 1; i < horizontalCuts.Length; i++) { + maxH = Math.Max(maxH, horizontalCuts[i] - horizontalCuts[i - 1]); + } + + long maxV = Math.Max(verticalCuts[0], w - verticalCuts[verticalCuts.Length - 1]); + for (int i = 1; i < verticalCuts.Length; i++) { + maxV = Math.Max(maxV, verticalCuts[i] - verticalCuts[i - 1]); + } + + return (int)((maxH * maxV) % MOD); + } +} diff --git a/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.dart b/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.dart new file mode 100644 index 00000000..2e87ccde --- /dev/null +++ b/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.dart @@ -0,0 +1,20 @@ +class Solution { + int maxArea(int h, int w, List horizontalCuts, List verticalCuts) { + const int MOD = 1000000007; + + horizontalCuts.sort(); + verticalCuts.sort(); + + int maxH = max(horizontalCuts[0], h - horizontalCuts.last); + for (int i = 1; i < horizontalCuts.length; i++) { + maxH = max(maxH, horizontalCuts[i] - horizontalCuts[i - 1]); + } + + int maxV = max(verticalCuts[0], w - verticalCuts.last); + for (int i = 1; i < verticalCuts.length; i++) { + maxV = max(maxV, verticalCuts[i] - verticalCuts[i - 1]); + } + + return (maxH * maxV) % MOD; + } +} diff --git a/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.go b/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.go new file mode 100644 index 00000000..75ef4b40 --- /dev/null +++ b/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.go @@ -0,0 +1,18 @@ +func maxArea(h int, w int, horizontalCuts []int, verticalCuts []int) int { + const MOD = 1_000_000_007 + + sort.Ints(horizontalCuts) + sort.Ints(verticalCuts) + + maxH := max(horizontalCuts[0], h - horizontalCuts[len(horizontalCuts)-1]) + for i := 1; i < len(horizontalCuts); i++ { + maxH = max(maxH, horizontalCuts[i] - horizontalCuts[i-1]) + } + + maxV := max(verticalCuts[0], w - verticalCuts[len(verticalCuts)-1]) + for i := 1; i < len(verticalCuts); i++ { + maxV = max(maxV, verticalCuts[i] - verticalCuts[i-1]) + } + + return (maxH * maxV) % MOD +} diff --git a/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.java b/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.java new file mode 100644 index 00000000..f2392b15 --- /dev/null +++ b/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.java @@ -0,0 +1,20 @@ +class Solution { + public int maxArea(int h, int w, int[] horizontalCuts, int[] verticalCuts) { + int MOD = 1_000_000_007; + + Arrays.sort(horizontalCuts); + Arrays.sort(verticalCuts); + + long maxH = Math.max(horizontalCuts[0], h - horizontalCuts[horizontalCuts.length - 1]); + for (int i = 1; i < horizontalCuts.length; i++) { + maxH = Math.max(maxH, horizontalCuts[i] - horizontalCuts[i - 1]); + } + + long maxV = Math.max(verticalCuts[0], w - verticalCuts[verticalCuts.length - 1]); + for (int i = 1; i < verticalCuts.length; i++) { + maxV = Math.max(maxV, verticalCuts[i] - verticalCuts[i - 1]); + } + + return (int)((maxH * maxV) % MOD); + } +} diff --git a/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.kt b/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.kt new file mode 100644 index 00000000..51a365f1 --- /dev/null +++ b/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.kt @@ -0,0 +1,20 @@ +class Solution { + fun maxArea(h: Int, w: Int, horizontalCuts: IntArray, verticalCuts: IntArray): Int { + val MOD = 1_000_000_007 + + horizontalCuts.sort() + verticalCuts.sort() + + var maxH = maxOf(horizontalCuts[0].toLong(), (h - horizontalCuts.last()).toLong()) + for (i in 1 until horizontalCuts.size) { + maxH = maxOf(maxH, (horizontalCuts[i] - horizontalCuts[i - 1]).toLong()) + } + + var maxV = maxOf(verticalCuts[0].toLong(), (w - verticalCuts.last()).toLong()) + for (i in 1 until verticalCuts.size) { + maxV = maxOf(maxV, (verticalCuts[i] - verticalCuts[i - 1]).toLong()) + } + + return ((maxH * maxV) % MOD).toInt() + } +} diff --git a/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.py b/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.py new file mode 100644 index 00000000..cd9e7185 --- /dev/null +++ b/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.py @@ -0,0 +1,24 @@ +class Solution(object): + def maxArea(self, h, w, horizontalCuts, verticalCuts): + """ + :type h: int + :type w: int + :type horizontalCuts: List[int] + :type verticalCuts: List[int] + :rtype: int + """ + MOD = 10**9 + 7 + + horizontalCuts.sort() + verticalCuts.sort() + + # Include the edges in the cut list + max_h = max(horizontalCuts[0], h - horizontalCuts[-1]) + for i in range(1, len(horizontalCuts)): + max_h = max(max_h, horizontalCuts[i] - horizontalCuts[i - 1]) + + max_v = max(verticalCuts[0], w - verticalCuts[-1]) + for i in range(1, len(verticalCuts)): + max_v = max(max_v, verticalCuts[i] - verticalCuts[i - 1]) + + return (max_h * max_v) % MOD diff --git a/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.py2 b/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.py2 new file mode 100644 index 00000000..aab39131 --- /dev/null +++ b/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.py2 @@ -0,0 +1,23 @@ +class Solution(object): + def maxArea(self, h, w, horizontalCuts, verticalCuts): + """ + :type h: int + :type w: int + :type horizontalCuts: List[int] + :type verticalCuts: List[int] + :rtype: int + """ + MOD = 10**9 + 7 + + horizontalCuts.sort() + verticalCuts.sort() + + max_h = max(horizontalCuts[0], h - horizontalCuts[-1]) + for i in range(1, len(horizontalCuts)): + max_h = max(max_h, horizontalCuts[i] - horizontalCuts[i - 1]) + + max_v = max(verticalCuts[0], w - verticalCuts[-1]) + for i in range(1, len(verticalCuts)): + max_v = max(max_v, verticalCuts[i] - verticalCuts[i - 1]) + + return (max_h * max_v) % MOD diff --git a/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.rb b/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.rb new file mode 100644 index 00000000..3f9a5dca --- /dev/null +++ b/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.rb @@ -0,0 +1,23 @@ +# @param {Integer} h +# @param {Integer} w +# @param {Integer[]} horizontal_cuts +# @param {Integer[]} vertical_cuts +# @return {Integer} +def max_area(h, w, horizontal_cuts, vertical_cuts) + mod = 10**9 + 7 + + horizontal_cuts.sort! + vertical_cuts.sort! + + max_h = [horizontal_cuts[0], h - horizontal_cuts[-1]].max + (1...horizontal_cuts.length).each do |i| + max_h = [max_h, horizontal_cuts[i] - horizontal_cuts[i - 1]].max + end + + max_v = [vertical_cuts[0], w - vertical_cuts[-1]].max + (1...vertical_cuts.length).each do |i| + max_v = [max_v, vertical_cuts[i] - vertical_cuts[i - 1]].max + end + + (max_h * max_v) % mod +end diff --git a/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.rs b/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.rs new file mode 100644 index 00000000..c1942a07 --- /dev/null +++ b/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.rs @@ -0,0 +1,20 @@ +impl Solution { + pub fn max_area(h: i32, w: i32, mut horizontal_cuts: Vec, mut vertical_cuts: Vec) -> i32 { + const MOD: i64 = 1_000_000_007; + + horizontal_cuts.sort(); + vertical_cuts.sort(); + + let mut max_h = std::cmp::max(horizontal_cuts[0] as i64, (h - horizontal_cuts[horizontal_cuts.len() - 1]) as i64); + for i in 1..horizontal_cuts.len() { + max_h = std::cmp::max(max_h, (horizontal_cuts[i] - horizontal_cuts[i - 1]) as i64); + } + + let mut max_v = std::cmp::max(vertical_cuts[0] as i64, (w - vertical_cuts[vertical_cuts.len() - 1]) as i64); + for i in 1..vertical_cuts.len() { + max_v = std::cmp::max(max_v, (vertical_cuts[i] - vertical_cuts[i - 1]) as i64); + } + + ((max_h * max_v) % MOD) as i32 + } +} diff --git a/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.swift b/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.swift new file mode 100644 index 00000000..8d65cae1 --- /dev/null +++ b/tests/1001-1500/1465. maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func maxArea(_ h: Int, _ w: Int, _ horizontalCuts: [Int], _ verticalCuts: [Int]) -> Int { + let MOD = 1_000_000_007 + + let horizontalCuts = horizontalCuts.sorted() + let verticalCuts = verticalCuts.sorted() + + var maxH = max(horizontalCuts[0], h - horizontalCuts.last!) + for i in 1.. a - b); + verticalCuts.sort((a, b) => a - b); + + let maxH = Math.max( + horizontalCuts[0], + h - horizontalCuts[horizontalCuts.length - 1], + ); + for (let i = 1; i < horizontalCuts.length; i++) { + maxH = Math.max(maxH, horizontalCuts[i] - horizontalCuts[i - 1]); + } + + let maxV = Math.max( + verticalCuts[0], + w - verticalCuts[verticalCuts.length - 1], + ); + for (let i = 1; i < verticalCuts.length; i++) { + maxV = Math.max(maxV, verticalCuts[i] - verticalCuts[i - 1]); + } + + return Number((BigInt(maxH) * BigInt(maxV)) % BigInt(MOD)); +} diff --git a/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/manifest.yaml b/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/manifest.yaml new file mode 100644 index 00000000..ae7cc6c3 --- /dev/null +++ b/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/manifest.yaml @@ -0,0 +1,726 @@ +entry: + id: 1466 + title: "reorder-routes-to-make-all-paths-lead-to-the-city-zero" + params: + n: + type: int + connections: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().minReorder({n}, {connections})" + rust: "Solution::min_reorder({n}, {connections})" + python3: "Solution().minReorder({n}, {connections})" + python2: "Solution().minReorder({n}, {connections})" + ruby: "min_reorder({n}, {connections})" + java: "new Solution().minReorder({n}, {connections})" + csharp: "new Solution().MinReorder({n}, {connections})" + kotlin: "Solution().minReorder({n}, {connections})" + go: "minReorder({n}, {connections})" + dart: "Solution().minReorder({n}, {connections})" + swift: "Solution().minReorder({n}, {connections})" + typescript: "minReorder({n}, {connections})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().minReorder(n, connections, {result})" + checker: | + class Checker: + def minReorder(self, n, connections, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + graph = [[] for _ in range(n)] + directed = set() + for a, b in connections: + graph[a].append(b) + graph[b].append(a) + directed.add((a, b)) + seen = {0} + stack = [0] + expected = 0 + while stack: + node = stack.pop() + for nxt in graph[node]: + if nxt not in seen: + seen.add(nxt) + expected += int((node, nxt) in directed) + stack.append(nxt) + return len(seen) == n and result == expected + +seed: 1466 + +tests: + - name: "example_one" + in: + n: 6 + connections: + elemType: "int" + value: + - [0, 1] + - [1, 3] + - [2, 3] + - [4, 0] + - [4, 5] + out: 3 + - name: "example_two" + in: + n: 5 + connections: + elemType: "int" + value: + - [1, 0] + - [1, 2] + - [3, 2] + - [3, 4] + out: 2 + - name: "example_three" + in: + n: 3 + connections: + elemType: "int" + value: + - [1, 0] + - [2, 0] + out: 0 + - name: "two_nodes_correct" + in: + n: 2 + connections: + elemType: "int" + value: + - [1, 0] + out: 0 + - name: "two_nodes_reverse" + in: + n: 2 + connections: + elemType: "int" + value: + - [0, 1] + out: 1 + - name: "star_all_inward" + in: + n: 7 + connections: + elemType: "int" + value: + - [1, 0] + - [2, 0] + - [3, 0] + - [4, 0] + - [5, 0] + - [6, 0] + out: 0 + - name: "star_all_outward" + in: + n: 7 + connections: + elemType: "int" + value: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [0, 5] + - [0, 6] + out: 6 + - name: "chain_inward" + in: + n: 6 + connections: + elemType: "int" + value: + - [1, 0] + - [2, 1] + - [3, 2] + - [4, 3] + - [5, 4] + out: 0 + - name: "chain_outward" + in: + n: 6 + connections: + elemType: "int" + value: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + out: 5 + - name: "chain_alternating" + in: + n: 9 + connections: + elemType: "int" + value: + - [0, 1] + - [2, 1] + - [2, 3] + - [4, 3] + - [4, 5] + - [6, 5] + - [6, 7] + - [8, 7] + out: 4 + - name: "branching_inward" + in: + n: 8 + connections: + elemType: "int" + value: + - [1, 0] + - [2, 0] + - [3, 1] + - [4, 1] + - [5, 2] + - [6, 2] + - [7, 5] + out: 0 + - name: "branching_outward" + in: + n: 8 + connections: + elemType: "int" + value: + - [0, 1] + - [0, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [2, 6] + - [5, 7] + out: 7 + - name: "mixed_small_tree" + in: + n: 7 + connections: + elemType: "int" + value: + - [1, 0] + - [0, 2] + - [3, 1] + - [1, 4] + - [5, 2] + - [6, 5] + out: 2 + - name: "mixed_balanced_tree" + in: + n: 15 + connections: + elemType: "int" + value: + - [0, 1] + - [2, 0] + - [3, 1] + - [1, 4] + - [5, 2] + - [2, 6] + - [7, 3] + - [4, 8] + - [9, 4] + - [5, 10] + - [11, 5] + - [6, 12] + - [13, 6] + - [14, 7] + out: 6 + - name: "root_with_long_tail" + in: + n: 10 + connections: + elemType: "int" + value: + - [0, 1] + - [2, 1] + - [2, 3] + - [4, 3] + - [5, 4] + - [5, 6] + - [7, 6] + - [8, 7] + - [9, 8] + out: 3 + - name: "edge_order_irrelevant" + in: + n: 6 + connections: + elemType: "int" + value: + - [4, 5] + - [2, 3] + - [0, 1] + - [4, 0] + - [1, 3] + out: 3 + - name: "deep_left_branch" + in: + n: 12 + connections: + elemType: "int" + value: + - [1, 0] + - [0, 2] + - [3, 1] + - [4, 3] + - [5, 4] + - [6, 5] + - [7, 6] + - [8, 7] + - [9, 8] + - [10, 9] + - [11, 10] + out: 1 + - name: "deep_right_branch" + in: + n: 12 + connections: + elemType: "int" + value: + - [0, 1] + - [1, 2] + - [3, 2] + - [3, 4] + - [5, 4] + - [5, 6] + - [7, 6] + - [7, 8] + - [9, 8] + - [9, 10] + - [11, 10] + out: 6 + - name: "ten_node_star_mixed" + in: + n: 10 + connections: + elemType: "int" + value: + - [1, 0] + - [0, 2] + - [3, 0] + - [4, 0] + - [0, 5] + - [6, 0] + - [0, 7] + - [8, 0] + - [9, 0] + out: 3 + - name: "fourteen_node_chain_mixed" + in: + n: 14 + connections: + elemType: "int" + value: + - [0, 1] + - [2, 1] + - [2, 3] + - [4, 3] + - [4, 5] + - [6, 5] + - [6, 7] + - [8, 7] + - [8, 9] + - [10, 9] + - [10, 11] + - [12, 11] + - [12, 13] + out: 7 + - name: "fifteen_node_three_branches" + in: + n: 15 + connections: + elemType: "int" + value: + - [1, 0] + - [0, 2] + - [3, 1] + - [4, 1] + - [5, 2] + - [2, 6] + - [7, 3] + - [8, 3] + - [9, 5] + - [10, 6] + - [6, 11] + - [12, 7] + - [13, 10] + - [14, 11] + out: 3 + - name: "twenty_node_chain" + in: + n: 20 + connections: + elemType: "int" + value: + - [0, 1] + - [1, 2] + - [3, 2] + - [3, 4] + - [5, 4] + - [5, 6] + - [7, 6] + - [7, 8] + - [9, 8] + - [9, 10] + - [11, 10] + - [11, 12] + - [13, 12] + - [13, 14] + - [15, 14] + - [15, 16] + - [17, 16] + - [17, 18] + - [19, 18] + out: 10 + - name: "twenty_node_star" + in: + n: 20 + connections: + elemType: "int" + value: + - [0, 1] + - [2, 0] + - [0, 3] + - [4, 0] + - [0, 5] + - [6, 0] + - [0, 7] + - [8, 0] + - [0, 9] + - [10, 0] + - [0, 11] + - [12, 0] + - [0, 13] + - [14, 0] + - [0, 15] + - [16, 0] + - [0, 17] + - [18, 0] + - [0, 19] + out: 10 + - name: "twentyfive_balanced" + in: + n: 25 + connections: + elemType: "int" + value: + - [1, 0] + - [0, 2] + - [3, 1] + - [1, 4] + - [5, 2] + - [2, 6] + - [7, 3] + - [3, 8] + - [9, 4] + - [4, 10] + - [11, 5] + - [5, 12] + - [13, 6] + - [6, 14] + - [15, 7] + - [7, 16] + - [17, 8] + - [8, 18] + - [19, 9] + - [9, 20] + - [21, 10] + - [10, 22] + - [23, 11] + - [11, 24] + out: 12 + - name: "three_node_one_reversal" + in: + n: 3 + connections: + elemType: "int" + value: + - [0, 1] + - [2, 1] + out: 1 + - name: "four_node_path" + in: + n: 4 + connections: + elemType: "int" + value: + - [1, 0] + - [1, 2] + - [3, 2] + out: 1 + - name: "five_node_star_mixed" + in: + n: 5 + connections: + elemType: "int" + value: + - [0, 1] + - [2, 0] + - [0, 3] + - [4, 0] + out: 2 + - name: "six_node_branch" + in: + n: 6 + connections: + elemType: "int" + value: + - [1, 0] + - [0, 2] + - [3, 1] + - [4, 1] + - [5, 2] + out: 1 + - name: "seven_node_binary" + in: + n: 7 + connections: + elemType: "int" + value: + - [0, 1] + - [2, 0] + - [3, 1] + - [1, 4] + - [5, 2] + - [2, 6] + out: 3 + - name: "eight_node_path" + in: + n: 8 + connections: + elemType: "int" + value: + - [1, 0] + - [1, 2] + - [3, 2] + - [3, 4] + - [5, 4] + - [5, 6] + - [7, 6] + out: 3 + - name: "nine_node_hub_and_tail" + in: + n: 9 + connections: + elemType: "int" + value: + - [0, 1] + - [2, 0] + - [0, 3] + - [4, 3] + - [3, 5] + - [6, 5] + - [5, 7] + - [8, 7] + out: 4 + - name: "eleven_node_two_hubs" + in: + n: 11 + connections: + elemType: "int" + value: + - [1, 0] + - [2, 0] + - [0, 3] + - [4, 1] + - [1, 5] + - [6, 2] + - [2, 7] + - [8, 3] + - [3, 9] + - [10, 9] + out: 4 + - name: "thirteen_node_comb" + in: + n: 13 + connections: + elemType: "int" + value: + - [0, 1] + - [2, 1] + - [1, 3] + - [4, 1] + - [5, 3] + - [3, 6] + - [7, 6] + - [6, 8] + - [9, 8] + - [8, 10] + - [11, 10] + - [10, 12] + out: 6 + - name: "sixteen_node_chain" + in: + n: 16 + connections: + elemType: "int" + value: + - [0, 1] + - [2, 1] + - [2, 3] + - [4, 3] + - [4, 5] + - [6, 5] + - [6, 7] + - [8, 7] + - [8, 9] + - [10, 9] + - [10, 11] + - [12, 11] + - [12, 13] + - [14, 13] + - [14, 15] + out: 8 + - name: "eighteen_node_star_mixed" + in: + n: 18 + connections: + elemType: "int" + value: + - [1, 0] + - [0, 2] + - [3, 0] + - [4, 0] + - [0, 5] + - [6, 0] + - [0, 7] + - [8, 0] + - [9, 0] + - [0, 10] + - [11, 0] + - [0, 12] + - [13, 0] + - [0, 14] + - [15, 0] + - [0, 16] + - [17, 0] + out: 7 + - name: "thirty_node_balanced" + in: + n: 30 + connections: + elemType: "int" + value: + - [0, 1] + - [2, 0] + - [3, 1] + - [1, 4] + - [5, 2] + - [2, 6] + - [7, 3] + - [3, 8] + - [9, 4] + - [4, 10] + - [11, 5] + - [5, 12] + - [13, 6] + - [6, 14] + - [15, 7] + - [7, 16] + - [17, 8] + - [8, 18] + - [19, 9] + - [9, 20] + - [21, 10] + - [10, 22] + - [23, 11] + - [11, 24] + - [25, 12] + - [12, 26] + - [27, 13] + - [13, 28] + - [29, 14] + out: 14 + - name: "forty_node_directed_outward" + in: + n: 40 + connections: + elemType: "int" + value: + - [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] + - [0, 20] + - [0, 21] + - [0, 22] + - [0, 23] + - [0, 24] + - [0, 25] + - [0, 26] + - [0, 27] + - [0, 28] + - [0, 29] + - [0, 30] + - [0, 31] + - [0, 32] + - [0, 33] + - [0, 34] + - [0, 35] + - [0, 36] + - [0, 37] + - [0, 38] + - [0, 39] + out: 39 + - name: "three_node_all_outward" + in: + n: 3 + connections: + elemType: "int" + value: + - [0, 1] + - [1, 2] + out: 2 + - name: "six_node_two_branch_mixed" + in: + n: 6 + connections: + elemType: "int" + value: + - [1, 0] + - [0, 2] + - [3, 1] + - [4, 3] + - [5, 2] + out: 1 + - name: "ten_node_all_inward" + in: + n: 10 + connections: + elemType: "int" + value: + - [1, 0] + - [2, 1] + - [3, 1] + - [4, 2] + - [5, 2] + - [6, 3] + - [7, 3] + - [8, 4] + - [9, 4] + out: 0 diff --git a/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.cpp b/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.cpp new file mode 100644 index 00000000..03660828 --- /dev/null +++ b/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + int minReorder(int n, vector>& connections) { + unordered_set roads; + vector> graph(n); + for (auto& conn : connections) { + int x = conn[0], y = conn[1]; + graph[x].push_back(y); + graph[y].push_back(x); + roads.insert(to_string(x) + "," + to_string(y)); + } + + vector seen(n, false); + seen[0] = true; + + function dfs = [&](int node) -> int { + int ans = 0; + for (int neighbor : graph[node]) { + if (!seen[neighbor]) { + if (roads.count(to_string(node) + "," + to_string(neighbor))) { + ans++; + } + seen[neighbor] = true; + ans += dfs(neighbor); + } + } + return ans; + }; + + return dfs(0); + } +}; diff --git a/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.cs b/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.cs new file mode 100644 index 00000000..b6b53082 --- /dev/null +++ b/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.cs @@ -0,0 +1,34 @@ +public class Solution { + public int MinReorder(int n, int[][] connections) { + HashSet roads = new HashSet(); + List[] graph = new List[n]; + for (int i = 0; i < n; i++) { + graph[i] = new List(); + } + foreach (var conn in connections) { + int x = conn[0], y = conn[1]; + graph[x].Add(y); + graph[y].Add(x); + roads.Add($"{x},{y}"); + } + + bool[] seen = new bool[n]; + seen[0] = true; + + int Dfs(int node) { + int ans = 0; + foreach (int neighbor in graph[node]) { + if (!seen[neighbor]) { + if (roads.Contains($"{node},{neighbor}")) { + ans++; + } + seen[neighbor] = true; + ans += Dfs(neighbor); + } + } + return ans; + } + + return Dfs(0); + } +} diff --git a/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.dart b/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.dart new file mode 100644 index 00000000..674c787a --- /dev/null +++ b/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.dart @@ -0,0 +1,31 @@ +class Solution { + int minReorder(int n, List> connections) { + Set roads = {}; + List> graph = List.generate(n, (_) => []); + for (var conn in connections) { + int x = conn[0], y = conn[1]; + graph[x].add(y); + graph[y].add(x); + roads.add('$x,$y'); + } + + List seen = List.filled(n, false); + seen[0] = true; + + int dfs(int node) { + int ans = 0; + for (int neighbor in graph[node]) { + if (!seen[neighbor]) { + if (roads.contains('$node,$neighbor')) { + ans++; + } + seen[neighbor] = true; + ans += dfs(neighbor); + } + } + return ans; + } + + return dfs(0); + } +} diff --git a/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.go b/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.go new file mode 100644 index 00000000..5da438d1 --- /dev/null +++ b/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.go @@ -0,0 +1,34 @@ +func minReorder(n int, connections [][]int) int { + roads := make(map[string]bool) + graph := make([][]int, n) + for i := 0; i < n; i++ { + graph[i] = []int{} + } + for _, conn := range connections { + x, y := conn[0], conn[1] + graph[x] = append(graph[x], y) + graph[y] = append(graph[y], x) + key := fmt.Sprintf("%d,%d", x, y) + roads[key] = true + } + + seen := make([]bool, n) + seen[0] = true + var dfs func(int) int + dfs = func(node int) int { + ans := 0 + for _, neighbor := range graph[node] { + if !seen[neighbor] { + key := fmt.Sprintf("%d,%d", node, neighbor) + if roads[key] { + ans++ + } + seen[neighbor] = true + ans += dfs(neighbor) + } + } + return ans + } + + return dfs(0) +} diff --git a/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.java b/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.java new file mode 100644 index 00000000..fa03ab38 --- /dev/null +++ b/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.java @@ -0,0 +1,38 @@ +import java.util.ArrayDeque; +import java.util.ArrayList; + +class Solution { + public int minReorder(int n, int[][] connections) { + ArrayList> graph = new ArrayList<>(); + for (int i = 0; i < n; i++) { + graph.add(new ArrayList<>()); + } + + for (int[] connection : connections) { + int from = connection[0]; + int to = connection[1]; + graph.get(from).add(new int[] {to, 1}); + graph.get(to).add(new int[] {from, 0}); + } + + boolean[] seen = new boolean[n]; + ArrayDeque stack = new ArrayDeque<>(); + stack.push(0); + seen[0] = true; + int changes = 0; + + while (!stack.isEmpty()) { + int city = stack.pop(); + for (int[] edge : graph.get(city)) { + int next = edge[0]; + if (!seen[next]) { + seen[next] = true; + changes += edge[1]; + stack.push(next); + } + } + } + + return changes; + } +} diff --git a/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.kt b/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.kt new file mode 100644 index 00000000..07451fae --- /dev/null +++ b/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.kt @@ -0,0 +1,29 @@ +class Solution { + fun minReorder(n: Int, connections: Array): Int { + val roads = HashSet() + val graph = Array(n) { mutableListOf() } + for ((x, y) in connections) { + graph[x].add(y) + graph[y].add(x) + roads.add("$x,$y") + } + + val seen = BooleanArray(n) + seen[0] = true + fun dfs(node: Int): Int { + var ans = 0 + for (neighbor in graph[node]) { + if (!seen[neighbor]) { + if (roads.contains("$node,$neighbor")) { + ans++ + } + seen[neighbor] = true + ans += dfs(neighbor) + } + } + return ans + } + + return dfs(0) + } +} diff --git a/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.py b/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.py new file mode 100644 index 00000000..917af254 --- /dev/null +++ b/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.py @@ -0,0 +1,25 @@ +from collections import defaultdict +from typing import List + + +class Solution: + def minReorder(self, n: int, connections: List[List[int]]) -> int: + roads = set() + graph = defaultdict(list) + for x, y in connections: + graph[x].append(y) + graph[y].append(x) + roads.add((x, y)) + + def dfs(node): + ans = 0 + for neighbor in graph[node]: + if neighbor not in seen: + if (node, neighbor) in roads: # This is the edge + ans += 1 + seen.add(neighbor) + ans += dfs(neighbor) + return ans + + seen = {0} + return dfs(0) diff --git a/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.py2 b/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.py2 new file mode 100644 index 00000000..5740596f --- /dev/null +++ b/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.py2 @@ -0,0 +1,28 @@ +class Solution(object): + def minReorder(self, n, connections): + """ + :type n: int + :type connections: List[List[int]] + :rtype: int + """ + roads = set() + graph = {} + for i in range(n): + graph[i] = [] + for x, y in connections: + graph[x].append(y) + graph[y].append(x) + roads.add((x, y)) + + seen = {0} + def dfs(node): + ans = 0 + for neighbor in graph[node]: + if neighbor not in seen: + if (node, neighbor) in roads: + ans += 1 + seen.add(neighbor) + ans += dfs(neighbor) + return ans + + return dfs(0) diff --git a/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.rb b/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.rb new file mode 100644 index 00000000..cc8986ee --- /dev/null +++ b/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.rb @@ -0,0 +1,27 @@ +# @param {Integer} n +# @param {Integer[][]} connections +# @return {Integer} +def min_reorder(n, connections) + roads = Set.new + graph = Hash.new { |h, k| h[k] = [] } + connections.each do |x, y| + graph[x] << y + graph[y] << x + roads.add([x, y]) + end + + seen = Set.new([0]) + dfs = lambda do |node| + ans = 0 + graph[node].each do |neighbor| + unless seen.include?(neighbor) + ans += 1 if roads.include?([node, neighbor]) + seen.add(neighbor) + ans += dfs.call(neighbor) + end + end + ans + end + + dfs.call(0) +end diff --git a/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.rs b/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.rs new file mode 100644 index 00000000..4449ae47 --- /dev/null +++ b/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.rs @@ -0,0 +1,34 @@ +impl Solution { + pub fn min_reorder(n: i32, connections: Vec>) -> i32 { + use std::collections::HashSet; + let n = n as usize; + let mut roads: HashSet<(i32, i32)> = HashSet::new(); + let mut graph: Vec> = vec![vec![]; n]; + for conn in &connections { + let x = conn[0]; + let y = conn[1]; + graph[x as usize].push(y); + graph[y as usize].push(x); + roads.insert((x, y)); + } + + let mut seen = vec![false; n]; + seen[0] = true; + + fn dfs(node: i32, graph: &Vec>, roads: &HashSet<(i32, i32)>, seen: &mut Vec) -> i32 { + let mut ans = 0; + for &neighbor in &graph[node as usize] { + if !seen[neighbor as usize] { + if roads.contains(&(node, neighbor)) { + ans += 1; + } + seen[neighbor as usize] = true; + ans += dfs(neighbor, graph, roads, seen); + } + } + ans + } + + dfs(0, &graph, &roads, &mut seen) + } +} diff --git a/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.swift b/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.swift new file mode 100644 index 00000000..773d4894 --- /dev/null +++ b/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.swift @@ -0,0 +1,31 @@ +class Solution { + func minReorder(_ n: Int, _ connections: [[Int]]) -> Int { + var roads = Set() + var graph = Array(repeating: [Int](), count: n) + for conn in connections { + let x = conn[0], y = conn[1] + graph[x].append(y) + graph[y].append(x) + roads.insert("\(x),\(y)") + } + + var seen = Array(repeating: false, count: n) + seen[0] = true + + func dfs(_ node: Int) -> Int { + var ans = 0 + for neighbor in graph[node] { + if !seen[neighbor] { + if roads.contains("\(node),\(neighbor)") { + ans += 1 + } + seen[neighbor] = true + ans += dfs(neighbor) + } + } + return ans + } + + return dfs(0) + } +} diff --git a/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.ts b/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.ts new file mode 100644 index 00000000..1dc8dfc0 --- /dev/null +++ b/tests/1001-1500/1466. reorder-routes-to-make-all-paths-lead-to-the-city-zero/sol.ts @@ -0,0 +1,28 @@ +function minReorder(n: number, connections: number[][]): number { + const roads = new Set(); + const graph: number[][] = Array.from({ length: n }, () => []); + for (const [x, y] of connections) { + graph[x].push(y); + graph[y].push(x); + roads.add(`${x},${y}`); + } + + const seen: boolean[] = new Array(n).fill(false); + seen[0] = true; + + function dfs(node: number): number { + let ans = 0; + for (const neighbor of graph[node]) { + if (!seen[neighbor]) { + if (roads.has(`${node},${neighbor}`)) { + ans++; + } + seen[neighbor] = true; + ans += dfs(neighbor); + } + } + return ans; + } + + return dfs(0); +} diff --git a/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/manifest.yaml b/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/manifest.yaml new file mode 100644 index 00000000..8b7c81e5 --- /dev/null +++ b/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/manifest.yaml @@ -0,0 +1,172 @@ +entry: + id: 1467 + title: "probability-of-a-two-boxes-having-the-same-number-of-distinct-balls" + params: + balls: + type: array + items: + type: int + call: + cpp: "Solution().getProbability({balls})" + rust: "Solution::get_probability({balls})" + python3: "Solution().getProbability({balls})" + python2: "Solution().getProbability({balls})" + ruby: "get_probability({balls})" + java: "new Solution().getProbability({balls})" + csharp: "new Solution().GetProbability({balls})" + kotlin: "Solution().getProbability({balls})" + go: "getProbability({balls})" + dart: "Solution().getProbability({balls})" + swift: "Solution().getProbability({balls})" + typescript: "getProbability({balls})" +judge: + type: exact +limits: + time_ms: 1000 + memory_mb: 300 +oracle: + python3: + call: "Checker().getProbability(balls, {result})" + checker: | + from itertools import product + from math import comb, isfinite + class Checker: + def getProbability(self, balls, result): + if isinstance(result, bool) or not isinstance(result, (int, float)) or not isfinite(result): + return False + half = sum(balls) // 2 + total = comb(sum(balls), half) + good = 0 + for allocation in product(*[range(count + 1) for count in balls]): + if sum(allocation) != half: + continue + left = sum(value > 0 for value in allocation) + right = sum(value < count for value, count in zip(allocation, balls)) + if left == right: + ways = 1 + for count, value in zip(balls, allocation): + ways *= comb(count, value) + good += ways + return abs(result - good / total) <= 1e-5 +seed: 1467 +tests: + - name: ex1 + in: + balls: [1, 1] + - name: ex2 + in: + balls: [2, 1, 1] + - name: ex3 + in: + balls: [1, 2, 1, 2] + - name: four_single_colors + in: + balls: [1, 1, 1, 1] + - name: six_single_colors + in: + balls: [1, 1, 1, 1, 1, 1] + - name: eight_single_colors + in: + balls: [1, 1, 1, 1, 1, 1, 1, 1] + - name: one_color_two + in: + balls: [2] + - name: one_color_four + in: + balls: [4] + - name: one_color_six + in: + balls: [6] + - name: two_colors_two_each + in: + balls: [2, 2] + - name: three_colors_two_each + in: + balls: [2, 2, 2] + - name: four_colors_two_each + in: + balls: [2, 2, 2, 2] + - name: six_colors_two_each + in: + balls: [2, 2, 2, 2, 2, 2] + - name: two_colors_three_each + in: + balls: [3, 3] + - name: three_three_two + in: + balls: [3, 3, 2] + - name: four_colors_three_each + in: + balls: [3, 3, 3, 3] + - name: four_two + in: + balls: [4, 2] + - name: two_colors_four_each + in: + balls: [4, 4] + - name: six_two + in: + balls: [6, 2] + - name: two_colors_six_each + in: + balls: [6, 6] + - name: three_one_two + in: + balls: [3, 1, 2] + - name: three_two_one + in: + balls: [3, 2, 1] + - name: four_one_one + in: + balls: [4, 1, 1] + - name: five_one_one_one + in: + balls: [5, 1, 1, 1] + - name: six_one_one + in: + balls: [6, 1, 1] + - name: six_two_two + in: + balls: [6, 2, 2] + - name: four_three_one + in: + balls: [4, 3, 1] + - name: four_two_two + in: + balls: [4, 2, 2] + - name: five_three_two + in: + balls: [5, 3, 2] + - name: four_four_two + in: + balls: [4, 4, 2] + - name: three_three_two_two + in: + balls: [3, 3, 2, 2] + - name: five_colors_two_each + in: + balls: [2, 2, 2, 2, 2] + - name: six_two_two_two + in: + balls: [6, 2, 2, 2] + - name: four_three_three_two + in: + balls: [4, 3, 3, 2] + - name: five_three_two_two_two + in: + balls: [5, 3, 2, 2, 2] + - name: four_colors_four_each + in: + balls: [4, 4, 4, 4] + - name: four_three_three_three_two_two + in: + balls: [3, 3, 3, 3, 2, 2] + - name: maximum_all_colors + in: + balls: [6, 6, 6, 6, 6, 6, 6, 6] + - name: one_one_two_two + in: + balls: [1, 1, 2, 2] + - name: two_one_two_one + in: + balls: [2, 1, 2, 1] diff --git a/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.cpp b/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.cpp new file mode 100644 index 00000000..fba04cb7 --- /dev/null +++ b/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.cpp @@ -0,0 +1,41 @@ +class Solution { +public: + double getProbability(vector& balls) { + int sm = 0; + for (int b : balls) sm += b; + + const int half = sm / 2; + long long choose[49][49] = {}; + for (int n = 0; n <= 48; ++n) { + choose[n][0] = choose[n][n] = 1; + for (int k = 1; k < n; ++k) { + choose[n][k] = choose[n - 1][k - 1] + choose[n - 1][k]; + } + } + + const int k = static_cast(balls.size()); + vector memo((k + 1) * (half + 1) * (k + 1) * (k + 1), -1); + auto index = [=](int color, int used, int distinct0, int distinct1) { + return (((color * (half + 1) + used) * (k + 1) + distinct0) * (k + 1) + distinct1); + }; + function dp = [&](int color, int used, int distinct0, int distinct1) -> long long { + if (used > half) return 0; + long long& cached = memo[index(color, used, distinct0, distinct1)]; + if (cached != -1) return cached; + if (color == k) return cached = (used == half && distinct0 == distinct1); + + cached = 0; + for (int first = 0; first <= balls[color]; ++first) { + cached += choose[balls[color]][first] * + dp(color + 1, used + first, + distinct0 + (first > 0), + distinct1 + (first < balls[color])); + } + return cached; + }; + + long long favorable = dp(0, 0, 0, 0); + long long total = choose[sm][half]; + return (double)favorable / total; + } +}; diff --git a/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.cs b/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.cs new file mode 100644 index 00000000..8eb4360e --- /dev/null +++ b/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.cs @@ -0,0 +1,41 @@ +public class Solution { + public double GetProbability(int[] balls) { + int sm = 0; + foreach (int b in balls) sm += b; + + int half = sm / 2; + long[,] choose = new long[49, 49]; + for (int n = 0; n <= 48; n++) { + choose[n, 0] = choose[n, n] = 1; + for (int k = 1; k < n; k++) { + choose[n, k] = choose[n - 1, k - 1] + choose[n - 1, k]; + } + } + + var memo = new Dictionary<(int color, int used, int distinct0, int distinct1), long>(); + long dp(int color, int used, int distinct0, int distinct1) { + if (used > half) return 0; + var key = (color, used, distinct0, distinct1); + if (memo.TryGetValue(key, out long cached)) return cached; + if (color == balls.Length) { + long result = used == half && distinct0 == distinct1 ? 1 : 0; + memo[key] = result; + return result; + } + + long resultForState = 0; + for (int first = 0; first <= balls[color]; first++) { + resultForState += choose[balls[color], first] * + dp(color + 1, used + first, + distinct0 + (first > 0 ? 1 : 0), + distinct1 + (first < balls[color] ? 1 : 0)); + } + memo[key] = resultForState; + return resultForState; + } + + long favorable = dp(0, 0, 0, 0); + long total = choose[sm, half]; + return (double)favorable / total; + } +} diff --git a/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.dart b/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.dart new file mode 100644 index 00000000..a3c5ae4a --- /dev/null +++ b/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.dart @@ -0,0 +1,59 @@ +import 'dart:collection'; + +class Solution { + double getProbability(List balls) { + int sm = balls.fold(0, (a, b) => a + b); + List expanded = []; + for (int i = 0; i < balls.length; i++) { + for (int j = 0; j < balls[i]; j++) { + expanded.add(i); + } + } + + Map memo = HashMap(); + + int dp(int i, int cnt0, int mask0, int mask1) { + String key = '$i,$cnt0,$mask0,$mask1'; + if (memo.containsKey(key)) return memo[key]!; + + int cnt1 = i - cnt0; + if (cnt0 > sm ~/ 2 || cnt1 > sm ~/ 2) { + memo[key] = 0; + return 0; + } + + if (i == expanded.length) { + int result = popCount(mask0) == popCount(mask1) ? 1 : 0; + memo[key] = result; + return result; + } + + int result = dp(i + 1, cnt0 + 1, mask0 | (1 << expanded[i]), mask1) + + dp(i + 1, cnt0, mask0, mask1 | (1 << expanded[i])); + memo[key] = result; + return result; + } + + int favorable = dp(0, 0, 0, 0); + int total = comb(sm, sm ~/ 2); + return favorable / total; + } + + int popCount(int n) { + int count = 0; + while (n != 0) { + count += n & 1; + n >>= 1; + } + return count; + } + + int comb(int n, int k) { + if (k > n) return 0; + int res = 1; + for (int i = 1; i <= k; i++) { + res = res * (n - k + i) ~/ i; + } + return res; + } +} diff --git a/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.go b/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.go new file mode 100644 index 00000000..05a98d74 --- /dev/null +++ b/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.go @@ -0,0 +1,67 @@ +func getProbability(balls []int) float64 { + colors := len(balls) + total := 0 + for _, count := range balls { + total += count + } + half := total / 2 + + dp := make([][][]int64, half+1) + for used := 0; used <= half; used++ { + dp[used] = make([][]int64, colors+1) + for left := 0; left <= colors; left++ { + dp[used][left] = make([]int64, colors+1) + } + } + dp[0][0][0] = 1 + + for _, count := range balls { + next := make([][][]int64, half+1) + for used := 0; used <= half; used++ { + next[used] = make([][]int64, colors+1) + for left := 0; left <= colors; left++ { + next[used][left] = make([]int64, colors+1) + } + } + for used := 0; used <= half; used++ { + for left := 0; left <= colors; left++ { + for right := 0; right <= colors; right++ { + ways := dp[used][left][right] + if ways == 0 { + continue + } + for inLeft := 0; inLeft <= count && used+inLeft <= half; inLeft++ { + nextLeft := left + if inLeft > 0 { + nextLeft++ + } + nextRight := right + if inLeft < count { + nextRight++ + } + next[used+inLeft][nextLeft][nextRight] += + ways * choose(count, inLeft) + } + } + } + } + dp = next + } + + var favorable int64 + for distinct := 0; distinct <= colors; distinct++ { + favorable += dp[half][distinct][distinct] + } + return float64(favorable) / float64(choose(total, half)) +} + +func choose(n, k int) int64 { + if k > n-k { + k = n - k + } + result := int64(1) + for i := 1; i <= k; i++ { + result = result * int64(n-k+i) / int64(i) + } + return result +} diff --git a/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.java b/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.java new file mode 100644 index 00000000..066ca4bf --- /dev/null +++ b/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.java @@ -0,0 +1,45 @@ +class Solution { + public double getProbability(int[] balls) { + int colors = balls.length; + int total = 0; + for (int count : balls) total += count; + int half = total / 2; + + long[][][] dp = new long[half + 1][colors + 1][colors + 1]; + dp[0][0][0] = 1; + + for (int count : balls) { + long[][][] next = new long[half + 1][colors + 1][colors + 1]; + for (int used = 0; used <= half; used++) { + for (int left = 0; left <= colors; left++) { + for (int right = 0; right <= colors; right++) { + long ways = dp[used][left][right]; + if (ways == 0) continue; + for (int inLeft = 0; inLeft <= count && used + inLeft <= half; inLeft++) { + int nextLeft = left + (inLeft > 0 ? 1 : 0); + int nextRight = right + (inLeft < count ? 1 : 0); + next[used + inLeft][nextLeft][nextRight] += + ways * choose(count, inLeft); + } + } + } + } + dp = next; + } + + long favorable = 0; + for (int distinct = 0; distinct <= colors; distinct++) { + favorable += dp[half][distinct][distinct]; + } + return (double) favorable / choose(total, half); + } + + private long choose(int n, int k) { + if (k > n - k) k = n - k; + long result = 1; + for (int i = 1; i <= k; i++) { + result = result * (n - k + i) / i; + } + return result; + } +} diff --git a/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.kt b/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.kt new file mode 100644 index 00000000..fda4e232 --- /dev/null +++ b/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.kt @@ -0,0 +1,43 @@ +class Solution { + fun getProbability(balls: IntArray): Double { + val sm = balls.sum() + val expanded = mutableListOf() + balls.forEachIndexed { i, ball -> repeat(ball) { expanded.add(i) } } + + val memo = mutableMapOf() + + fun dp(i: Int, cnt0: Int, mask0: Int, mask1: Int): Long { + val key = "$i,$cnt0,$mask0,$mask1" + memo[key]?.let { return it } + + val cnt1 = i - cnt0 + if (cnt0 > sm / 2 || cnt1 > sm / 2) { + memo[key] = 0 + return 0 + } + + if (i == expanded.size) { + val result = if (mask0.countOneBits() == mask1.countOneBits()) 1L else 0L + memo[key] = result + return result + } + + val result = dp(i + 1, cnt0 + 1, mask0 or (1 shl expanded[i]), mask1) + + dp(i + 1, cnt0, mask0, mask1 or (1 shl expanded[i])) + memo[key] = result + return result + } + + val favorable = dp(0, 0, 0, 0) + val total = comb(sm.toLong(), (sm / 2).toLong()) + return favorable.toDouble() / total.toDouble() + } + + private fun comb(n: Long, k: Long): Long { + var res = 1L + for (i in 1..k) { + res = res * (n - k + i) / i + } + return res + } +} diff --git a/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.py b/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.py new file mode 100644 index 00000000..488dad88 --- /dev/null +++ b/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.py @@ -0,0 +1,31 @@ +from functools import lru_cache +from itertools import chain +from math import comb + + +class Solution: + def getProbability(self, balls: List[int]) -> float: + + nxt = lambda x, y: x | 1 << balls[y] # function to update masks + + @lru_cache(None) + def dp(i, cnt0, box0, box1): # i: current ball + # cnt0: count of balls in first box + # box0: mask of colors in first box + # box1: mask of colors in second box + cnt1 = i - cnt0 + if cnt0 > sm // 2 or cnt1 > sm // 2: + return 0 # a box has too many balls + + if i == len(balls): + return box0.bit_count() == box1.bit_count() # each bit is a color + + return ( + dp(i + 1, cnt0 + 1, nxt(box0, i), box1) # ball added to first box + + dp(i + 1, cnt0, box0, nxt(box1, i)) + ) # ball added to second box + + sm = sum(balls) + balls = list(chain(*([i] * ball for i, ball in enumerate(balls)))) + + return dp(0, 0, 0, 0) / comb(sm, sm // 2) diff --git a/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.py2 b/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.py2 new file mode 100644 index 00000000..1152a6c3 --- /dev/null +++ b/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.py2 @@ -0,0 +1,38 @@ +class Solution(object): + def getProbability(self, balls): + """ + :type balls: List[int] + :rtype: float + """ + total = sum(balls) + half = total // 2 + + # Binomial weights count which distinct balls of a color enter box 0. + choose = [[0] * (total + 1) for _ in xrange(total + 1)] + for i in xrange(total + 1): + choose[i][0] = 1 + choose[i][i] = 1 + for j in xrange(1, i): + choose[i][j] = choose[i - 1][j - 1] + choose[i - 1][j] + + states = {(0, 0, 0): 1} + for count in balls: + next_states = {} + for (used, distinct0, distinct1), ways in states.iteritems(): + for take in xrange(count + 1): + new_used = used + take + if new_used > half: + break + key = (new_used, + distinct0 + (take > 0), + distinct1 + (take < count)) + next_states[key] = (next_states.get(key, 0) + + ways * choose[count][take]) + states = next_states + + favorable = 0 + for (used, distinct0, distinct1), ways in states.iteritems(): + if used == half and distinct0 == distinct1: + favorable += ways + + return float(favorable) / choose[total][half] diff --git a/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.rb b/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.rb new file mode 100644 index 00000000..2c2a4c23 --- /dev/null +++ b/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.rb @@ -0,0 +1,37 @@ +# @param {Integer[]} balls +# @return {Float} +def get_probability(balls) + total = balls.sum + half = total / 2 + + # Binomial weights count which distinct balls of a color enter box 0. + choose = Array.new(total + 1) { Array.new(total + 1, 0) } + 0.upto(total) do |i| + choose[i][0] = 1 + choose[i][i] = 1 + 1.upto(i - 1) do |j| + choose[i][j] = choose[i - 1][j - 1] + choose[i - 1][j] + end + end + + states = { [0, 0, 0] => 1 } + balls.each do |count| + next_states = Hash.new(0) + states.each do |(used, distinct0, distinct1), ways| + 0.upto(count) do |take| + new_used = used + take + break if new_used > half + key = [new_used, + distinct0 + (take > 0 ? 1 : 0), + distinct1 + (take < count ? 1 : 0)] + next_states[key] += ways * choose[count][take] + end + end + states = next_states + end + + favorable = states.sum do |(used, distinct0, distinct1), ways| + used == half && distinct0 == distinct1 ? ways : 0 + end + favorable.to_f / choose[total][half] +end diff --git a/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.rs b/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.rs new file mode 100644 index 00000000..fd9bc89c --- /dev/null +++ b/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.rs @@ -0,0 +1,51 @@ +impl Solution { + pub fn get_probability(balls: Vec) -> f64 { + use std::collections::HashMap; + + let sm: i32 = balls.iter().sum(); + let mut expanded = Vec::new(); + for (i, &b) in balls.iter().enumerate() { + for _ in 0..b { + expanded.push(i as i32); + } + } + + let mut memo: HashMap = HashMap::new(); + + fn dp(i: usize, cnt0: i32, mask0: i32, mask1: i32, sm: i32, expanded: &[i32], memo: &mut HashMap) -> i64 { + let key = format!("{},{},{},{}", i, cnt0, mask0, mask1); + if let Some(&val) = memo.get(&key) { + return val; + } + + let cnt1 = i as i32 - cnt0; + if cnt0 > sm / 2 || cnt1 > sm / 2 { + memo.insert(key, 0); + return 0; + } + + if i == expanded.len() { + let result = if mask0.count_ones() == mask1.count_ones() { 1 } else { 0 }; + memo.insert(key, result); + return result; + } + + let result = dp(i + 1, cnt0 + 1, mask0 | (1 << expanded[i]), mask1, sm, expanded, memo) + + dp(i + 1, cnt0, mask0, mask1 | (1 << expanded[i]), sm, expanded, memo); + memo.insert(key, result); + result + } + + fn comb(n: i32, k: i32) -> i64 { + let mut res: i64 = 1; + for i in 1..=k { + res = res * (n - k + i) as i64 / i as i64; + } + res + } + + let favorable = dp(0, 0, 0, 0, sm, &expanded, &mut memo); + let total = comb(sm, sm / 2); + favorable as f64 / total as f64 + } +} diff --git a/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.swift b/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.swift new file mode 100644 index 00000000..92c18e15 --- /dev/null +++ b/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.swift @@ -0,0 +1,47 @@ +class Solution { + func getProbability(_ balls: [Int]) -> Double { + let sm = balls.reduce(0, +) + var expanded = [Int]() + for (i, b) in balls.enumerated() { + for _ in 0.. Int { + let key = "\(i),\(cnt0),\(mask0),\(mask1)" + if let val = memo[key] { return val } + + let cnt1 = i - cnt0 + if cnt0 > sm / 2 || cnt1 > sm / 2 { + memo[key] = 0 + return 0 + } + + if i == expanded.count { + let result = mask0.nonzeroBitCount == mask1.nonzeroBitCount ? 1 : 0 + memo[key] = result + return result + } + + let result = dp(i + 1, cnt0 + 1, mask0 | (1 << expanded[i]), mask1) + + dp(i + 1, cnt0, mask0, mask1 | (1 << expanded[i])) + memo[key] = result + return result + } + + let favorable = dp(0, 0, 0, 0) + let total = comb(sm, sm / 2) + return Double(favorable) / Double(total) + } + + private func comb(_ n: Int, _ k: Int) -> Int { + var res = 1 + for i in 1...k { + res = res * (n - k + i) / i + } + return res + } +} diff --git a/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.ts b/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.ts new file mode 100644 index 00000000..78629df2 --- /dev/null +++ b/tests/1001-1500/1467. probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/sol.ts @@ -0,0 +1,55 @@ +function getProbability(balls: number[]): number { + const sm = balls.reduce((a, b) => a + b, 0); + const expanded: number[] = []; + balls.forEach((b, i) => { + for (let j = 0; j < b; j++) { + expanded.push(i); + } + }); + + const memo = new Map(); + + function popCount(n: number): number { + let count = 0; + while (n) { + count += n & 1; + n >>>= 1; + } + return count; + } + + function dp(i: number, cnt0: number, mask0: number, mask1: number): number { + const key = `${i},${cnt0},${mask0},${mask1}`; + if (memo.has(key)) return memo.get(key)!; + + const cnt1 = i - cnt0; + if (cnt0 > sm / 2 || cnt1 > sm / 2) { + memo.set(key, 0); + return 0; + } + + if (i === expanded.length) { + const result = popCount(mask0) === popCount(mask1) ? 1 : 0; + memo.set(key, result); + return result; + } + + const result = + dp(i + 1, cnt0 + 1, mask0 | (1 << expanded[i]), mask1) + + dp(i + 1, cnt0, mask0, mask1 | (1 << expanded[i])); + memo.set(key, result); + return result; + } + + function comb(n: number, k: number): number { + let res = 1; + for (let i = 1; i <= k; i++) { + res = (res * (n - k + i)) / i; + } + return res; + } + + const favorable = dp(0, 0, 0, 0); + const total = comb(sm, sm / 2); + return favorable / total; +} diff --git a/tests/1001-1500/1470. shuffle-the-array/manifest.yaml b/tests/1001-1500/1470. shuffle-the-array/manifest.yaml new file mode 100644 index 00000000..d2d9aeaf --- /dev/null +++ b/tests/1001-1500/1470. shuffle-the-array/manifest.yaml @@ -0,0 +1,1235 @@ +entry: + id: 1470 + title: "shuffle-the-array" + params: + nums: + type: array + items: + type: int + n: + type: int + call: + cpp: "Solution().shuffle({nums}, {n})" + rust: "Solution::shuffle({nums}, {n})" + python3: "Solution().shuffle({nums}, {n})" + python2: "Solution().shuffle({nums}, {n})" + ruby: "shuffle({nums}, {n})" + java: "new Solution().shuffle({nums}, {n})" + csharp: "new Solution().Shuffle({nums}, {n})" + kotlin: "Solution().shuffle({nums}, {n})" + go: "shuffle({nums}, {n})" + dart: "Solution().shuffle({nums}, {n})" + swift: "Solution().shuffle({nums}, {n})" + typescript: "shuffle({nums}, {n})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().shuffle(nums, n, {result})" + checker: | + class Checker: + def shuffle(self, nums, n, result): + if not isinstance(result, list) or len(result) != 2 * n: + return False + expected = [] + for index in range(n): + expected.extend((nums[index], nums[n + index])) + return result == expected + +seed: 1470 + +tests: + - name: "example-one" + in: + nums: [2, 5, 1, 3, 4, 7] + n: 3 + out: [2, 3, 5, 4, 1, 7] + - name: "example-two" + in: + nums: [1, 2, 3, 4, 4, 3, 2, 1] + n: 4 + out: [1, 4, 2, 3, 3, 2, 4, 1] + - name: "example-three" + in: + nums: [1, 1, 2, 2] + n: 2 + out: [1, 2, 1, 2] + - name: "minimum-n" + in: + nums: [1, 1000] + n: 1 + out: [1, 1000] + - name: "minimum-n-equal" + in: + nums: [777, 777] + n: 1 + out: [777, 777] + - name: "two-pairs" + in: + nums: [1, 2, 3, 4] + n: 2 + out: [1, 3, 2, 4] + - name: "two-pairs-repeated" + in: + nums: [9, 9, 1, 1] + n: 2 + out: [9, 1, 9, 1] + - name: "three-ascending" + in: + nums: [1, 2, 3, 4, 5, 6] + n: 3 + out: [1, 4, 2, 5, 3, 6] + - name: "three-reversed-halves" + in: + nums: [3, 2, 1, 6, 5, 4] + n: 3 + out: [3, 6, 2, 5, 1, 4] + - name: "four-duplicates" + in: + nums: [8, 8, 8, 8, 2, 2, 2, 2] + n: 4 + out: [8, 2, 8, 2, 8, 2, 8, 2] + - name: "four-bound-values" + in: + nums: [1, 1000, 2, 999, 3, 998, 4, 997] + n: 4 + out: [1, 3, 1000, 998, 2, 4, 999, 997] + - name: "five-alternating" + in: + nums: [1, 3, 5, 7, 9, 2, 4, 6, 8, 10] + n: 5 + out: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + - name: "five-constant" + in: + nums: [42, 42, 42, 42, 42, 42, 42, 42, 42, 42] + n: 5 + out: [42, 42, 42, 42, 42, 42, 42, 42, 42, 42] + - name: "six-permuted" + in: + nums: [6, 1, 5, 2, 4, 3, 12, 7, 11, 8, 10, 9] + n: 6 + out: [6, 12, 1, 7, 5, 11, 2, 8, 4, 10, 3, 9] + - name: "six-max-values" + in: + nums: [1000, 999, 998, 997, 996, 995, 994, 993, 992, 991, 990, 989] + n: 6 + out: [1000, 994, 999, 993, 998, 992, 997, 991, 996, 990, 995, 989] + - name: "seven-interleaving" + in: + nums: [10, 20, 30, 40, 50, 60, 70, 1, 2, 3, 4, 5, 6, 7] + n: 7 + out: [10, 1, 20, 2, 30, 3, 40, 4, 50, 5, 60, 6, 70, 7] + - name: "seven-duplicate-runs" + in: + nums: [1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4] + n: 7 + out: [1, 3, 1, 3, 1, 3, 2, 4, 2, 4, 2, 4, 2, 4] + - name: "eight-reversed" + in: + nums: [8, 7, 6, 5, 4, 3, 2, 1, 16, 15, 14, 13, 12, 11, 10, 9] + n: 8 + out: [8, 16, 7, 15, 6, 14, 5, 13, 4, 12, 3, 11, 2, 10, 1, 9] + - name: "nine-palindrome-halves" + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1] + n: 9 + out: [1, 9, 2, 8, 3, 7, 4, 6, 5, 5, 6, 4, 7, 3, 8, 2, 9, 1] + - name: "ten-two-valued" + in: + nums: [1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1] + n: 10 + out: [1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2, 1] + - name: "twelve-cyclic" + 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, + ] + n: 12 + out: + [ + 1, + 12, + 2, + 11, + 3, + 10, + 4, + 9, + 5, + 8, + 6, + 7, + 7, + 6, + 8, + 5, + 9, + 4, + 10, + 3, + 11, + 2, + 12, + 1, + ] + - name: "fifteen-ascending" + 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, + ] + n: 15 + out: + [ + 1, + 16, + 2, + 17, + 3, + 18, + 4, + 19, + 5, + 20, + 6, + 21, + 7, + 22, + 8, + 23, + 9, + 24, + 10, + 25, + 11, + 26, + 12, + 27, + 13, + 28, + 14, + 29, + 15, + 30, + ] + - name: "sixteen-repeated-blocks" + 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, + ] + n: 16 + out: + [ + 1, + 9, + 1, + 9, + 2, + 10, + 2, + 10, + 3, + 11, + 3, + 11, + 4, + 12, + 4, + 12, + 5, + 13, + 5, + 13, + 6, + 14, + 6, + 14, + 7, + 15, + 7, + 15, + 8, + 16, + 8, + 16, + ] + - name: "twenty-mixed" + in: + nums: + [ + 20, + 1, + 19, + 2, + 18, + 3, + 17, + 4, + 16, + 5, + 15, + 6, + 14, + 7, + 13, + 8, + 12, + 9, + 11, + 10, + 40, + 21, + 39, + 22, + 38, + 23, + 37, + 24, + 36, + 25, + 35, + 26, + 34, + 27, + 33, + 28, + 32, + 29, + 31, + 30, + ] + n: 20 + out: + [ + 20, + 40, + 1, + 21, + 19, + 39, + 2, + 22, + 18, + 38, + 3, + 23, + 17, + 37, + 4, + 24, + 16, + 36, + 5, + 25, + 15, + 35, + 6, + 26, + 14, + 34, + 7, + 27, + 13, + 33, + 8, + 28, + 12, + 32, + 9, + 29, + 11, + 31, + 10, + 30, + ] + - name: "twenty-five-constant" + in: + nums: + [ + 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, + 5, + ] + n: 25 + out: + [ + 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, + 5, + ] + - name: "thirty-boundary" + in: + nums: + [ + 1000, + 999, + 998, + 997, + 996, + 995, + 994, + 993, + 992, + 991, + 990, + 989, + 988, + 987, + 986, + 985, + 984, + 983, + 982, + 981, + 980, + 979, + 978, + 977, + 976, + 975, + 974, + 973, + 972, + 971, + 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, + ] + n: 30 + out: + [ + 1000, + 1, + 999, + 2, + 998, + 3, + 997, + 4, + 996, + 5, + 995, + 6, + 994, + 7, + 993, + 8, + 992, + 9, + 991, + 10, + 990, + 11, + 989, + 12, + 988, + 13, + 987, + 14, + 986, + 15, + 985, + 16, + 984, + 17, + 983, + 18, + 982, + 19, + 981, + 20, + 980, + 21, + 979, + 22, + 978, + 23, + 977, + 24, + 976, + 25, + 975, + 26, + 974, + 27, + 973, + 28, + 972, + 29, + 971, + 30, + ] + - name: "thirty-two-repeated" + in: + nums: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + ] + n: 32 + out: + [ + 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, + 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, + ] + - name: "forty-alternating" + in: + nums: + [ + 1, + 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, + 1, + 2, + 1, + 2, + 1, + 2, + 1, + 2, + 1, + 2, + 1, + 2, + 1, + 2, + 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, + 1, + 2, + 1, + 2, + 1, + 2, + 1, + 2, + 1, + 2, + 1, + 2, + 1, + 2, + 1, + 2, + ] + n: 40 + - name: "fifty-unique-halves" + 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, + 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, + ] + n: 50 + out: + [ + 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, + 25, + 76, + 26, + 75, + 27, + 74, + 28, + 73, + 29, + 72, + 30, + 71, + 31, + 70, + 32, + 69, + 33, + 68, + 34, + 67, + 35, + 66, + 36, + 65, + 37, + 64, + 38, + 63, + 39, + 62, + 40, + 61, + 41, + 60, + 42, + 59, + 43, + 58, + 44, + 57, + 45, + 56, + 46, + 55, + 47, + 54, + 48, + 53, + 49, + 52, + 50, + 51, + ] + - name: "three-min-max-mix" + in: + nums: [1, 1000, 1000, 1, 500, 500] + n: 3 + out: [1, 1, 1000, 500, 1000, 500] + - name: "four-same-first-half" + in: + nums: [6, 6, 6, 6, 1, 2, 3, 4] + n: 4 + out: [6, 1, 6, 2, 6, 3, 6, 4] + - name: "five-descending-values" + in: + nums: [1000, 900, 800, 700, 600, 500, 400, 300, 200, 100] + n: 5 + out: [1000, 500, 900, 400, 800, 300, 700, 200, 600, 100] + - name: "eight-single-value-halves" + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1] + n: 8 + out: [1, 8, 2, 7, 3, 6, 4, 5, 5, 4, 6, 3, 7, 2, 8, 1] + - name: "ten-boundary-duplicates" + in: + nums: + [ + 1, + 1000, + 1, + 1000, + 1, + 1000, + 1, + 1000, + 1, + 1000, + 1000, + 1, + 1000, + 1, + 1000, + 1, + 1000, + 1, + 1000, + 1, + ] + n: 10 + out: + [ + 1, + 1000, + 1000, + 1, + 1, + 1000, + 1000, + 1, + 1, + 1000, + 1000, + 1, + 1, + 1000, + 1000, + 1, + 1, + 1000, + 1000, + 1, + ] + - name: "two-max-min-pairs" + in: + nums: [1000, 1, 999, 2] + n: 2 + out: [1000, 999, 1, 2] + - name: "generated-small" + seed: 147001 + in: + nums: + gen: "array" + len: 20 + of: + gen: "int" + min: 1 + max: 1000 + n: 10 + - name: "generated-medium" + seed: 147002 + in: + nums: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 1000 + n: 50 + - name: "generated-large-a" + seed: 147003 + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 1000 + n: 500 + - name: "generated-large-b" + seed: 147004 + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 1000 + n: 500 + - name: "generated-small-duplicates" + seed: 147005 + in: + nums: + gen: "array" + len: 40 + of: + gen: "int" + min: 1 + max: 3 + n: 20 diff --git a/tests/1001-1500/1470. shuffle-the-array/sol.cpp b/tests/1001-1500/1470. shuffle-the-array/sol.cpp new file mode 100644 index 00000000..0bc11264 --- /dev/null +++ b/tests/1001-1500/1470. shuffle-the-array/sol.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + vector shuffle(vector& nums, int n) { + vector ans(2 * n); + for (int i = 0; i < 2 * n; i++) { + if (i % 2 == 0) { + ans[i] = nums[i / 2]; + } else { + ans[i] = nums[n + i / 2]; + } + } + return ans; + } +}; diff --git a/tests/1001-1500/1470. shuffle-the-array/sol.cs b/tests/1001-1500/1470. shuffle-the-array/sol.cs new file mode 100644 index 00000000..0616b1d7 --- /dev/null +++ b/tests/1001-1500/1470. shuffle-the-array/sol.cs @@ -0,0 +1,13 @@ +public class Solution { + public int[] Shuffle(int[] nums, int n) { + int[] ans = new int[2 * n]; + for (int i = 0; i < 2 * n; i++) { + if (i % 2 == 0) { + ans[i] = nums[i / 2]; + } else { + ans[i] = nums[n + i / 2]; + } + } + return ans; + } +} diff --git a/tests/1001-1500/1470. shuffle-the-array/sol.dart b/tests/1001-1500/1470. shuffle-the-array/sol.dart new file mode 100644 index 00000000..8f191957 --- /dev/null +++ b/tests/1001-1500/1470. shuffle-the-array/sol.dart @@ -0,0 +1,10 @@ +class Solution { + List shuffle(List nums, int n) { + final result = List.filled(2 * n, 0); + for (int i = 0; i < n; i++) { + result[2 * i] = nums[i]; + result[2 * i + 1] = nums[n + i]; + } + return result; + } +} diff --git a/tests/1001-1500/1470. shuffle-the-array/sol.go b/tests/1001-1500/1470. shuffle-the-array/sol.go new file mode 100644 index 00000000..826346c7 --- /dev/null +++ b/tests/1001-1500/1470. shuffle-the-array/sol.go @@ -0,0 +1,11 @@ +func shuffle(nums []int, n int) []int { + ans := make([]int, 2*n) + for i := 0; i < 2*n; i++ { + if i%2 == 0 { + ans[i] = nums[i/2] + } else { + ans[i] = nums[n+i/2] + } + } + return ans +} diff --git a/tests/1001-1500/1470. shuffle-the-array/sol.java b/tests/1001-1500/1470. shuffle-the-array/sol.java new file mode 100644 index 00000000..37f595b7 --- /dev/null +++ b/tests/1001-1500/1470. shuffle-the-array/sol.java @@ -0,0 +1,13 @@ +class Solution { + public int[] shuffle(int[] nums, int n) { + int[] ans = new int[2 * n]; + for (int i = 0; i < 2 * n; i++) { + if (i % 2 == 0) { + ans[i] = nums[i / 2]; + } else { + ans[i] = nums[n + i / 2]; + } + } + return ans; + } +} diff --git a/tests/1001-1500/1470. shuffle-the-array/sol.kt b/tests/1001-1500/1470. shuffle-the-array/sol.kt new file mode 100644 index 00000000..224e98c2 --- /dev/null +++ b/tests/1001-1500/1470. shuffle-the-array/sol.kt @@ -0,0 +1,13 @@ +class Solution { + fun shuffle(nums: IntArray, n: Int): IntArray { + val ans = IntArray(2 * n) + for (i in 0 until 2 * n) { + if (i % 2 == 0) { + ans[i] = nums[i / 2] + } else { + ans[i] = nums[n + i / 2] + } + } + return ans + } +} diff --git a/tests/1001-1500/1470. shuffle-the-array/sol.py b/tests/1001-1500/1470. shuffle-the-array/sol.py new file mode 100644 index 00000000..dd5610ea --- /dev/null +++ b/tests/1001-1500/1470. shuffle-the-array/sol.py @@ -0,0 +1,9 @@ +class Solution: + def shuffle(self, nums: List[int], n: int) -> List[int]: + ans = [0] * (2 * n) + for i in range(2 * n): + if i % 2 == 0: + ans[i] = nums[i // 2] + else: + ans[i] = nums[n + i // 2] + return ans diff --git a/tests/1001-1500/1470. shuffle-the-array/sol.py2 b/tests/1001-1500/1470. shuffle-the-array/sol.py2 new file mode 100644 index 00000000..42d2f6a5 --- /dev/null +++ b/tests/1001-1500/1470. shuffle-the-array/sol.py2 @@ -0,0 +1,14 @@ +class Solution(object): + def shuffle(self, nums, n): + """ + :type nums: List[int] + :type n: int + :rtype: List[int] + """ + ans = [0] * (2 * n) + for i in range(2 * n): + if i % 2 == 0: + ans[i] = nums[i // 2] + else: + ans[i] = nums[n + i // 2] + return ans diff --git a/tests/1001-1500/1470. shuffle-the-array/sol.rb b/tests/1001-1500/1470. shuffle-the-array/sol.rb new file mode 100644 index 00000000..b2fb8c84 --- /dev/null +++ b/tests/1001-1500/1470. shuffle-the-array/sol.rb @@ -0,0 +1,14 @@ +# @param {Integer[]} nums +# @param {Integer} n +# @return {Integer[]} +def shuffle(nums, n) + ans = Array.new(2 * n, 0) + (0...2 * n).each do |i| + if i % 2 == 0 + ans[i] = nums[i / 2] + else + ans[i] = nums[n + i / 2] + end + end + ans +end diff --git a/tests/1001-1500/1470. shuffle-the-array/sol.rs b/tests/1001-1500/1470. shuffle-the-array/sol.rs new file mode 100644 index 00000000..9d505759 --- /dev/null +++ b/tests/1001-1500/1470. shuffle-the-array/sol.rs @@ -0,0 +1,14 @@ +impl Solution { + pub fn shuffle(nums: Vec, n: i32) -> Vec { + let n_u = n as usize; + let mut ans = vec![0; 2 * n_u]; + for i in 0..(2 * n_u) { + if i % 2 == 0 { + ans[i] = nums[i / 2]; + } else { + ans[i] = nums[n_u + i / 2]; + } + } + ans + } +} diff --git a/tests/1001-1500/1470. shuffle-the-array/sol.swift b/tests/1001-1500/1470. shuffle-the-array/sol.swift new file mode 100644 index 00000000..3d6ec2e7 --- /dev/null +++ b/tests/1001-1500/1470. shuffle-the-array/sol.swift @@ -0,0 +1,13 @@ +class Solution { + func shuffle(_ nums: [Int], _ n: Int) -> [Int] { + var ans = [Int](repeating: 0, count: 2 * n) + for i in 0..<(2 * n) { + if i % 2 == 0 { + ans[i] = nums[i / 2] + } else { + ans[i] = nums[n + i / 2] + } + } + return ans + } +} diff --git a/tests/1001-1500/1470. shuffle-the-array/sol.ts b/tests/1001-1500/1470. shuffle-the-array/sol.ts new file mode 100644 index 00000000..8b365dfb --- /dev/null +++ b/tests/1001-1500/1470. shuffle-the-array/sol.ts @@ -0,0 +1,11 @@ +function shuffle(nums: number[], n: number): number[] { + const ans: number[] = new Array(2 * n); + for (let i = 0; i < 2 * n; i++) { + if (i % 2 === 0) { + ans[i] = nums[(i / 2) | 0]; + } else { + ans[i] = nums[n + ((i / 2) | 0)]; + } + } + return ans; +} diff --git a/tests/1001-1500/1471. the-k-strongest-values-in-an-array/manifest.yaml b/tests/1001-1500/1471. the-k-strongest-values-in-an-array/manifest.yaml new file mode 100644 index 00000000..b6eb3aa7 --- /dev/null +++ b/tests/1001-1500/1471. the-k-strongest-values-in-an-array/manifest.yaml @@ -0,0 +1,220 @@ +entry: + id: 1471 + title: "the-k-strongest-values-in-an-array" + params: + arr: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().getStrongest({arr}, {k})" + rust: "Solution::get_strongest({arr}, {k})" + python3: "Solution().getStrongest({arr}, {k})" + python2: "Solution().getStrongest({arr}, {k})" + ruby: "get_strongest({arr}, {k})" + java: "new Solution().getStrongest({arr}, {k})" + csharp: "new Solution().GetStrongest({arr}, {k})" + kotlin: "Solution().getStrongest({arr}, {k})" + go: "getStrongest({arr}, {k})" + dart: "Solution().getStrongest({arr}, {k})" + swift: "Solution().getStrongest({arr}, {k})" + typescript: "getStrongest({arr}, {k})" +judge: + type: "ignore_order" +limits: + time_ms: 700 + memory_mb: 256 +oracle: + python3: + call: "Checker().getStrongest(arr, k, {result})" + checker: | + class Checker: + def getStrongest(self, arr, k, result): + center = sorted(arr)[(len(arr) - 1) // 2] + expected = sorted(arr, key=lambda value: (abs(value - center), value), reverse=True)[:k] + return sorted(result) == sorted(expected) +seed: 1471 +tests: + - name: "official-one" + in: + arr: [1, 2, 3, 4, 5] + k: 2 + out: [5, 1] + - name: "official-two" + in: + arr: [1, 1, 3, 5, 5] + k: 2 + out: [5, 5] + - name: "official-three" + in: + arr: [6, 7, 11, 7, 6, 8] + k: 5 + out: [11, 8, 6, 6, 7] + - name: "single" + in: + arr: [42] + k: 1 + - name: "two-values" + in: + arr: [1, 9] + k: 1 + - name: "two-all" + in: + arr: [1, 9] + k: 2 + - name: "all-equal" + in: + arr: [7, 7, 7, 7, 7] + k: 3 + - name: "all-equal-all" + in: + arr: [0, 0, 0, 0] + k: 4 + - name: "negative-values" + in: + arr: [-9, -5, -2, -1] + k: 2 + - name: "symmetric-values" + in: + arr: [-5, -2, 0, 2, 5] + k: 3 + - name: "even-center-lower" + in: + arr: [1, 2, 3, 10] + k: 2 + - name: "odd-center" + in: + arr: [-10, -2, 0, 1, 5] + k: 2 + - name: "duplicates-extremes" + in: + arr: [-10, -10, 0, 10, 10] + k: 4 + - name: "tie-prefers-larger" + in: + arr: [1, 3, 5] + k: 2 + - name: "tie-prefers-larger-even" + in: + arr: [1, 3, 5, 7] + k: 3 + - name: "k-one-largest" + in: + arr: [-20, -1, 0, 3, 8] + k: 1 + - name: "k-all-small" + in: + arr: [-3, -1, 2, 4, 8] + k: 5 + - name: "zero-centered" + in: + arr: [-8, -3, 0, 2, 6] + k: 4 + - name: "positive-centered" + in: + arr: [1, 4, 5, 6, 20] + k: 3 + - name: "negative-centered" + in: + arr: [-20, -6, -5, -4, 1] + k: 3 + - name: "repeated-middle" + in: + arr: [1, 2, 2, 2, 8, 9] + k: 4 + - name: "repeated-low" + in: + arr: [-4, -4, -4, 0, 3, 5] + k: 3 + - name: "repeated-high" + in: + arr: [-5, 0, 4, 9, 9, 9] + k: 4 + - name: "wide-range" + in: + arr: [-100000, -50000, -1, 0, 1, 50000, 100000] + k: 5 + - name: "boundary-negative" + in: + arr: [-100000, -99999, -99998, -1] + k: 2 + - name: "boundary-positive" + in: + arr: [1, 99998, 99999, 100000] + k: 3 + - name: "unsorted-small" + in: + arr: [8, 1, 6, 2, 7, 3] + k: 4 + - name: "unsorted-negative" + in: + arr: [-1, -8, -3, -6, -2] + k: 3 + - name: "alternating-signs" + in: + arr: [10, -10, 9, -9, 0, 1] + k: 5 + - name: "close-cluster" + in: + arr: [100, 101, 102, 103, 104] + k: 2 + - name: "far-cluster" + in: + arr: [-100, -1, 0, 1, 100] + k: 4 + - name: "many-duplicates" + in: + arr: [2, 2, 2, 5, 5, 9, 9, 9] + k: 5 + - name: "four-values" + in: + arr: [4, 1, 7, 10] + k: 1 + - name: "six-values" + in: + arr: [-6, -4, -2, 2, 4, 6] + k: 6 + - name: "center-not-zero" + in: + arr: [-2, 2, 4, 5, 6, 7, 20] + k: 4 + - name: "strongest-low-side" + in: + arr: [-50, -10, -9, -8, 0] + k: 2 + - name: "strongest-high-side" + in: + arr: [0, 8, 9, 10, 50] + k: 2 + - name: "large-random-half" + in: + arr: + gen: "array" + len: 100000 + of: + gen: "int" + min: -100000 + max: 100000 + distinct: false + sorted: false + elemType: "int" + k: 50000 + - name: "large-random-nearly-all" + in: + arr: + gen: "array" + len: 100000 + of: + gen: "int" + min: -100000 + max: 100000 + distinct: false + sorted: false + elemType: "int" + k: 99999 + - name: "even-lower-median-boundary-ties" + in: + arr: [-100000, -100000, -99999, 0, 1, 99999, 100000, 100000] + k: 6 diff --git a/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.cpp b/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.cpp new file mode 100644 index 00000000..2f1432ff --- /dev/null +++ b/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + vector getStrongest(vector& arr, int k) { + sort(arr.begin(), arr.end()); + int m = arr[(arr.size() - 1) / 2]; + + int left = 0, right = arr.size() - 1; + vector result; + for (int i = 0; i < k; i++) { + if (abs(arr[right] - m) >= abs(arr[left] - m)) { + result.push_back(arr[right]); + right--; + } else { + result.push_back(arr[left]); + left++; + } + } + return result; + } +}; diff --git a/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.cs b/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.cs new file mode 100644 index 00000000..fe591113 --- /dev/null +++ b/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.cs @@ -0,0 +1,19 @@ +public class Solution { + public int[] GetStrongest(int[] arr, int k) { + Array.Sort(arr); + int m = arr[(arr.Length - 1) / 2]; + + int left = 0, right = arr.Length - 1; + int[] result = new int[k]; + for (int i = 0; i < k; i++) { + if (Math.Abs(arr[right] - m) >= Math.Abs(arr[left] - m)) { + result[i] = arr[right]; + right--; + } else { + result[i] = arr[left]; + left++; + } + } + return result; + } +} diff --git a/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.dart b/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.dart new file mode 100644 index 00000000..fe763670 --- /dev/null +++ b/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.dart @@ -0,0 +1,19 @@ +class Solution { + List getStrongest(List arr, int k) { + arr.sort(); + int m = arr[(arr.length - 1) ~/ 2]; + + int left = 0, right = arr.length - 1; + List result = []; + for (int i = 0; i < k; i++) { + if ((arr[right] - m).abs() >= (arr[left] - m).abs()) { + result.add(arr[right]); + right--; + } else { + result.add(arr[left]); + left++; + } + } + return result; + } +} diff --git a/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.go b/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.go new file mode 100644 index 00000000..27fcdcf8 --- /dev/null +++ b/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.go @@ -0,0 +1,24 @@ +func getStrongest(arr []int, k int) []int { + sort.Ints(arr) + m := arr[(len(arr)-1)/2] + + left, right := 0, len(arr)-1 + result := make([]int, k) + for i := 0; i < k; i++ { + if abs(arr[right]-m) >= abs(arr[left]-m) { + result[i] = arr[right] + right-- + } else { + result[i] = arr[left] + left++ + } + } + return result +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} diff --git a/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.java b/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.java new file mode 100644 index 00000000..74fc91dc --- /dev/null +++ b/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.java @@ -0,0 +1,19 @@ +class Solution { + public int[] getStrongest(int[] arr, int k) { + java.util.Arrays.sort(arr); + int m = arr[(arr.length - 1) / 2]; + + int left = 0, right = arr.length - 1; + int[] result = new int[k]; + for (int i = 0; i < k; i++) { + if (Math.abs(arr[right] - m) >= Math.abs(arr[left] - m)) { + result[i] = arr[right]; + right--; + } else { + result[i] = arr[left]; + left++; + } + } + return result; + } +} diff --git a/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.kt b/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.kt new file mode 100644 index 00000000..6929979f --- /dev/null +++ b/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.kt @@ -0,0 +1,20 @@ +class Solution { + fun getStrongest(arr: IntArray, k: Int): IntArray { + arr.sort() + val m = arr[(arr.size - 1) / 2] + + var left = 0 + var right = arr.size - 1 + val result = IntArray(k) + for (i in 0 until k) { + if (Math.abs(arr[right] - m) >= Math.abs(arr[left] - m)) { + result[i] = arr[right] + right-- + } else { + result[i] = arr[left] + left++ + } + } + return result + } +} diff --git a/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.py b/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.py new file mode 100644 index 00000000..6a1eb145 --- /dev/null +++ b/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.py @@ -0,0 +1,20 @@ +class Solution(object): + def getStrongest(self, ns, k): + + ns = sorted(ns) + mi = (len(ns) - 1) // 2 + cnt = ns[mi] + + i1 = 0 + i2 = len(ns) - 1 + + a = [] + for _ in range(k): + if abs(ns[i2] - cnt) >= abs(ns[i1] - cnt): + a.append(ns[i2]) + i2 -= 1 + else: + a.append(ns[i1]) + i1 += 1 + + return a diff --git a/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.py2 b/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.py2 new file mode 100644 index 00000000..b43b116e --- /dev/null +++ b/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.py2 @@ -0,0 +1,20 @@ +class Solution(object): + def getStrongest(self, arr, k): + """ + :type arr: List[int] + :type k: int + :rtype: List[int] + """ + arr.sort() + m = arr[(len(arr) - 1) // 2] + + left, right = 0, len(arr) - 1 + result = [] + for _ in range(k): + if abs(arr[right] - m) >= abs(arr[left] - m): + result.append(arr[right]) + right -= 1 + else: + result.append(arr[left]) + left += 1 + return result diff --git a/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.rb b/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.rb new file mode 100644 index 00000000..4de0eca9 --- /dev/null +++ b/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.rb @@ -0,0 +1,21 @@ +# @param {Integer[]} arr +# @param {Integer} k +# @return {Integer[]} +def get_strongest(arr, k) + arr.sort! + m = arr[(arr.length - 1) / 2] + + left = 0 + right = arr.length - 1 + result = [] + k.times do + if (arr[right] - m).abs >= (arr[left] - m).abs + result << arr[right] + right -= 1 + else + result << arr[left] + left += 1 + end + end + result +end diff --git a/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.rs b/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.rs new file mode 100644 index 00000000..e1a57ace --- /dev/null +++ b/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.rs @@ -0,0 +1,21 @@ +impl Solution { + pub fn get_strongest(arr: Vec, k: i32) -> Vec { + let mut arr = arr; + arr.sort_unstable(); + let m = arr[((arr.len() - 1) / 2) as usize]; + + let mut left = 0; + let mut right = arr.len() - 1; + let mut result = Vec::with_capacity(k as usize); + for _ in 0..k { + if (arr[right] - m).abs() >= (arr[left] - m).abs() { + result.push(arr[right]); + if right > 0 { right -= 1; } + } else { + result.push(arr[left]); + left += 1; + } + } + result + } +} diff --git a/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.swift b/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.swift new file mode 100644 index 00000000..c81b38e3 --- /dev/null +++ b/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func getStrongest(_ arr: [Int], _ k: Int) -> [Int] { + var arr = arr.sorted() + let m = arr[(arr.count - 1) / 2] + + var left = 0 + var right = arr.count - 1 + var result = [Int]() + for _ in 0..= abs(arr[left] - m) { + result.append(arr[right]) + right -= 1 + } else { + result.append(arr[left]) + left += 1 + } + } + return result + } +} diff --git a/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.ts b/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.ts new file mode 100644 index 00000000..7b97f870 --- /dev/null +++ b/tests/1001-1500/1471. the-k-strongest-values-in-an-array/sol.ts @@ -0,0 +1,18 @@ +function getStrongest(arr: number[], k: number): number[] { + arr.sort((a, b) => a - b); + const m = arr[Math.floor((arr.length - 1) / 2)]; + + let left = 0, + right = arr.length - 1; + const result: number[] = []; + for (let i = 0; i < k; i++) { + if (Math.abs(arr[right] - m) >= Math.abs(arr[left] - m)) { + result.push(arr[right]); + right--; + } else { + result.push(arr[left]); + left++; + } + } + return result; +} diff --git a/tests/1001-1500/1473. paint-house-iii/manifest.yaml b/tests/1001-1500/1473. paint-house-iii/manifest.yaml new file mode 100644 index 00000000..38a97208 --- /dev/null +++ b/tests/1001-1500/1473. paint-house-iii/manifest.yaml @@ -0,0 +1,779 @@ +entry: + id: 1473 + title: "paint-house-iii" + params: + houses: + type: array + items: + type: int + cost: + type: array + items: + type: array + items: + type: int + m: + type: int + n: + type: int + target: + type: int + call: + cpp: "Solution().minCost({houses}, {cost}, {m}, {n}, {target})" + rust: "Solution::min_cost({houses}, {cost}, {m}, {n}, {target})" + python3: "Solution().minCost({houses}, {cost}, {m}, {n}, {target})" + python2: "Solution().minCost({houses}, {cost}, {m}, {n}, {target})" + ruby: "min_cost({houses}, {cost}, {m}, {n}, {target})" + java: "new Solution().minCost({houses}, {cost}, {m}, {n}, {target})" + csharp: "new Solution().MinCost({houses}, {cost}, {m}, {n}, {target})" + kotlin: "Solution().minCost({houses}, {cost}, {m}, {n}, {target})" + go: "minCost({houses}, {cost}, {m}, {n}, {target})" + dart: "Solution().minCost({houses}, {cost}, {m}, {n}, {target})" + swift: "Solution().minCost({houses}, {cost}, {m}, {n}, {target})" + typescript: "minCost({houses}, {cost}, {m}, {n}, {target})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().minCost(houses, cost, m, n, target, {result})" + checker: | + class Checker: + def minCost(self, houses, cost, m, n, target, result): + inf = 10**18 + dp = [[inf] * (target + 1) for _ in range(n)] + first = range(n) if houses[0] == 0 else [houses[0] - 1] + for color in first: + dp[color][1] = 0 if houses[0] else cost[0][color] + for i in range(1, m): + ndp = [[inf] * (target + 1) for _ in range(n)] + choices = range(n) if houses[i] == 0 else [houses[i] - 1] + for color in choices: + add = 0 if houses[i] else cost[i][color] + for groups in range(1, target + 1): + ndp[color][groups] = min(ndp[color][groups], dp[color][groups] + add) + if groups > 1: + ndp[color][groups] = min( + ndp[color][groups], + min((dp[old][groups - 1] for old in range(n) if old != color), default=inf) + add) + dp = ndp + expected = min(dp[color][target] for color in range(n)) + expected = -1 if expected >= inf else expected + return isinstance(result, int) and not isinstance(result, bool) and result == expected + +seed: 1473 + +tests: + - name: "example_one" + in: + houses: [0, 0, 0, 0, 0] + cost: + elemType: "int" + value: + - [1, 10] + - [10, 1] + - [10, 1] + - [1, 10] + - [5, 1] + m: 5 + n: 2 + target: 3 + out: 9 + - name: "example_two" + in: + houses: [0, 2, 1, 2, 0] + cost: + elemType: "int" + value: + - [1, 10] + - [10, 1] + - [10, 1] + - [1, 10] + - [5, 1] + m: 5 + n: 2 + target: 3 + out: 11 + - name: "example_three" + in: + houses: [3, 1, 2, 3] + cost: + elemType: "int" + value: + - [1, 1, 1] + - [1, 1, 1] + - [1, 1, 1] + - [1, 1, 1] + m: 4 + n: 3 + target: 3 + out: -1 + - name: "one_house_unpainted" + in: + houses: [0] + cost: + elemType: "int" + value: + - [7, 2, 9] + m: 1 + n: 3 + target: 1 + out: 2 + - name: "one_house_fixed" + in: + houses: [2] + cost: + elemType: "int" + value: + - [7, 2, 9] + m: 1 + n: 3 + target: 1 + out: 0 + - name: "fixed_already_one_group" + in: + houses: [1, 1, 1, 1, 1] + cost: + elemType: "int" + value: + - [5, 5] + - [5, 5] + - [5, 5] + - [5, 5] + - [5, 5] + m: 5 + n: 2 + target: 1 + out: 0 + - name: "fixed_already_many_groups" + in: + houses: [1, 2, 1, 2] + cost: + elemType: "int" + value: + - [5, 5] + - [5, 5] + - [5, 5] + - [5, 5] + m: 4 + n: 2 + target: 4 + out: 0 + - name: "fixed_impossible_low_target" + in: + houses: [1, 2, 1] + cost: + elemType: "int" + value: + - [1, 1] + - [1, 1] + - [1, 1] + m: 3 + n: 2 + target: 1 + out: -1 + - name: "two_colors_target_two" + in: + houses: [0, 0, 0] + cost: + elemType: "int" + value: + - [4, 1] + - [2, 8] + - [9, 3] + m: 3 + n: 2 + target: 2 + - name: "two_colors_target_three" + in: + houses: [0, 0, 0] + cost: + elemType: "int" + value: + - [4, 1] + - [2, 8] + - [9, 3] + m: 3 + n: 2 + target: 3 + - name: "three_colors_single_change" + in: + houses: [1, 0, 1, 0] + cost: + elemType: "int" + value: + - [4, 4, 4] + - [9, 1, 5] + - [4, 4, 4] + - [2, 8, 3] + m: 4 + n: 3 + target: 2 + - name: "three_colors_max_groups" + in: + houses: [0, 0, 0, 0, 0] + cost: + elemType: "int" + value: + - [1, 9, 9] + - [9, 1, 9] + - [9, 9, 1] + - [1, 9, 9] + - [9, 1, 9] + m: 5 + n: 3 + target: 5 + - name: "three_colors_impossible_target" + in: + houses: [1, 1, 1, 1] + cost: + elemType: "int" + value: + - [1, 1, 1] + - [1, 1, 1] + - [1, 1, 1] + - [1, 1, 1] + m: 4 + n: 3 + target: 3 + out: -1 + - name: "expensive_fixed_mix" + in: + houses: [0, 2, 0, 3, 0] + cost: + elemType: "int" + value: + - [100, 1, 100] + - [100, 100, 100] + - [1, 100, 100] + - [100, 100, 100] + - [100, 1, 100] + m: 5 + n: 3 + target: 3 + - name: "cheap_color_dominates" + in: + houses: [0, 0, 0, 0, 0, 0] + cost: + elemType: "int" + value: + - [1, 50, 50] + - [1, 50, 50] + - [50, 1, 50] + - [50, 1, 50] + - [50, 50, 1] + - [50, 50, 1] + m: 6 + n: 3 + target: 3 + - name: "alternating_fixed" + in: + houses: [1, 0, 2, 0, 1, 0] + cost: + elemType: "int" + value: + - [3, 3] + - [2, 7] + - [3, 3] + - [8, 1] + - [3, 3] + - [1, 8] + m: 6 + n: 2 + target: 5 + - name: "alternating_reduce_groups" + in: + houses: [1, 0, 2, 0, 1] + cost: + elemType: "int" + value: + - [1, 1] + - [1, 1] + - [1, 1] + - [1, 1] + - [1, 1] + m: 5 + n: 2 + target: 3 + - name: "four_colors" + in: + houses: [0, 0, 0, 0] + cost: + elemType: "int" + value: + - [8, 7, 6, 1] + - [1, 8, 7, 6] + - [6, 1, 8, 7] + - [7, 6, 1, 8] + m: 4 + n: 4 + target: 2 + - name: "four_colors_target_one" + in: + houses: [0, 0, 0, 0] + cost: + elemType: "int" + value: + - [8, 7, 6, 1] + - [1, 8, 7, 6] + - [6, 1, 8, 7] + - [7, 6, 1, 8] + m: 4 + n: 4 + target: 1 + - name: "six_houses_two_colors" + in: + houses: [0, 1, 0, 2, 0, 0] + cost: + elemType: "int" + value: + - [5, 2] + - [5, 5] + - [1, 7] + - [5, 5] + - [2, 4] + - [6, 1] + m: 6 + n: 2 + target: 4 + - name: "six_houses_three_colors" + in: + houses: [0, 0, 3, 0, 0, 2] + cost: + elemType: "int" + value: + - [3, 9, 4] + - [8, 2, 6] + - [5, 5, 5] + - [1, 7, 8] + - [6, 3, 2] + - [4, 4, 4] + m: 6 + n: 3 + target: 3 + - name: "large_cost_values" + in: + houses: [0, 0, 1, 0, 0] + cost: + elemType: "int" + value: + - [10000, 9999] + - [9998, 10000] + - [10000, 10000] + - [9997, 9996] + - [10000, 9995] + m: 5 + n: 2 + target: 2 + - name: "all_fixed_three_colors" + in: + houses: [2, 2, 3, 3, 1, 1, 2, 2] + cost: + elemType: "int" + value: + - [5, 5, 5] + - [5, 5, 5] + - [5, 5, 5] + - [5, 5, 5] + - [5, 5, 5] + - [5, 5, 5] + - [5, 5, 5] + - [5, 5, 5] + m: 8 + n: 3 + target: 3 + - name: "all_fixed_wrong_target" + in: + houses: [2, 2, 3, 3, 1, 1, 2, 2] + cost: + elemType: "int" + value: + - [5, 5, 5] + - [5, 5, 5] + - [5, 5, 5] + - [5, 5, 5] + - [5, 5, 5] + - [5, 5, 5] + - [5, 5, 5] + - [5, 5, 5] + m: 8 + n: 3 + target: 4 + - name: "eight_houses_two_colors" + in: + houses: [0, 0, 0, 1, 0, 0, 2, 0] + cost: + elemType: "int" + value: + - [4, 8] + - [3, 7] + - [2, 6] + - [5, 5] + - [1, 9] + - [8, 2] + - [5, 5] + - [7, 1] + m: 8 + n: 2 + target: 4 + - name: "nine_houses_three_colors" + in: + houses: [0, 2, 0, 0, 3, 0, 0, 1, 0] + cost: + elemType: "int" + value: + - [2, 5, 8] + - [5, 5, 5] + - [8, 2, 5] + - [1, 7, 4] + - [5, 5, 5] + - [6, 3, 1] + - [2, 9, 4] + - [5, 5, 5] + - [3, 4, 2] + m: 9 + n: 3 + target: 5 + - name: "ten_houses_target_ten" + in: + houses: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + cost: + elemType: "int" + value: + - [1, 9] + - [9, 1] + - [1, 9] + - [9, 1] + - [1, 9] + - [9, 1] + - [1, 9] + - [9, 1] + - [1, 9] + - [9, 1] + m: 10 + n: 2 + target: 10 + - name: "eleven_houses_fixed_blocks" + in: + houses: [0, 1, 1, 0, 2, 2, 0, 3, 3, 0, 1] + cost: + elemType: "int" + value: + - [4, 2, 8] + - [5, 5, 5] + - [5, 5, 5] + - [1, 7, 3] + - [5, 5, 5] + - [5, 5, 5] + - [3, 2, 6] + - [5, 5, 5] + - [5, 5, 5] + - [2, 8, 1] + - [5, 5, 5] + m: 11 + n: 3 + target: 7 + - name: "twelve_houses_two_colors_middle_fixed" + in: + houses: [0, 0, 1, 0, 0, 2, 0, 0, 1, 0, 0, 2] + cost: + elemType: "int" + value: + - [2, 8] + - [3, 7] + - [5, 5] + - [1, 9] + - [4, 6] + - [5, 5] + - [6, 2] + - [7, 1] + - [5, 5] + - [2, 4] + - [3, 1] + - [5, 5] + m: 12 + n: 2 + target: 6 + - name: "twelve_houses_four_colors" + in: + houses: [0, 2, 0, 0, 4, 0, 1, 0, 0, 3, 0, 0] + cost: + elemType: "int" + value: + - [3, 8, 5, 2] + - [5, 5, 5, 5] + - [7, 2, 6, 4] + - [1, 9, 3, 8] + - [5, 5, 5, 5] + - [6, 4, 2, 7] + - [5, 5, 5, 5] + - [2, 6, 9, 1] + - [4, 3, 8, 2] + - [5, 5, 5, 5] + - [1, 7, 4, 6] + - [8, 2, 5, 3] + m: 12 + n: 4 + target: 8 + - name: "single_color_max_cost" + in: + houses: [0, 0, 0, 0, 0] + cost: + elemType: "int" + value: + - [10000] + - [9999] + - [10000] + - [9998] + - [10000] + m: 5 + n: 1 + target: 1 + out: 49997 + - name: "twenty_colors_two_houses" + in: + houses: [0, 0] + cost: + elemType: "int" + value: + - [ + 20, + 19, + 18, + 17, + 16, + 15, + 14, + 13, + 12, + 11, + 10, + 9, + 8, + 7, + 6, + 5, + 4, + 3, + 2, + 1, + ] + - [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + ] + m: 2 + n: 20 + target: 1 + out: 21 + - name: "fixed_color_forces_split" + in: + houses: [0, 1, 0, 1, 0, 1, 0] + cost: + elemType: "int" + value: + - [1, 100, 100] + - [100, 100, 100] + - [100, 1, 100] + - [100, 100, 100] + - [1, 100, 100] + - [100, 100, 100] + - [100, 1, 100] + m: 7 + n: 3 + target: 5 + - name: "high_target_with_unpainted_edges" + in: + houses: [0, 2, 0, 3, 0, 1, 0, 2, 0] + cost: + elemType: "int" + value: + - [9, 1, 9] + - [9, 9, 9] + - [1, 9, 9] + - [9, 9, 9] + - [9, 9, 1] + - [9, 9, 9] + - [1, 9, 9] + - [9, 9, 9] + - [9, 1, 9] + m: 9 + n: 3 + target: 7 + - name: "twenty_houses_four_colors_sparse_fixed" + in: + houses: [0, 1, 0, 0, 2, 0, 0, 3, 0, 0, 4, 0, 0, 1, 0, 0, 2, 0, 0, 3] + cost: + elemType: "int" + value: + - [4, 1, 9, 8] + - [5, 5, 5, 5] + - [1, 7, 6, 8] + - [2, 6, 5, 9] + - [5, 5, 5, 5] + - [8, 2, 7, 6] + - [6, 3, 1, 9] + - [5, 5, 5, 5] + - [7, 8, 2, 4] + - [1, 6, 9, 3] + - [5, 5, 5, 5] + - [4, 7, 3, 1] + - [8, 1, 6, 2] + - [5, 5, 5, 5] + - [2, 9, 4, 7] + - [6, 3, 8, 1] + - [5, 5, 5, 5] + - [9, 2, 6, 4] + - [3, 8, 1, 7] + - [5, 5, 5, 5] + m: 20 + n: 4 + target: 10 + - name: "generated_max_m_two_colors" + seed: 147301 + in: + houses: + gen: "array" + len: 100 + of: + gen: "int" + min: 0 + max: 2 + cost: + gen: "array" + len: 100 + elemType: "int" + of: + gen: "array" + len: 2 + elemType: "int" + of: + gen: "int" + min: 1 + max: 10000 + m: 100 + n: 2 + target: 1 + - name: "generated_max_m_three_colors" + seed: 147302 + in: + houses: + gen: "array" + len: 100 + of: + gen: "int" + min: 0 + max: 3 + cost: + gen: "array" + len: 100 + elemType: "int" + of: + gen: "array" + len: 3 + elemType: "int" + of: + gen: "int" + min: 1 + max: 10000 + m: 100 + n: 3 + target: 50 + - name: "generated_max_m_five_colors" + seed: 147303 + in: + houses: + gen: "array" + len: 100 + of: + gen: "int" + min: 0 + max: 5 + cost: + gen: "array" + len: 100 + elemType: "int" + of: + gen: "array" + len: 5 + elemType: "int" + of: + gen: "int" + min: 1 + max: 10000 + m: 100 + n: 5 + target: 100 + - name: "generated_max_m_ten_colors" + seed: 147304 + in: + houses: + gen: "array" + len: 100 + of: + gen: "int" + min: 0 + max: 10 + cost: + gen: "array" + len: 100 + elemType: "int" + of: + gen: "array" + len: 10 + elemType: "int" + of: + gen: "int" + min: 1 + max: 10000 + m: 100 + n: 10 + target: 37 + - name: "generated_max_m_twenty_colors" + seed: 147305 + in: + houses: + gen: "array" + len: 100 + of: + gen: "int" + min: 0 + max: 20 + cost: + gen: "array" + len: 100 + elemType: "int" + of: + gen: "array" + len: 20 + elemType: "int" + of: + gen: "int" + min: 1 + max: 10000 + m: 100 + n: 20 + target: 75 diff --git a/tests/1001-1500/1473. paint-house-iii/sol.cpp b/tests/1001-1500/1473. paint-house-iii/sol.cpp new file mode 100644 index 00000000..2e6cd450 --- /dev/null +++ b/tests/1001-1500/1473. paint-house-iii/sol.cpp @@ -0,0 +1,70 @@ +class Solution { +public: + int minCost(vector& houses, vector>& cost, int m, int n, int target) { + const int INF = 1000000000; + vector> prev(n, vector(target + 1, INF)); + if (houses[0] != 0) { + int c = houses[0] - 1; + prev[c][1] = 0; + } else { + for (int c = 0; c < n; c++) { + prev[c][1] = cost[0][c]; + } + } + for (int i = 1; i < m; i++) { + vector> curr(n, vector(target + 1, INF)); + if (houses[i] != 0) { + int c = houses[i] - 1; + int add = 0; + for (int k = 1; k <= target; k++) { + if (prev[c][k] < INF) { + if (prev[c][k] + add < curr[c][k]) { + curr[c][k] = prev[c][k] + add; + } + } + if (k > 1) { + int best = INF; + for (int pc = 0; pc < n; pc++) { + if (pc != c && prev[pc][k - 1] < best) { + best = prev[pc][k - 1]; + } + } + if (best < INF && best + add < curr[c][k]) { + curr[c][k] = best + add; + } + } + } + } else { + for (int c = 0; c < n; c++) { + int add = cost[i][c]; + for (int k = 1; k <= target; k++) { + if (prev[c][k] < INF) { + if (prev[c][k] + add < curr[c][k]) { + curr[c][k] = prev[c][k] + add; + } + } + if (k > 1) { + int best = INF; + for (int pc = 0; pc < n; pc++) { + if (pc != c && prev[pc][k - 1] < best) { + best = prev[pc][k - 1]; + } + } + if (best < INF && best + add < curr[c][k]) { + curr[c][k] = best + add; + } + } + } + } + } + prev = curr; + } + int ans = INF; + for (int c = 0; c < n; c++) { + if (prev[c][target] < ans) { + ans = prev[c][target]; + } + } + return ans >= INF ? -1 : ans; + } +}; diff --git a/tests/1001-1500/1473. paint-house-iii/sol.cs b/tests/1001-1500/1473. paint-house-iii/sol.cs new file mode 100644 index 00000000..279f3a57 --- /dev/null +++ b/tests/1001-1500/1473. paint-house-iii/sol.cs @@ -0,0 +1,81 @@ +public class Solution { + public int MinCost(int[] houses, int[][] cost, int m, int n, int target) { + int INF = 1000000000; + int[][] prev = new int[n][]; + for (int c = 0; c < n; c++) { + prev[c] = new int[target + 1]; + for (int k = 0; k <= target; k++) { + prev[c][k] = INF; + } + } + if (houses[0] != 0) { + int c = houses[0] - 1; + prev[c][1] = 0; + } else { + for (int c = 0; c < n; c++) { + prev[c][1] = cost[0][c]; + } + } + for (int i = 1; i < m; i++) { + int[][] curr = new int[n][]; + for (int c = 0; c < n; c++) { + curr[c] = new int[target + 1]; + for (int k = 0; k <= target; k++) { + curr[c][k] = INF; + } + } + if (houses[i] != 0) { + int c = houses[i] - 1; + int add = 0; + for (int k = 1; k <= target; k++) { + if (prev[c][k] < INF) { + if (prev[c][k] + add < curr[c][k]) { + curr[c][k] = prev[c][k] + add; + } + } + if (k > 1) { + int best = INF; + for (int pc = 0; pc < n; pc++) { + if (pc != c && prev[pc][k - 1] < best) { + best = prev[pc][k - 1]; + } + } + if (best < INF && best + add < curr[c][k]) { + curr[c][k] = best + add; + } + } + } + } else { + for (int c = 0; c < n; c++) { + int add = cost[i][c]; + for (int k = 1; k <= target; k++) { + if (prev[c][k] < INF) { + if (prev[c][k] + add < curr[c][k]) { + curr[c][k] = prev[c][k] + add; + } + } + if (k > 1) { + int best = INF; + for (int pc = 0; pc < n; pc++) { + if (pc != c && prev[pc][k - 1] < best) { + best = prev[pc][k - 1]; + } + } + if (best < INF && best + add < curr[c][k]) { + curr[c][k] = best + add; + } + } + } + } + } + prev = curr; + } + int ans = INF; + for (int c = 0; c < n; c++) { + if (prev[c][target] < ans) { + ans = prev[c][target]; + } + } + return ans >= INF ? -1 : ans; + } +} diff --git a/tests/1001-1500/1473. paint-house-iii/sol.dart b/tests/1001-1500/1473. paint-house-iii/sol.dart new file mode 100644 index 00000000..1297d45c --- /dev/null +++ b/tests/1001-1500/1473. paint-house-iii/sol.dart @@ -0,0 +1,69 @@ +class Solution { + int minCost(List houses, List> cost, int m, int n, int target) { + final int INF = 1000000000; + var prev = List.generate(n, (_) => List.filled(target + 1, INF)); + if (houses[0] != 0) { + int c = houses[0] - 1; + prev[c][1] = 0; + } else { + for (int c = 0; c < n; c++) { + prev[c][1] = cost[0][c]; + } + } + for (int i = 1; i < m; i++) { + var curr = List.generate(n, (_) => List.filled(target + 1, INF)); + if (houses[i] != 0) { + int c = houses[i] - 1; + int add = 0; + for (int k = 1; k <= target; k++) { + if (prev[c][k] < INF) { + if (prev[c][k] + add < curr[c][k]) { + curr[c][k] = prev[c][k] + add; + } + } + if (k > 1) { + int best = INF; + for (int pc = 0; pc < n; pc++) { + if (pc != c && prev[pc][k - 1] < best) { + best = prev[pc][k - 1]; + } + } + if (best < INF && best + add < curr[c][k]) { + curr[c][k] = best + add; + } + } + } + } else { + for (int c = 0; c < n; c++) { + int add = cost[i][c]; + for (int k = 1; k <= target; k++) { + if (prev[c][k] < INF) { + if (prev[c][k] + add < curr[c][k]) { + curr[c][k] = prev[c][k] + add; + } + } + if (k > 1) { + int best = INF; + for (int pc = 0; pc < n; pc++) { + if (pc != c && prev[pc][k - 1] < best) { + best = prev[pc][k - 1]; + } + } + if (best < INF && best + add < curr[c][k]) { + curr[c][k] = best + add; + } + } + } + } + } + prev = curr; + } + int ans = INF; + for (int c = 0; c < n; c++) { + if (prev[c][target] < ans) { + ans = prev[c][target]; + } + } + return ans >= INF ? -1 : ans; + } +} diff --git a/tests/1001-1500/1473. paint-house-iii/sol.go b/tests/1001-1500/1473. paint-house-iii/sol.go new file mode 100644 index 00000000..07552cde --- /dev/null +++ b/tests/1001-1500/1473. paint-house-iii/sol.go @@ -0,0 +1,82 @@ +func minCost(houses []int, cost [][]int, m int, n int, target int) int { + INF := int(1e9) + prev := make([][]int, n) + for c := 0; c < n; c++ { + prev[c] = make([]int, target+1) + for k := 0; k <= target; k++ { + prev[c][k] = INF + } + } + if houses[0] != 0 { + c := houses[0] - 1 + prev[c][1] = 0 + } else { + for c := 0; c < n; c++ { + prev[c][1] = cost[0][c] + } + } + for i := 1; i < m; i++ { + curr := make([][]int, n) + for c := 0; c < n; c++ { + curr[c] = make([]int, target+1) + for k := 0; k <= target; k++ { + curr[c][k] = INF + } + } + if houses[i] != 0 { + c := houses[i] - 1 + add := 0 + for k := 1; k <= target; k++ { + if prev[c][k] < INF { + if prev[c][k]+add < curr[c][k] { + curr[c][k] = prev[c][k] + add + } + } + if k > 1 { + best := INF + for pc := 0; pc < n; pc++ { + if pc != c && prev[pc][k-1] < best { + best = prev[pc][k-1] + } + } + if best < INF && best+add < curr[c][k] { + curr[c][k] = best + add + } + } + } + } else { + for c := 0; c < n; c++ { + add := cost[i][c] + for k := 1; k <= target; k++ { + if prev[c][k] < INF { + if prev[c][k]+add < curr[c][k] { + curr[c][k] = prev[c][k] + add + } + } + if k > 1 { + best := INF + for pc := 0; pc < n; pc++ { + if pc != c && prev[pc][k-1] < best { + best = prev[pc][k-1] + } + } + if best < INF && best+add < curr[c][k] { + curr[c][k] = best + add + } + } + } + } + } + prev = curr + } + ans := INF + for c := 0; c < n; c++ { + if prev[c][target] < ans { + ans = prev[c][target] + } + } + if ans >= INF { + return -1 + } + return ans +} diff --git a/tests/1001-1500/1473. paint-house-iii/sol.java b/tests/1001-1500/1473. paint-house-iii/sol.java new file mode 100644 index 00000000..e4a9f97e --- /dev/null +++ b/tests/1001-1500/1473. paint-house-iii/sol.java @@ -0,0 +1,79 @@ +class Solution { + public int minCost(int[] houses, int[][] cost, int m, int n, int target) { + int INF = Integer.MAX_VALUE / 2; + int[][] prev = new int[n][target + 1]; + for (int c = 0; c < n; c++) { + for (int k = 0; k <= target; k++) { + prev[c][k] = INF; + } + } + if (houses[0] != 0) { + int c = houses[0] - 1; + prev[c][1] = 0; + } else { + for (int c = 0; c < n; c++) { + prev[c][1] = cost[0][c]; + } + } + for (int i = 1; i < m; i++) { + int[][] curr = new int[n][target + 1]; + for (int c = 0; c < n; c++) { + for (int k = 0; k <= target; k++) { + curr[c][k] = INF; + } + } + if (houses[i] != 0) { + int c = houses[i] - 1; + int add = 0; + for (int k = 1; k <= target; k++) { + if (prev[c][k] < INF) { + if (prev[c][k] + add < curr[c][k]) { + curr[c][k] = prev[c][k] + add; + } + } + if (k > 1) { + int best = INF; + for (int pc = 0; pc < n; pc++) { + if (pc != c && prev[pc][k - 1] < best) { + best = prev[pc][k - 1]; + } + } + if (best < INF && best + add < curr[c][k]) { + curr[c][k] = best + add; + } + } + } + } else { + for (int c = 0; c < n; c++) { + int add = cost[i][c]; + for (int k = 1; k <= target; k++) { + if (prev[c][k] < INF) { + if (prev[c][k] + add < curr[c][k]) { + curr[c][k] = prev[c][k] + add; + } + } + if (k > 1) { + int best = INF; + for (int pc = 0; pc < n; pc++) { + if (pc != c && prev[pc][k - 1] < best) { + best = prev[pc][k - 1]; + } + } + if (best < INF && best + add < curr[c][k]) { + curr[c][k] = best + add; + } + } + } + } + } + prev = curr; + } + int ans = INF; + for (int c = 0; c < n; c++) { + if (prev[c][target] < ans) { + ans = prev[c][target]; + } + } + return ans >= INF ? -1 : ans; + } +} diff --git a/tests/1001-1500/1473. paint-house-iii/sol.kt b/tests/1001-1500/1473. paint-house-iii/sol.kt new file mode 100644 index 00000000..fa119323 --- /dev/null +++ b/tests/1001-1500/1473. paint-house-iii/sol.kt @@ -0,0 +1,69 @@ +class Solution { + fun minCost(houses: IntArray, cost: Array, m: Int, n: Int, target: Int): Int { + val INF = Int.MAX_VALUE / 2 + var prev = Array(n) { IntArray(target + 1) { INF } } + if (houses[0] != 0) { + val c = houses[0] - 1 + prev[c][1] = 0 + } else { + for (c in 0 until n) { + prev[c][1] = cost[0][c] + } + } + for (i in 1 until m) { + val curr = Array(n) { IntArray(target + 1) { INF } } + if (houses[i] != 0) { + val c = houses[i] - 1 + val add = 0 + for (k in 1..target) { + if (prev[c][k] < INF) { + if (prev[c][k] + add < curr[c][k]) { + curr[c][k] = prev[c][k] + add + } + } + if (k > 1) { + var best = INF + for (pc in 0 until n) { + if (pc != c && prev[pc][k - 1] < best) { + best = prev[pc][k - 1] + } + } + if (best < INF && best + add < curr[c][k]) { + curr[c][k] = best + add + } + } + } + } else { + for (c in 0 until n) { + val add = cost[i][c] + for (k in 1..target) { + if (prev[c][k] < INF) { + if (prev[c][k] + add < curr[c][k]) { + curr[c][k] = prev[c][k] + add + } + } + if (k > 1) { + var best = INF + for (pc in 0 until n) { + if (pc != c && prev[pc][k - 1] < best) { + best = prev[pc][k - 1] + } + } + if (best < INF && best + add < curr[c][k]) { + curr[c][k] = best + add + } + } + } + } + } + prev = curr + } + var ans = INF + for (c in 0 until n) { + if (prev[c][target] < ans) { + ans = prev[c][target] + } + } + return if (ans >= INF) -1 else ans + } +} diff --git a/tests/1001-1500/1473. paint-house-iii/sol.py b/tests/1001-1500/1473. paint-house-iii/sol.py new file mode 100644 index 00000000..7fbd52f5 --- /dev/null +++ b/tests/1001-1500/1473. paint-house-iii/sol.py @@ -0,0 +1,44 @@ +class Solution: + def minCost( + self, houses: list[int], cost: list[list[int]], m: int, n: int, target: int + ) -> int: + prev = [[float("inf")] * (target + 1) for _ in range(n)] + if houses[0]: + c = houses[0] - 1 + prev[c][1] = 0 + else: + for c in range(n): + prev[c][1] = cost[0][c] + for i in range(1, m): + curr = [[float("inf")] * (target + 1) for _ in range(n)] + if houses[i]: + c = houses[i] - 1 + add = 0 + for k in range(1, target + 1): + if prev[c][k] < float("inf"): + if prev[c][k] + add < curr[c][k]: + curr[c][k] = prev[c][k] + add + if k > 1: + best = float("inf") + for pc in range(n): + if pc != c and prev[pc][k - 1] < best: + best = prev[pc][k - 1] + if best < float("inf") and best + add < curr[c][k]: + curr[c][k] = best + add + else: + for c in range(n): + add = cost[i][c] + for k in range(1, target + 1): + if prev[c][k] < float("inf"): + if prev[c][k] + add < curr[c][k]: + curr[c][k] = prev[c][k] + add + if k > 1: + best = float("inf") + for pc in range(n): + if pc != c and prev[pc][k - 1] < best: + best = prev[pc][k - 1] + if best < float("inf") and best + add < curr[c][k]: + curr[c][k] = best + add + prev = curr + ans = min(prev[c][target] for c in range(n)) + return -1 if ans >= float("inf") else ans diff --git a/tests/1001-1500/1473. paint-house-iii/sol.py2 b/tests/1001-1500/1473. paint-house-iii/sol.py2 new file mode 100644 index 00000000..617ae5ce --- /dev/null +++ b/tests/1001-1500/1473. paint-house-iii/sol.py2 @@ -0,0 +1,50 @@ +class Solution(object): + def minCost(self, houses, cost, m, n, target): + """ + :type houses: List[int] + :type cost: List[List[int]] + :type m: int + :type n: int + :type target: int + :rtype: int + """ + prev = [[float('inf')] * (target + 1) for _ in range(n)] + if houses[0]: + c = houses[0] - 1 + prev[c][1] = 0 + else: + for c in range(n): + prev[c][1] = cost[0][c] + for i in range(1, m): + curr = [[float('inf')] * (target + 1) for _ in range(n)] + if houses[i]: + c = houses[i] - 1 + add = 0 + for k in range(1, target + 1): + if prev[c][k] < float('inf'): + if prev[c][k] + add < curr[c][k]: + curr[c][k] = prev[c][k] + add + if k > 1: + best = float('inf') + for pc in range(n): + if pc != c and prev[pc][k - 1] < best: + best = prev[pc][k - 1] + if best < float('inf') and best + add < curr[c][k]: + curr[c][k] = best + add + else: + for c in range(n): + add = cost[i][c] + for k in range(1, target + 1): + if prev[c][k] < float('inf'): + if prev[c][k] + add < curr[c][k]: + curr[c][k] = prev[c][k] + add + if k > 1: + best = float('inf') + for pc in range(n): + if pc != c and prev[pc][k - 1] < best: + best = prev[pc][k - 1] + if best < float('inf') and best + add < curr[c][k]: + curr[c][k] = best + add + prev = curr + ans = min(prev[c][target] for c in range(n)) + return -1 if ans >= float('inf') else ans diff --git a/tests/1001-1500/1473. paint-house-iii/sol.rb b/tests/1001-1500/1473. paint-house-iii/sol.rb new file mode 100644 index 00000000..93e70b89 --- /dev/null +++ b/tests/1001-1500/1473. paint-house-iii/sol.rb @@ -0,0 +1,68 @@ +# @param {Integer[]} houses +# @param {Integer[][]} cost +# @param {Integer} m +# @param {Integer} n +# @param {Integer} target +# @return {Integer} +def min_cost(houses, cost, m, n, target) + inf = Float::INFINITY + prev = Array.new(n) { Array.new(target + 1, inf) } + if houses[0] != 0 + c = houses[0] - 1 + prev[c][1] = 0 + else + (0...n).each do |c| + prev[c][1] = cost[0][c] + end + end + (1...m).each do |i| + curr = Array.new(n) { Array.new(target + 1, inf) } + if houses[i] != 0 + c = houses[i] - 1 + add = 0 + (1..target).each do |k| + if prev[c][k] < inf + if prev[c][k] + add < curr[c][k] + curr[c][k] = prev[c][k] + add + end + end + if k > 1 + best = inf + (0...n).each do |pc| + if pc != c && prev[pc][k - 1] < best + best = prev[pc][k - 1] + end + end + if best < inf && best + add < curr[c][k] + curr[c][k] = best + add + end + end + end + else + (0...n).each do |c| + add = cost[i][c] + (1..target).each do |k| + if prev[c][k] < inf + if prev[c][k] + add < curr[c][k] + curr[c][k] = prev[c][k] + add + end + end + if k > 1 + best = inf + (0...n).each do |pc| + if pc != c && prev[pc][k - 1] < best + best = prev[pc][k - 1] + end + end + if best < inf && best + add < curr[c][k] + curr[c][k] = best + add + end + end + end + end + end + prev = curr + end + ans = prev.map { |row| row[target] }.min + ans >= inf ? -1 : ans +end diff --git a/tests/1001-1500/1473. paint-house-iii/sol.rs b/tests/1001-1500/1473. paint-house-iii/sol.rs new file mode 100644 index 00000000..bcaf2e42 --- /dev/null +++ b/tests/1001-1500/1473. paint-house-iii/sol.rs @@ -0,0 +1,76 @@ +impl Solution { + pub fn min_cost(houses: Vec, cost: Vec>, m: i32, n: i32, target: i32) -> i32 { + let m = m as usize; + let n = n as usize; + let target = target as usize; + let inf = 1_000_000_000; + let mut prev = vec![vec![inf; target + 1]; n]; + if houses[0] != 0 { + let c = (houses[0] - 1) as usize; + prev[c][1] = 0; + } else { + for c in 0..n { + prev[c][1] = cost[0][c]; + } + } + for i in 1..m { + let mut curr = vec![vec![inf; target + 1]; n]; + if houses[i] != 0 { + let c = (houses[i] - 1) as usize; + let add = 0; + for k in 1..=target { + if prev[c][k] < inf { + if prev[c][k] + add < curr[c][k] { + curr[c][k] = prev[c][k] + add; + } + } + if k > 1 { + let mut best = inf; + for pc in 0..n { + if pc != c && prev[pc][k - 1] < best { + best = prev[pc][k - 1]; + } + } + if best < inf && best + add < curr[c][k] { + curr[c][k] = best + add; + } + } + } + } else { + for c in 0..n { + let add = cost[i][c]; + for k in 1..=target { + if prev[c][k] < inf { + if prev[c][k] + add < curr[c][k] { + curr[c][k] = prev[c][k] + add; + } + } + if k > 1 { + let mut best = inf; + for pc in 0..n { + if pc != c && prev[pc][k - 1] < best { + best = prev[pc][k - 1]; + } + } + if best < inf && best + add < curr[c][k] { + curr[c][k] = best + add; + } + } + } + } + } + prev = curr; + } + let mut ans = inf; + for c in 0..n { + if prev[c][target] < ans { + ans = prev[c][target]; + } + } + if ans >= inf { + -1 + } else { + ans + } + } +} diff --git a/tests/1001-1500/1473. paint-house-iii/sol.swift b/tests/1001-1500/1473. paint-house-iii/sol.swift new file mode 100644 index 00000000..a9098242 --- /dev/null +++ b/tests/1001-1500/1473. paint-house-iii/sol.swift @@ -0,0 +1,69 @@ +class Solution { + func minCost(_ houses: [Int], _ cost: [[Int]], _ m: Int, _ n: Int, _ target: Int) -> Int { + let INF = 1000000000 + var prev = Array(repeating: Array(repeating: INF, count: target + 1), count: n) + if houses[0] != 0 { + let c = houses[0] - 1 + prev[c][1] = 0 + } else { + for c in 0.. 1 { + var best = INF + for pc in 0.. 1 { + var best = INF + for pc in 0..= INF ? -1 : ans + } +} diff --git a/tests/1001-1500/1473. paint-house-iii/sol.ts b/tests/1001-1500/1473. paint-house-iii/sol.ts new file mode 100644 index 00000000..cc450c35 --- /dev/null +++ b/tests/1001-1500/1473. paint-house-iii/sol.ts @@ -0,0 +1,77 @@ +function minCost( + houses: number[], + cost: number[][], + m: number, + n: number, + target: number, +): number { + const INF = 1000000000; + let prev: number[][] = Array.from({ length: n }, () => + Array(target + 1).fill(INF), + ); + if (houses[0] !== 0) { + const c = houses[0] - 1; + prev[c][1] = 0; + } else { + for (let c = 0; c < n; c++) { + prev[c][1] = cost[0][c]; + } + } + for (let i = 1; i < m; i++) { + const curr: number[][] = Array.from({ length: n }, () => + Array(target + 1).fill(INF), + ); + if (houses[i] !== 0) { + const c = houses[i] - 1; + const add = 0; + for (let k = 1; k <= target; k++) { + if (prev[c][k] < INF) { + if (prev[c][k] + add < curr[c][k]) { + curr[c][k] = prev[c][k] + add; + } + } + if (k > 1) { + let best = INF; + for (let pc = 0; pc < n; pc++) { + if (pc !== c && prev[pc][k - 1] < best) { + best = prev[pc][k - 1]; + } + } + if (best < INF && best + add < curr[c][k]) { + curr[c][k] = best + add; + } + } + } + } else { + for (let c = 0; c < n; c++) { + const add = cost[i][c]; + for (let k = 1; k <= target; k++) { + if (prev[c][k] < INF) { + if (prev[c][k] + add < curr[c][k]) { + curr[c][k] = prev[c][k] + add; + } + } + if (k > 1) { + let best = INF; + for (let pc = 0; pc < n; pc++) { + if (pc !== c && prev[pc][k - 1] < best) { + best = prev[pc][k - 1]; + } + } + if (best < INF && best + add < curr[c][k]) { + curr[c][k] = best + add; + } + } + } + } + } + prev = curr; + } + let ans = INF; + for (let c = 0; c < n; c++) { + if (prev[c][target] < ans) { + ans = prev[c][target]; + } + } + return ans >= INF ? -1 : ans; +} diff --git a/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/manifest.yaml b/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/manifest.yaml new file mode 100644 index 00000000..c65a2939 --- /dev/null +++ b/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/manifest.yaml @@ -0,0 +1,217 @@ +entry: + id: 1475 + title: "final-prices-with-a-special-discount-in-a-shop" + params: + prices: + type: array + items: + type: int + call: + cpp: "Solution().finalPrices({prices})" + rust: "Solution::final_prices({prices})" + python3: "Solution().finalPrices({prices})" + python2: "Solution().finalPrices({prices})" + ruby: "final_prices({prices})" + java: "new Solution().finalPrices({prices})" + csharp: "new Solution().FinalPrices({prices})" + kotlin: "Solution().finalPrices({prices})" + go: "finalPrices({prices})" + dart: "Solution().finalPrices({prices})" + swift: "Solution().finalPrices({prices})" + typescript: "finalPrices({prices})" +judge: + type: exact +limits: + time_ms: 400 + memory_mb: 300 +oracle: + python3: + call: "Checker().finalPrices(prices, {result})" + checker: | + class Checker: + def finalPrices(self, prices, result): + expected = [] + for i, value in enumerate(prices): + discount = next((prices[j] for j in range(i+1, len(prices)) if prices[j] <= value), 0) + expected.append(value - discount) + return result == expected +seed: 1475 +tests: + - name: ex1 + in: + prices: [8, 4, 6, 2, 3] + out: [4, 2, 4, 2, 3] + - name: ex2 + in: + prices: [1, 2, 3, 4, 5] + out: [1, 2, 3, 4, 5] + - name: ex3 + in: + prices: [10, 1, 1, 6] + out: [9, 0, 1, 6] + - name: one + in: + prices: [5] + out: [5] + - name: equal + in: + prices: [4, 4, 4, 4] + - name: descending + in: + prices: [5, 4, 3, 2, 1] + - name: ascending + in: + prices: [1, 2, 3, 4, 5] + - name: all_high + in: + prices: [100, 100, 100] + - name: all_low + in: + prices: [1, 1, 1, 1] + - name: alternating + in: + prices: [5, 1, 5, 1, 5] + - name: delayed_discount + in: + prices: [10, 9, 8, 1] + - name: immediate_discount + in: + prices: [10, 1, 9, 2] + - name: no_discount + in: + prices: [2, 4, 6, 8, 10] + - name: duplicate_discount + in: + prices: [7, 5, 5, 3] + - name: varied_a + in: + prices: [12, 3, 8, 2, 10, 1] + - name: varied_b + in: + prices: [20, 15, 18, 4, 9] + - name: varied_c + in: + prices: [1, 100, 2, 99, 3, 98] + - name: varied_d + in: + prices: [50, 40, 30, 20, 10] + - name: varied_e + in: + prices: [10, 20, 10, 20, 10] + - name: generated_small + seed: 1501 + in: + prices: + gen: "array" + len: + gen: "int" + min: 1 + max: 20 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + sorted: false + - name: generated_medium + seed: 1502 + in: + prices: + gen: "array" + len: + gen: "int" + min: 25 + max: 60 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + sorted: false + - name: generated_boundary_values + seed: 1503 + in: + prices: + gen: "array" + len: + gen: "int" + min: 80 + max: 120 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + sorted: false + - name: generated_near_max + seed: 1504 + in: + prices: + gen: "array" + len: 499 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + sorted: false + - name: generated_max + seed: 1505 + in: + prices: + gen: "array" + len: 500 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + sorted: false + - name: max_price + in: + prices: [1000, 1, 1000, 1] + - name: min_price + in: + prices: [1, 1000, 1, 1000] + - name: blocks_a + in: + prices: [3, 3, 2, 2, 1, 1] + - name: blocks_b + in: + prices: [1, 1, 2, 2, 3, 3] + - name: blocks_c + in: + prices: [9, 9, 8, 8, 7, 7, 6, 6] + - name: peaks + in: + prices: [100, 1, 99, 2, 98, 3, 97] + - name: valleys + in: + prices: [1, 100, 2, 99, 3, 98] + - name: boundary_a + in: + prices: [999, 998, 997, 1] + - name: boundary_b + in: + prices: [1, 999, 998, 997] + - name: final_a + in: + prices: [25, 10, 20, 5, 15, 1] + - name: final_b + in: + prices: [31, 7, 23, 11, 19, 3, 17] + - name: equal_plateau_then_drop + in: + prices: [8, 8, 8, 7, 7, 6] + - name: first_lower_is_not_global_minimum + in: + prices: [15, 12, 14, 10, 11, 9] + - name: repeated_peak_valley + in: + prices: [20, 5, 20, 5, 20, 5, 20] + - name: minimum_at_both_ends + in: + prices: [1, 50, 40, 30, 20, 1] + - name: all_prices_at_constraint_maximum + in: + prices: [1000, 1000, 999, 1000, 1, 1000] diff --git a/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.cpp b/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.cpp new file mode 100644 index 00000000..249b5e2f --- /dev/null +++ b/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + vector finalPrices(vector& prices) { + vector stack; + for (int i = 0; i < prices.size(); i++) { + while (!stack.empty() && prices[stack.back()] >= prices[i]) { + int index = stack.back(); + stack.pop_back(); + prices[index] -= prices[i]; + } + stack.push_back(i); + } + return prices; + } +}; diff --git a/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.cs b/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.cs new file mode 100644 index 00000000..21100be7 --- /dev/null +++ b/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.cs @@ -0,0 +1,13 @@ +public class Solution { + public int[] FinalPrices(int[] prices) { + var stack = new System.Collections.Generic.Stack(); + for (int i = 0; i < prices.Length; i++) { + while (stack.Count > 0 && prices[stack.Peek()] >= prices[i]) { + int index = stack.Pop(); + prices[index] -= prices[i]; + } + stack.Push(i); + } + return prices; + } +} diff --git a/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.dart b/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.dart new file mode 100644 index 00000000..1bda664b --- /dev/null +++ b/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.dart @@ -0,0 +1,13 @@ +class Solution { + List finalPrices(List prices) { + List stack = []; + for (int i = 0; i < prices.length; i++) { + while (stack.isNotEmpty && prices[stack.last] >= prices[i]) { + int index = stack.removeLast(); + prices[index] -= prices[i]; + } + stack.add(i); + } + return prices; + } +} diff --git a/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.go b/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.go new file mode 100644 index 00000000..f629d517 --- /dev/null +++ b/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.go @@ -0,0 +1,12 @@ +func finalPrices(prices []int) []int { + stack := make([]int, 0, len(prices)) + for i, price := range prices { + for len(stack) > 0 && prices[stack[len(stack)-1]] >= price { + index := stack[len(stack)-1] + stack = stack[:len(stack)-1] + prices[index] -= price + } + stack = append(stack, i) + } + return prices +} diff --git a/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.java b/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.java new file mode 100644 index 00000000..ee6a7bd8 --- /dev/null +++ b/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.java @@ -0,0 +1,14 @@ +class Solution { + public int[] finalPrices(int[] prices) { + int[] stack = new int[prices.length]; + int top = -1; + for (int i = 0; i < prices.length; i++) { + while (top >= 0 && prices[stack[top]] >= prices[i]) { + int index = stack[top--]; + prices[index] -= prices[i]; + } + stack[++top] = i; + } + return prices; + } +} diff --git a/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.kt b/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.kt new file mode 100644 index 00000000..c3ce88e6 --- /dev/null +++ b/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.kt @@ -0,0 +1,13 @@ +class Solution { + fun finalPrices(prices: IntArray): IntArray { + val stack = ArrayDeque() + for (i in prices.indices) { + while (stack.isNotEmpty() && prices[stack.last()] >= prices[i]) { + val index = stack.removeLast() + prices[index] -= prices[i] + } + stack.addLast(i) + } + return prices + } +} diff --git a/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.py b/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.py new file mode 100644 index 00000000..a65d9da3 --- /dev/null +++ b/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.py @@ -0,0 +1,12 @@ +class Solution: + def finalPrices(self, prices: List[int]) -> List[int]: + stack = [] + + for i in range(len(prices)): + while stack and prices[stack[-1]] >= prices[i]: + index = stack.pop() + prices[index] -= prices[i] + + stack.append(i) + + return prices diff --git a/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.py2 b/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.py2 new file mode 100644 index 00000000..0f73468d --- /dev/null +++ b/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.py2 @@ -0,0 +1,13 @@ +class Solution(object): + def finalPrices(self, prices): + """ + :type prices: List[int] + :rtype: List[int] + """ + stack = [] + for i in range(len(prices)): + while stack and prices[stack[-1]] >= prices[i]: + index = stack.pop() + prices[index] -= prices[i] + stack.append(i) + return prices diff --git a/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.rb b/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.rb new file mode 100644 index 00000000..e225343f --- /dev/null +++ b/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.rb @@ -0,0 +1,13 @@ +# @param {Integer[]} prices +# @return {Integer[]} +def final_prices(prices) + stack = [] + prices.each_with_index do |price, i| + while !stack.empty? && prices[stack.last] >= price + index = stack.pop + prices[index] -= price + end + stack.push(i) + end + prices +end diff --git a/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.rs b/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.rs new file mode 100644 index 00000000..979b98bf --- /dev/null +++ b/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.rs @@ -0,0 +1,18 @@ +impl Solution { + pub fn final_prices(prices: Vec) -> Vec { + let mut prices = prices; + let mut stack: Vec = Vec::new(); + for i in 0..prices.len() { + while let Some(&last) = stack.last() { + if prices[last] >= prices[i] { + let index = stack.pop().unwrap(); + prices[index] -= prices[i]; + } else { + break; + } + } + stack.push(i); + } + prices + } +} diff --git a/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.swift b/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.swift new file mode 100644 index 00000000..f30eb223 --- /dev/null +++ b/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.swift @@ -0,0 +1,14 @@ +class Solution { + func finalPrices(_ prices: [Int]) -> [Int] { + var prices = prices + var stack: [Int] = [] + for i in 0..= prices[i] { + let index = stack.removeLast() + prices[index] -= prices[i] + } + stack.append(i) + } + return prices + } +} diff --git a/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.ts b/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.ts new file mode 100644 index 00000000..a5eb8334 --- /dev/null +++ b/tests/1001-1500/1475. final-prices-with-a-special-discount-in-a-shop/sol.ts @@ -0,0 +1,11 @@ +function finalPrices(prices: number[]): number[] { + const stack: number[] = []; + for (let i = 0; i < prices.length; i++) { + while (stack.length > 0 && prices[stack[stack.length - 1]] >= prices[i]) { + const index = stack.pop()!; + prices[index] -= prices[i]; + } + stack.push(i); + } + return prices; +} diff --git a/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/manifest.yaml b/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/manifest.yaml new file mode 100644 index 00000000..c2e7bf49 --- /dev/null +++ b/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/manifest.yaml @@ -0,0 +1,262 @@ +entry: + id: 1477 + title: "find-two-non-overlapping-sub-arrays-each-with-target-sum" + params: + arr: + type: array + items: + type: int + target: + type: int + call: + cpp: "Solution().minSumOfLengths({arr}, {target})" + rust: "Solution::min_sum_of_lengths({arr}, {target})" + python3: "Solution().minSumOfLengths({arr}, {target})" + python2: "Solution().minSumOfLengths({arr}, {target})" + ruby: "min_sum_of_lengths({arr}, {target})" + java: "new Solution().minSumOfLengths({arr}, {target})" + csharp: "new Solution().MinSumOfLengths({arr}, {target})" + kotlin: "Solution().minSumOfLengths({arr}, {target})" + go: "minSumOfLengths({arr}, {target})" + dart: "Solution().minSumOfLengths({arr}, {target})" + swift: "Solution().minSumOfLengths({arr}, {target})" + typescript: "minSumOfLengths({arr}, {target})" +judge: + type: "exact" +limits: + time_ms: 900 + memory_mb: 256 +oracle: + python3: + call: "Checker().minSumOfLengths(arr, target, {result})" + checker: | + class Checker: + def minSumOfLengths(self, arr, target, result): + n = len(arr) + best_before = [n + 1] * n + left = 0 + current = 0 + answer = n + 1 + for right, value in enumerate(arr): + current += value + while left <= right and current > target: + current -= arr[left] + left += 1 + best_before[right] = best_before[right - 1] if right else n + 1 + if current == target: + length = right - left + 1 + if left and best_before[left - 1] <= n: + answer = min(answer, best_before[left - 1] + length) + best_before[right] = min(best_before[right], length) + expected = -1 if answer == n + 1 else answer + return result == expected +seed: 1477 +tests: + - name: "official-one" + in: + arr: [3, 2, 2, 4, 3] + target: 3 + out: 2 + - name: "official-two" + in: + arr: [7, 3, 4, 7] + target: 7 + out: 2 + - name: "official-three" + in: + arr: [4, 3, 2, 6, 2, 3, 4] + target: 6 + out: -1 + - name: "single-no-pair" + in: + arr: [5] + target: 5 + - name: "two-singletons" + in: + arr: [5, 5] + target: 5 + - name: "adjacent-pairs" + in: + arr: [2, 2, 2, 2] + target: 2 + - name: "two-length-two" + in: + arr: [1, 2, 3, 1, 2] + target: 3 + - name: "no-target" + in: + arr: [1, 1, 1] + target: 10 + - name: "whole-array-only" + in: + arr: [1, 2, 3] + target: 6 + - name: "repeated-singletons" + in: + arr: [4, 1, 4, 1, 4] + target: 4 + - name: "separated-long-runs" + in: + arr: [1, 1, 1, 9, 1, 1, 1] + target: 3 + - name: "overlapping-candidates" + in: + arr: [1, 1, 1, 1] + target: 2 + - name: "choose-shortest" + in: + arr: [1, 1, 2, 2, 1, 1] + target: 2 + - name: "large-target" + in: + arr: [1000, 1000, 1000, 1000] + target: 2000 + - name: "target-one" + in: + arr: [1, 2, 1, 3, 1] + target: 1 + - name: "target-two" + in: + arr: [1, 1, 1, 1, 1] + target: 2 + - name: "target-three" + in: + arr: [1, 1, 1, 1, 1, 1] + target: 3 + - name: "uneven-solutions" + in: + arr: [1, 2, 1, 1, 1, 2] + target: 3 + - name: "far-apart-singletons" + in: + arr: [8, 1, 1, 1, 8] + target: 8 + - name: "middle-solutions" + in: + arr: [9, 2, 2, 2, 9, 2, 2, 2] + target: 6 + - name: "all-equal-length-three" + in: + arr: [2, 2, 2, 2, 2, 2] + target: 6 + - name: "all-equal-length-one" + in: + arr: [3, 3, 3, 3, 3] + target: 3 + - name: "large-elements" + in: + arr: [999, 1, 999, 1, 999] + target: 1000 + - name: "one-long-one-short" + in: + arr: [1, 1, 1, 1, 5, 5] + target: 5 + - name: "two-long-separated" + in: + arr: [2, 2, 2, 9, 3, 3, 3] + target: 6 + - name: "near-end-pairs" + in: + arr: [9, 9, 1, 1, 9, 9] + target: 2 + - name: "many-overlaps" + in: + arr: [1, 1, 1, 1, 1, 1, 1] + target: 3 + - name: "three-singletons" + in: + arr: [6, 2, 6, 4, 6] + target: 6 + - name: "no-two-disjoint" + in: + arr: [2, 3, 2] + target: 5 + - name: "exact-boundary-sums" + in: + arr: [1, 4, 1, 4, 1] + target: 5 + - name: "alternating-small" + in: + arr: [1, 2, 1, 2, 1, 2, 1] + target: 3 + - name: "alternating-large" + in: + arr: [5, 1, 5, 1, 5, 1] + target: 6 + - name: "leading-filler" + in: + arr: [9, 9, 2, 2, 9, 2, 2] + target: 4 + - name: "trailing-filler" + in: + arr: [2, 2, 9, 2, 2, 9, 9] + target: 4 + - name: "minimum-values" + in: + arr: [1, 1, 1, 1] + target: 1 + - name: "generated-all-ones-singletons" + in: + arr: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 1 + distinct: false + sorted: false + elemType: "int" + target: 1 + - name: "generated-all-ones-pairs" + in: + arr: + gen: "array" + len: 99999 + of: + gen: "int" + min: 1 + max: 1 + distinct: false + sorted: false + elemType: "int" + target: 2 + - name: "generated-max-values" + in: + arr: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1000 + max: 1000 + distinct: false + sorted: false + elemType: "int" + target: 1000 + - name: "generated-wide-values" + in: + arr: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + sorted: false + elemType: "int" + target: 100000000 + - name: "generated-target-two" + in: + arr: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 2 + distinct: false + sorted: false + elemType: "int" + target: 2 diff --git a/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.cpp b/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.cpp new file mode 100644 index 00000000..5cfb4dcd --- /dev/null +++ b/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + int minSumOfLengths(vector& arr, int target) { + int n = arr.size(); + vector bestLeft(n, n); + int minTotal = INT_MAX; + int left = 0; + int curr = 0; + for (int right = 0; right < n; ++right) { + curr += arr[right]; + while (curr > target) { + curr -= arr[left]; + ++left; + } + if (curr == target) { + int length = right - left + 1; + if (right > 0) { + bestLeft[right] = min(bestLeft[right - 1], length); + } else { + bestLeft[right] = length; + } + if (left > 0 && bestLeft[left - 1] != n) { + minTotal = min(minTotal, bestLeft[left - 1] + length); + } + } else { + if (right > 0) { + bestLeft[right] = bestLeft[right - 1]; + } + } + } + return minTotal == INT_MAX ? -1 : minTotal; + } +}; diff --git a/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.cs b/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.cs new file mode 100644 index 00000000..30fe1034 --- /dev/null +++ b/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.cs @@ -0,0 +1,35 @@ +public class Solution { + public int MinSumOfLengths(int[] arr, int target) { + int n = arr.Length; + int[] bestLeft = new int[n]; + for (int i = 0; i < n; i++) { + bestLeft[i] = n; + } + int minTotal = int.MaxValue; + int left = 0; + int curr = 0; + for (int right = 0; right < n; right++) { + curr += arr[right]; + while (curr > target) { + curr -= arr[left]; + left++; + } + if (curr == target) { + int length = right - left + 1; + if (right > 0) { + bestLeft[right] = Math.Min(bestLeft[right - 1], length); + } else { + bestLeft[right] = length; + } + if (left > 0 && bestLeft[left - 1] != n) { + minTotal = Math.Min(minTotal, bestLeft[left - 1] + length); + } + } else { + if (right > 0) { + bestLeft[right] = bestLeft[right - 1]; + } + } + } + return minTotal == int.MaxValue ? -1 : minTotal; + } +} diff --git a/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.dart b/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.dart new file mode 100644 index 00000000..9e11ba90 --- /dev/null +++ b/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.dart @@ -0,0 +1,32 @@ +class Solution { + int minSumOfLengths(List arr, int target) { + int n = arr.length; + List bestLeft = List.filled(n, n); + int minTotal = 1 << 60; // large number + int left = 0; + int curr = 0; + for (int right = 0; right < n; right++) { + curr += arr[right]; + while (curr > target) { + curr -= arr[left]; + left++; + } + if (curr == target) { + int length = right - left + 1; + if (right > 0) { + bestLeft[right] = bestLeft[right - 1] < length ? bestLeft[right - 1] : length; + } else { + bestLeft[right] = length; + } + if (left > 0 && bestLeft[left - 1] != n) { + minTotal = minTotal < bestLeft[left - 1] + length ? minTotal : bestLeft[left - 1] + length; + } + } else { + if (right > 0) { + bestLeft[right] = bestLeft[right - 1]; + } + } + } + return minTotal == 1 << 60 ? -1 : minTotal; + } +} diff --git a/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.go b/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.go new file mode 100644 index 00000000..d2b45b1a --- /dev/null +++ b/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.go @@ -0,0 +1,42 @@ +func minSumOfLengths(arr []int, target int) int { + n := len(arr) + bestLeft := make([]int, n) + for i := range bestLeft { + bestLeft[i] = n + } + minTotal := int(^uint(0) >> 1) // max int + left := 0 + curr := 0 + for right := 0; right < n; right++ { + curr += arr[right] + for curr > target { + curr -= arr[left] + left++ + } + if curr == target { + length := right - left + 1 + if right > 0 { + if bestLeft[right-1] < length { + bestLeft[right] = bestLeft[right-1] + } else { + bestLeft[right] = length + } + } else { + bestLeft[right] = length + } + if left > 0 && bestLeft[left-1] != n { + if bestLeft[left-1]+length < minTotal { + minTotal = bestLeft[left-1] + length + } + } + } else { + if right > 0 { + bestLeft[right] = bestLeft[right-1] + } + } + } + if minTotal == int(^uint(0)>>1) { + return -1 + } + return minTotal +} diff --git a/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.java b/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.java new file mode 100644 index 00000000..101aef96 --- /dev/null +++ b/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.java @@ -0,0 +1,35 @@ +class Solution { + public int minSumOfLengths(int[] arr, int target) { + int n = arr.length; + int[] bestLeft = new int[n]; + for (int i = 0; i < n; i++) { + bestLeft[i] = n; + } + int minTotal = Integer.MAX_VALUE; + int left = 0; + int curr = 0; + for (int right = 0; right < n; right++) { + curr += arr[right]; + while (curr > target) { + curr -= arr[left]; + left++; + } + if (curr == target) { + int length = right - left + 1; + if (right > 0) { + bestLeft[right] = Math.min(bestLeft[right - 1], length); + } else { + bestLeft[right] = length; + } + if (left > 0 && bestLeft[left - 1] != n) { + minTotal = Math.min(minTotal, bestLeft[left - 1] + length); + } + } else { + if (right > 0) { + bestLeft[right] = bestLeft[right - 1]; + } + } + } + return minTotal == Integer.MAX_VALUE ? -1 : minTotal; + } +} diff --git a/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.kt b/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.kt new file mode 100644 index 00000000..e4b0913f --- /dev/null +++ b/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.kt @@ -0,0 +1,32 @@ +class Solution { + fun minSumOfLengths(arr: IntArray, target: Int): Int { + val n = arr.size + val bestLeft = IntArray(n) { n } + var minTotal = Int.MAX_VALUE + var left = 0 + var curr = 0 + for (right in arr.indices) { + curr += arr[right] + while (curr > target) { + curr -= arr[left] + left++ + } + if (curr == target) { + val length = right - left + 1 + if (right > 0) { + bestLeft[right] = minOf(bestLeft[right - 1], length) + } else { + bestLeft[right] = length + } + if (left > 0 && bestLeft[left - 1] != n) { + minTotal = minOf(minTotal, bestLeft[left - 1] + length) + } + } else { + if (right > 0) { + bestLeft[right] = bestLeft[right - 1] + } + } + } + return if (minTotal == Int.MAX_VALUE) -1 else minTotal + } +} diff --git a/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.py b/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.py new file mode 100644 index 00000000..cc61f963 --- /dev/null +++ b/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.py @@ -0,0 +1,21 @@ +class Solution: + def minSumOfLengths(self, arr: List[int], target: int) -> int: + n = len(arr) + best_left = [n] * n + min_total = float("inf") + left = 0 + curr = 0 + for right, val in enumerate(arr): + curr += val + while curr > target: + curr -= arr[left] + left += 1 + if curr == target: + length = right - left + 1 + best_left[right] = min(best_left[right - 1], length) + if left > 0 and best_left[left - 1] != n: + min_total = min(min_total, best_left[left - 1] + length) + + else: + best_left[right] = best_left[right - 1] + return min_total if min_total != float("inf") else -1 diff --git a/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.py2 b/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.py2 new file mode 100644 index 00000000..40686bd7 --- /dev/null +++ b/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.py2 @@ -0,0 +1,29 @@ +class Solution(object): + def minSumOfLengths(self, arr, target): + """ + :type arr: List[int] + :type target: int + :rtype: int + """ + n = len(arr) + best_left = [n] * n + min_total = float('inf') + left = 0 + curr = 0 + for right in range(n): + curr += arr[right] + while curr > target: + curr -= arr[left] + left += 1 + if curr == target: + length = right - left + 1 + if right > 0: + best_left[right] = min(best_left[right - 1], length) + else: + best_left[right] = length + if left > 0 and best_left[left - 1] != n: + min_total = min(min_total, best_left[left - 1] + length) + else: + if right > 0: + best_left[right] = best_left[right - 1] + return min_total if min_total != float('inf') else -1 diff --git a/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.rb b/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.rb new file mode 100644 index 00000000..1dbdb252 --- /dev/null +++ b/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.rb @@ -0,0 +1,33 @@ +# @param {Integer[]} arr +# @param {Integer} target +# @return {Integer} +def min_sum_of_lengths(arr, target) + n = arr.length + best_left = Array.new(n, n) + min_total = Float::INFINITY + left = 0 + curr = 0 + arr.each_with_index do |val, right| + curr += val + while curr > target + curr -= arr[left] + left += 1 + end + if curr == target + length = right - left + 1 + if right > 0 + best_left[right] = [best_left[right - 1], length].min + else + best_left[right] = length + end + if left > 0 && best_left[left - 1] != n + min_total = [min_total, best_left[left - 1] + length].min + end + else + if right > 0 + best_left[right] = best_left[right - 1] + end + end + end + min_total == Float::INFINITY ? -1 : min_total +end diff --git a/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.rs b/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.rs new file mode 100644 index 00000000..81b224ff --- /dev/null +++ b/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.rs @@ -0,0 +1,30 @@ +impl Solution { + pub fn min_sum_of_lengths(arr: Vec, target: i32) -> i32 { + let n = arr.len(); + let mut best_left = vec![n as i32; n]; + let mut min_total = i32::MAX; + let mut left = 0; + let mut curr = 0; + for right in 0..n { + curr += arr[right]; + while curr > target { + curr -= arr[left]; + left += 1; + } + if curr == target { + let length = (right - left + 1) as i32; + if right > 0 { + best_left[right] = best_left[right - 1].min(length); + } else { + best_left[right] = length; + } + if left > 0 && best_left[left - 1] != n as i32 { + min_total = min_total.min(best_left[left - 1] + length); + } + } else if right > 0 { + best_left[right] = best_left[right - 1]; + } + } + if min_total == i32::MAX { -1 } else { min_total } + } +} diff --git a/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.swift b/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.swift new file mode 100644 index 00000000..f0bd6957 --- /dev/null +++ b/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.swift @@ -0,0 +1,32 @@ +class Solution { + func minSumOfLengths(_ arr: [Int], _ target: Int) -> Int { + let n = arr.count + var bestLeft = [Int](repeating: n, count: n) + var minTotal = Int.max + var left = 0 + var curr = 0 + for right in 0.. target { + curr -= arr[left] + left += 1 + } + if curr == target { + let length = right - left + 1 + if right > 0 { + bestLeft[right] = min(bestLeft[right - 1], length) + } else { + bestLeft[right] = length + } + if left > 0 && bestLeft[left - 1] != n { + minTotal = min(minTotal, bestLeft[left - 1] + length) + } + } else { + if right > 0 { + bestLeft[right] = bestLeft[right - 1] + } + } + } + return minTotal == Int.max ? -1 : minTotal + } +} diff --git a/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.ts b/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.ts new file mode 100644 index 00000000..bb35a3d5 --- /dev/null +++ b/tests/1001-1500/1477. find-two-non-overlapping-sub-arrays-each-with-target-sum/sol.ts @@ -0,0 +1,30 @@ +function minSumOfLengths(arr: number[], target: number): number { + const n = arr.length; + const bestLeft: number[] = new Array(n).fill(n); + let minTotal = Number.MAX_SAFE_INTEGER; + let left = 0; + let curr = 0; + for (let right = 0; right < n; right++) { + curr += arr[right]; + while (curr > target) { + curr -= arr[left]; + left++; + } + if (curr === target) { + const length = right - left + 1; + if (right > 0) { + bestLeft[right] = Math.min(bestLeft[right - 1], length); + } else { + bestLeft[right] = length; + } + if (left > 0 && bestLeft[left - 1] !== n) { + minTotal = Math.min(minTotal, bestLeft[left - 1] + length); + } + } else { + if (right > 0) { + bestLeft[right] = bestLeft[right - 1]; + } + } + } + return minTotal === Number.MAX_SAFE_INTEGER ? -1 : minTotal; +} diff --git a/tests/1001-1500/1478. allocate-mailboxes/manifest.yaml b/tests/1001-1500/1478. allocate-mailboxes/manifest.yaml new file mode 100644 index 00000000..313632ef --- /dev/null +++ b/tests/1001-1500/1478. allocate-mailboxes/manifest.yaml @@ -0,0 +1,248 @@ +entry: + id: 1478 + title: allocate-mailboxes + params: + houses: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().minDistance({houses}, {k})" + rust: "Solution::min_distance({houses}, {k})" + python3: "Solution().minDistance({houses}, {k})" + python2: "Solution().minDistance({houses}, {k})" + ruby: "min_distance({houses}, {k})" + java: "new Solution().minDistance({houses}, {k})" + csharp: "new Solution().MinDistance({houses}, {k})" + kotlin: "Solution().minDistance({houses}, {k})" + go: "minDistance({houses}, {k})" + dart: "Solution().minDistance({houses}, {k})" + swift: "Solution().minDistance({houses}, {k})" + typescript: "minDistance({houses}, {k})" +judge: + type: exact +limits: + time_ms: 5000 + memory_mb: 512 +oracle: + python3: + call: "Checker().minDistance(houses, k, {result})" + checker: | + class Checker: + def minDistance(self, houses, k, result): + if type(result) is not int or len(houses) < 1 or not (1 <= k <= len(houses)): + return False + a = sorted(houses) + n = len(a) + cost = [[0] * n for _ in range(n)] + for i in range(n): + for j in range(i, n): + mid = (i + j) // 2 + cost[i][j] = sum(abs(a[x] - a[mid]) for x in range(i, j + 1)) + inf = 10 ** 30 + dp = [[inf] * (n + 1) for _ in range(k + 1)] + dp[0][0] = 0 + for boxes in range(1, k + 1): + for used in range(1, n + 1): + dp[boxes][used] = min(dp[boxes - 1][start] + cost[start][used - 1] for start in range(used)) + return result == dp[k][n] +seed: 1478 +tests: + - name: prompt-example-one + in: + houses: [1, 4, 8, 10, 20] + k: 3 + - name: prompt-example-two + in: + houses: [2, 3, 5, 12, 18] + k: 2 + - name: two-houses-one-box + in: + houses: [1, 10] + k: 1 + - name: two-houses-two-boxes + in: + houses: [1, 10] + k: 2 + - name: consecutive-one-box + in: + houses: [1, 2, 3, 4, 5] + k: 1 + - name: consecutive-all-boxes + in: + houses: [1, 2, 3, 4, 5] + k: 5 + - name: single-cluster-even + in: + houses: [1, 4, 7, 10] + k: 1 + - name: single-cluster-odd + in: + houses: [1, 4, 8, 10, 20] + k: 1 + - name: separated-pairs + in: + houses: [1, 2, 100, 101] + k: 2 + - name: separated-three + in: + houses: [1, 50, 100] + k: 2 + - name: outlier-right + in: + houses: [1, 2, 3, 4, 100] + k: 2 + - name: outlier-left + in: + houses: [1, 100, 101, 102, 103] + k: 2 + - name: two-dense-clusters + in: + houses: [10, 11, 12, 50, 51, 52] + k: 2 + - name: three-dense-clusters + in: + houses: [1, 2, 3, 20, 21, 22, 100, 101, 102] + k: 3 + - name: k-near-n + in: + houses: [2, 8, 15, 30, 45, 90] + k: 5 + - name: k-one-wide-range + in: + houses: [1, 25, 50, 75, 100] + k: 1 + - name: large-coordinate-gap + in: + houses: [1, 1000, 5000, 9999] + k: 2 + - name: uneven-gaps + in: + houses: [3, 4, 20, 21, 22, 80, 200] + k: 3 + - name: median-left-tie + in: + houses: [1, 3, 5, 7] + k: 2 + - name: median-right-tie + in: + houses: [2, 6, 10, 14, 18, 22] + k: 3 + - name: duplicate-spacing-pattern + in: + houses: [5, 6, 7, 20, 21, 22, 23, 100] + k: 3 + - name: five-boxes + in: + houses: [4, 10, 11, 12, 40, 41, 90] + k: 5 + - name: two-box-balanced + in: + houses: [1, 10, 11, 20, 21, 30] + k: 2 + - name: three-box-unbalanced + in: + houses: [1, 2, 3, 4, 50, 51, 100, 101, 102] + k: 3 + - name: powers-of-ten + in: + houses: [1, 10, 100, 1000, 10000] + k: 2 + - name: near-maximum-values + in: + houses: [9990, 9992, 9994, 9996, 9998, 10000] + k: 2 + - name: alternating-gaps + in: + houses: [1, 2, 20, 21, 100, 101, 500, 501] + k: 4 + - name: long-middle-cluster + in: + houses: [1, 2, 3, 4, 5, 6, 7, 50, 100] + k: 3 + - name: endpoints-and-middle + in: + houses: [10, 11, 12, 90, 91, 92, 93] + k: 2 + - name: seven-houses-four-boxes + in: + houses: [2, 5, 9, 30, 31, 70, 100] + k: 4 + - name: eight-houses-three-boxes + in: + houses: [1, 4, 8, 9, 10, 40, 80, 81] + k: 3 + - name: nine-houses-four-boxes + in: + houses: [1, 2, 10, 11, 12, 50, 51, 90, 100] + k: 4 + - name: ten-houses-five-boxes + in: + houses: [3, 7, 8, 20, 21, 22, 60, 61, 90, 200] + k: 5 + - name: dense-and-isolated + in: + houses: [100, 101, 102, 103, 104, 500, 900, 901, 902, 1000] + k: 4 + - name: maximum-k-one + in: + houses: [1, 17, 33, 49, 65, 81, 97, 113, 129, 145] + k: 1 + - name: maximum-k-all + in: + houses: [1, 17, 33, 49, 65, 81, 97, 113, 129, 145] + k: 10 + - name: generated-maximum-houses-one-box + in: + houses: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 10000 + distinct: true + sorted: false + elemType: "int" + k: 1 + - name: generated-maximum-houses-half-boxes + in: + houses: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 10000 + distinct: true + sorted: false + elemType: "int" + k: 50 + - name: generated-maximum-houses-near-all-boxes + in: + houses: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 10000 + distinct: true + sorted: false + elemType: "int" + k: 99 + - name: generated-maximum-houses-all-boxes + in: + houses: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 10000 + distinct: true + sorted: false + elemType: "int" + k: 100 diff --git a/tests/1001-1500/1478. allocate-mailboxes/sol.cpp b/tests/1001-1500/1478. allocate-mailboxes/sol.cpp new file mode 100644 index 00000000..fcc3962d --- /dev/null +++ b/tests/1001-1500/1478. allocate-mailboxes/sol.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + int minDistance(vector& houses, int k) { + int n = houses.size(); + sort(houses.begin(), houses.end()); + vector P(n + 1, 0); + for (int i = 0; i < n; i++) { + P[i + 1] = P[i] + houses[i]; + } + + vector> G(n, vector(n, 0)); + for (int i = 0; i < n; i++) { + for (int j = i; j < n; j++) { + int mid = (i + j) / 2; + int countLeft = mid - i + 1; + int countRight = j - mid; + int sumLeft = P[mid + 1] - P[i]; + int sumRight = P[j + 1] - P[mid + 1]; + G[i][j] = (houses[mid] * countLeft - sumLeft) + (sumRight - houses[mid] * countRight); + } + } + + vector> dp(k + 1, vector(n + 1, 1e9)); + dp[0][0] = 0; + + for (int m = 1; m <= k; m++) { + for (int j = 1; j <= n; j++) { + int best = 1e9; + for (int i = 0; i < j; i++) { + best = min(best, dp[m-1][i] + G[i][j-1]); + } + dp[m][j] = best; + } + } + + return dp[k][n]; + } +}; diff --git a/tests/1001-1500/1478. allocate-mailboxes/sol.cs b/tests/1001-1500/1478. allocate-mailboxes/sol.cs new file mode 100644 index 00000000..6becfaa5 --- /dev/null +++ b/tests/1001-1500/1478. allocate-mailboxes/sol.cs @@ -0,0 +1,42 @@ +public class Solution { + public int MinDistance(int[] houses, int k) { + int n = houses.Length; + Array.Sort(houses); + int[] P = new int[n + 1]; + for (int i = 0; i < n; i++) { + P[i + 1] = P[i] + houses[i]; + } + + int[,] G = new int[n, n]; + for (int i = 0; i < n; i++) { + for (int j = i; j < n; j++) { + int mid = (i + j) / 2; + int countLeft = mid - i + 1; + int countRight = j - mid; + int sumLeft = P[mid + 1] - P[i]; + int sumRight = P[j + 1] - P[mid + 1]; + G[i, j] = (houses[mid] * countLeft - sumLeft) + (sumRight - houses[mid] * countRight); + } + } + + int[,] dp = new int[k + 1, n + 1]; + for (int i = 0; i <= k; i++) { + for (int j = 0; j <= n; j++) { + dp[i, j] = 1000000000; + } + } + dp[0, 0] = 0; + + for (int m = 1; m <= k; m++) { + for (int j = 1; j <= n; j++) { + int best = int.MaxValue; + for (int i = 0; i < j; i++) { + best = Math.Min(best, dp[m-1, i] + G[i, j-1]); + } + dp[m, j] = best; + } + } + + return dp[k, n]; + } +} diff --git a/tests/1001-1500/1478. allocate-mailboxes/sol.dart b/tests/1001-1500/1478. allocate-mailboxes/sol.dart new file mode 100644 index 00000000..28c39353 --- /dev/null +++ b/tests/1001-1500/1478. allocate-mailboxes/sol.dart @@ -0,0 +1,38 @@ +class Solution { + int minDistance(List houses, int k) { + int n = houses.length; + houses.sort(); + List P = List.filled(n + 1, 0); + for (int i = 0; i < n; i++) { + P[i + 1] = P[i] + houses[i]; + } + + List> G = List.generate(n, (_) => List.filled(n, 0)); + for (int i = 0; i < n; i++) { + for (int j = i; j < n; j++) { + int mid = (i + j) ~/ 2; + int countLeft = mid - i + 1; + int countRight = j - mid; + int sumLeft = P[mid + 1] - P[i]; + int sumRight = P[j + 1] - P[mid + 1]; + G[i][j] = (houses[mid] * countLeft - sumLeft) + (sumRight - houses[mid] * countRight); + } + } + + List> dp = List.generate(k + 1, (_) => List.filled(n + 1, 1 << 30)); + dp[0][0] = 0; + + for (int m = 1; m <= k; m++) { + for (int j = 1; j <= n; j++) { + int best = 1 << 30; + for (int i = 0; i < j; i++) { + int cand = dp[m-1][i] + G[i][j-1]; + if (cand < best) best = cand; + } + dp[m][j] = best; + } + } + + return dp[k][n]; + } +} diff --git a/tests/1001-1500/1478. allocate-mailboxes/sol.go b/tests/1001-1500/1478. allocate-mailboxes/sol.go new file mode 100644 index 00000000..2ed8b822 --- /dev/null +++ b/tests/1001-1500/1478. allocate-mailboxes/sol.go @@ -0,0 +1,46 @@ +func minDistance(houses []int, k int) int { + n := len(houses) + sort.Ints(houses) + P := make([]int, n+1) + for i := 0; i < n; i++ { + P[i+1] = P[i] + houses[i] + } + + G := make([][]int, n) + for i := range G { + G[i] = make([]int, n) + } + for i := 0; i < n; i++ { + for j := i; j < n; j++ { + mid := (i + j) / 2 + countLeft := mid - i + 1 + countRight := j - mid + sumLeft := P[mid+1] - P[i] + sumRight := P[j+1] - P[mid+1] + G[i][j] = (houses[mid]*countLeft - sumLeft) + (sumRight - houses[mid]*countRight) + } + } + + dp := make([][]int, k+1) + for i := range dp { + dp[i] = make([]int, n+1) + for j := range dp[i] { + dp[i][j] = 1 << 30 + } + } + dp[0][0] = 0 + + for m := 1; m <= k; m++ { + for j := 1; j <= n; j++ { + best := 1 << 30 + for i := 0; i < j; i++ { + if cand := dp[m-1][i] + G[i][j-1]; cand < best { + best = cand + } + } + dp[m][j] = best + } + } + + return dp[k][n] +} diff --git a/tests/1001-1500/1478. allocate-mailboxes/sol.java b/tests/1001-1500/1478. allocate-mailboxes/sol.java new file mode 100644 index 00000000..af017195 --- /dev/null +++ b/tests/1001-1500/1478. allocate-mailboxes/sol.java @@ -0,0 +1,40 @@ +class Solution { + public int minDistance(int[] houses, int k) { + int n = houses.length; + Arrays.sort(houses); + int[] P = new int[n + 1]; + for (int i = 0; i < n; i++) { + P[i + 1] = P[i] + houses[i]; + } + + int[][] G = new int[n][n]; + for (int i = 0; i < n; i++) { + for (int j = i; j < n; j++) { + int mid = (i + j) / 2; + int countLeft = mid - i + 1; + int countRight = j - mid; + int sumLeft = P[mid + 1] - P[i]; + int sumRight = P[j + 1] - P[mid + 1]; + G[i][j] = (houses[mid] * countLeft - sumLeft) + (sumRight - houses[mid] * countRight); + } + } + + int[][] dp = new int[k + 1][n + 1]; + for (int i = 0; i <= k; i++) { + Arrays.fill(dp[i], 1000000000); + } + dp[0][0] = 0; + + for (int m = 1; m <= k; m++) { + for (int j = 1; j <= n; j++) { + int best = Integer.MAX_VALUE; + for (int i = 0; i < j; i++) { + best = Math.min(best, dp[m-1][i] + G[i][j-1]); + } + dp[m][j] = best; + } + } + + return dp[k][n]; + } +} diff --git a/tests/1001-1500/1478. allocate-mailboxes/sol.kt b/tests/1001-1500/1478. allocate-mailboxes/sol.kt new file mode 100644 index 00000000..fd374dd9 --- /dev/null +++ b/tests/1001-1500/1478. allocate-mailboxes/sol.kt @@ -0,0 +1,37 @@ +class Solution { + fun minDistance(houses: IntArray, k: Int): Int { + val n = houses.size + houses.sort() + val P = IntArray(n + 1) + for (i in 0 until n) { + P[i + 1] = P[i] + houses[i] + } + + val G = Array(n) { IntArray(n) } + for (i in 0 until n) { + for (j in i until n) { + val mid = (i + j) / 2 + val countLeft = mid - i + 1 + val countRight = j - mid + val sumLeft = P[mid + 1] - P[i] + val sumRight = P[j + 1] - P[mid + 1] + G[i][j] = (houses[mid] * countLeft - sumLeft) + (sumRight - houses[mid] * countRight) + } + } + + val dp = Array(k + 1) { IntArray(n + 1) { Int.MAX_VALUE / 2 } } + dp[0][0] = 0 + + for (m in 1..k) { + for (j in 1..n) { + var best = Int.MAX_VALUE + for (i in 0 until j) { + best = minOf(best, dp[m-1][i] + G[i][j-1]) + } + dp[m][j] = best + } + } + + return dp[k][n] + } +} diff --git a/tests/1001-1500/1478. allocate-mailboxes/sol.py b/tests/1001-1500/1478. allocate-mailboxes/sol.py new file mode 100644 index 00000000..74b5d166 --- /dev/null +++ b/tests/1001-1500/1478. allocate-mailboxes/sol.py @@ -0,0 +1,66 @@ +from typing import List +import numpy as np + + +class Solution: + def minDistance(self, houses: List[int], k: int) -> int: + n = len(houses) + houses = np.sort(np.array(houses)) + + # 1. The Integrated Signal (Prefix Sums) + P = np.concatenate(([0], np.cumsum(houses))) + + # 2. Creating Coordinate Grids for i and j (0 <= i <= j < n) + # i_grid: rows represent starting house, j_grid: columns represent ending house + i_idx, j_idx = np.indices((n, n)) + + # 3. Vectorized Median Calculation + # Masking to only compute the Upper Triangle (where j >= i) + mask = j_idx >= i_idx + mid_idx = (i_idx + j_idx) // 2 + + # 4. The Horizontal Sum (L1 Cost) calculated via Broadcasting + # G[i,j] = (houses[mid] * (mid-i+1) - sum(houses[i..mid])) + + # (sum(houses[mid+1..j]) - houses[mid] * (j-mid)) + G = np.zeros((n, n)) + + # Extracting the components for the vectorized formula + count_left = mid_idx - i_idx + 1 + count_right = j_idx - mid_idx + + sum_left = P[mid_idx + 1] - P[i_idx] + sum_right = P[j_idx + 1] - P[mid_idx + 1] + + # The Vectorized L1 Manifold + G[mask] = (houses[mid_idx[mask]] * count_left[mask] - sum_left[mask]) + ( + sum_right[mask] - houses[mid_idx[mask]] * count_right[mask] + ) + + # 5. DP Phase: Optimal Partitioning + dp = np.full((k + 1, n + 1), float("inf")) + dp[0, 0] = 0 + + # --- Assuming G (N x N) and dp (K+1 x N+1) are already initialized --- + # G[i, j] is the cost for one mailbox to cover houses from index i to j. + # dp[m-1, :n] is the vector of minimum costs using m-1 mailboxes. + + for m in range(1, k + 1): + # 1. Linear Transformation: Broadcast dp[m-1] into the transition space + # We take the previous state vector and 'stretch' it to align with G + # Shape: (n, 1) + (n, n) -> (n, n) + # Each cell [i, j] represents: "Cost of m-1 mailboxes for i houses + 1 mailbox for houses i...j" + prev_states = dp[m - 1, :n][:, np.newaxis] + transition_matrix = prev_states + G + + # 2. Causality Masking (The Upper-Triangular Constraint) + # We cannot transition from more houses to fewer houses. + # We set the lower triangle to infinity so they are ignored in the min() + i_idx, j_idx = np.indices((n, n)) + transition_matrix[j_idx < i_idx] = float("inf") + + # 3. Horizontal Reduction (The Min-Plus Product) + # Taking the minimum along the 'previous house' axis (axis 0) + # This gives us the optimal cost for covering 'j+1' houses using 'm' mailboxes. + dp[m, 1:] = np.min(transition_matrix, axis=0) + + return int(dp[k, n]) diff --git a/tests/1001-1500/1478. allocate-mailboxes/sol.py2 b/tests/1001-1500/1478. allocate-mailboxes/sol.py2 new file mode 100644 index 00000000..0b92a833 --- /dev/null +++ b/tests/1001-1500/1478. allocate-mailboxes/sol.py2 @@ -0,0 +1,31 @@ +class Solution(object): + def minDistance(self, houses, k): + n = len(houses) + houses.sort() + P = [0] + for h in houses: + P.append(P[-1] + h) + + G = [[0] * n for _ in range(n)] + for i in range(n): + for j in range(i, n): + mid = (i + j) // 2 + count_left = mid - i + 1 + count_right = j - mid + sum_left = P[mid + 1] - P[i] + sum_right = P[j + 1] - P[mid + 1] + G[i][j] = (houses[mid] * count_left - sum_left) + (sum_right - houses[mid] * count_right) + + dp = [[float('inf')] * (n + 1) for _ in range(k + 1)] + dp[0][0] = 0 + + for m in range(1, k + 1): + for j in range(1, n + 1): + best = float('inf') + for i in range(j): + candidate = dp[m-1][i] + G[i][j-1] + if candidate < best: + best = candidate + dp[m][j] = best + + return int(dp[k][n]) diff --git a/tests/1001-1500/1478. allocate-mailboxes/sol.rb b/tests/1001-1500/1478. allocate-mailboxes/sol.rb new file mode 100644 index 00000000..19152555 --- /dev/null +++ b/tests/1001-1500/1478. allocate-mailboxes/sol.rb @@ -0,0 +1,37 @@ +# @param {Integer[]} houses +# @param {Integer} k +# @return {Integer} +def min_distance(houses, k) + n = houses.length + houses.sort! + pref = [0] + houses.each { |h| pref << pref[-1] + h } + + g = Array.new(n) { Array.new(n, 0) } + (0...n).each do |i| + (i...n).each do |j| + mid = (i + j) / 2 + count_left = mid - i + 1 + count_right = j - mid + sum_left = pref[mid + 1] - pref[i] + sum_right = pref[j + 1] - pref[mid + 1] + g[i][j] = (houses[mid] * count_left - sum_left) + (sum_right - houses[mid] * count_right) + end + end + + dp = Array.new(k + 1) { Array.new(n + 1, Float::INFINITY) } + dp[0][0] = 0 + + (1..k).each do |m| + (1..n).each do |j| + best = Float::INFINITY + (0...j).each do |i| + cand = dp[m-1][i] + g[i][j-1] + best = cand if cand < best + end + dp[m][j] = best + end + end + + dp[k][n].to_i +end diff --git a/tests/1001-1500/1478. allocate-mailboxes/sol.rs b/tests/1001-1500/1478. allocate-mailboxes/sol.rs new file mode 100644 index 00000000..25f7e25e --- /dev/null +++ b/tests/1001-1500/1478. allocate-mailboxes/sol.rs @@ -0,0 +1,40 @@ +impl Solution { + pub fn min_distance(houses: Vec, k: i32) -> i32 { + let mut houses = houses; + houses.sort(); + let n = houses.len(); + let k = k as usize; + + let mut P = vec![0; n + 1]; + for i in 0..n { + P[i + 1] = P[i] + houses[i]; + } + + let mut G = vec![vec![0; n]; n]; + for i in 0..n { + for j in i..n { + let mid = (i + j) / 2; + let count_left = (mid - i + 1) as i32; + let count_right = (j - mid) as i32; + let sum_left = P[mid + 1] - P[i]; + let sum_right = P[j + 1] - P[mid + 1]; + G[i][j] = (houses[mid] * count_left - sum_left) + (sum_right - houses[mid] * count_right); + } + } + + let mut dp = vec![vec![i32::MAX / 2; n + 1]; k + 1]; + dp[0][0] = 0; + + for m in 1..=k { + for j in 1..=n { + let mut best = i32::MAX; + for i in 0..j { + best = best.min(dp[m-1][i] + G[i][j-1]); + } + dp[m][j] = best; + } + } + + dp[k][n] + } +} diff --git a/tests/1001-1500/1478. allocate-mailboxes/sol.swift b/tests/1001-1500/1478. allocate-mailboxes/sol.swift new file mode 100644 index 00000000..22fde80f --- /dev/null +++ b/tests/1001-1500/1478. allocate-mailboxes/sol.swift @@ -0,0 +1,37 @@ +class Solution { + func minDistance(_ houses: [Int], _ k: Int) -> Int { + let n = houses.count + var houses = houses.sorted() + var P = [Int](repeating: 0, count: n + 1) + for i in 0.. a - b); + const P: number[] = new Array(n + 1).fill(0); + for (let i = 0; i < n; i++) { + P[i + 1] = P[i] + houses[i]; + } + + const G: number[][] = Array.from({ length: n }, () => new Array(n).fill(0)); + for (let i = 0; i < n; i++) { + for (let j = i; j < n; j++) { + const mid = Math.floor((i + j) / 2); + const countLeft = mid - i + 1; + const countRight = j - mid; + const sumLeft = P[mid + 1] - P[i]; + const sumRight = P[j + 1] - P[mid + 1]; + G[i][j] = + houses[mid] * countLeft - + sumLeft + + (sumRight - houses[mid] * countRight); + } + } + + const dp: number[][] = Array.from({ length: k + 1 }, () => + new Array(n + 1).fill(Infinity), + ); + dp[0][0] = 0; + + for (let m = 1; m <= k; m++) { + for (let j = 1; j <= n; j++) { + let best = Infinity; + for (let i = 0; i < j; i++) { + best = Math.min(best, dp[m - 1][i] + G[i][j - 1]); + } + dp[m][j] = best; + } + } + + return dp[k][n]; +} diff --git a/tests/1001-1500/1480. running-sum-of-1d-array/manifest.yaml b/tests/1001-1500/1480. running-sum-of-1d-array/manifest.yaml new file mode 100644 index 00000000..04991d32 --- /dev/null +++ b/tests/1001-1500/1480. running-sum-of-1d-array/manifest.yaml @@ -0,0 +1,304 @@ +entry: + id: 1480 + title: "running-sum-of-1d-array" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().runningSum({nums})" + rust: "Solution::running_sum({nums})" + python3: "Solution().runningSum({nums})" + python2: "Solution().runningSum({nums})" + ruby: "running_sum({nums})" + java: "new Solution().runningSum({nums})" + csharp: "new Solution().RunningSum({nums})" + kotlin: "Solution().runningSum({nums})" + go: "runningSum({nums})" + dart: "Solution().runningSum({nums})" + swift: "Solution().runningSum({nums})" + typescript: "runningSum({nums})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().runningSum(nums, {result})" + checker: | + class Checker: + def runningSum(self, nums, result): + total = 0 + expected = [] + for value in nums: + total += value + expected.append(total) + return result == expected + +seed: 1480 + +tests: + - name: "example-one" + in: + nums: [1, 2, 3, 4] + out: [1, 3, 6, 10] + - name: "example-two" + in: + nums: [1, 1, 1, 1, 1] + out: [1, 2, 3, 4, 5] + - name: "example-three" + in: + nums: [3, 1, 2, 10, 1] + out: [3, 4, 6, 16, 17] + - name: "single-positive" + in: + nums: [7] + - name: "single-negative" + in: + nums: [-7] + - name: "single-zero" + in: + nums: [0] + - name: "two-positive" + in: + nums: [5, 10] + - name: "two-negative" + in: + nums: [-5, -10] + - name: "cancellation" + in: + nums: [10, -10, 10, -10] + - name: "all-zero" + in: + nums: [0, 0, 0, 0, 0, 0] + - name: "alternating-one" + in: + nums: [1, -1, 1, -1, 1, -1] + - name: "alternating-large" + in: + nums: [1000000, -1000000, 1000000, -1000000] + - name: "strictly-increasing" + in: + nums: [1, 2, 3, 4, 5, 6, 7] + - name: "strictly-decreasing" + in: + nums: [7, 6, 5, 4, 3, 2, 1] + - name: "mixed-small" + in: + nums: [4, -2, 7, -5, 3] + - name: "mixed-medium" + in: + nums: [100, -50, 25, -75, 200, -10] + - name: "maximum-positive" + in: + nums: [1000000, 1000000, 1000000] + - name: "minimum-negative" + in: + nums: [-1000000, -1000000, -1000000] + - name: "positive-then-negative" + in: + nums: [20, 20, -10, -10, -10] + - name: "negative-then-positive" + in: + nums: [-20, -20, 10, 10, 10] + - name: "sawtooth" + in: + nums: [10, -1, -1, 10, -1, -1, 10] + - name: "powers-of-two" + in: + nums: [1, 2, 4, 8, 16, 32] + - name: "repeated-five" + in: + nums: [5, 5, 5, 5, 5, 5, 5, 5] + - name: "repeated-negative-five" + in: + nums: [-5, -5, -5, -5, -5, -5] + - name: "palindromic-values" + in: + nums: [1, 3, 5, 3, 1] + - name: "large-total" + in: + nums: [999999, 999999, -1, 999999] + - name: "large-negative-total" + in: + nums: [-999999, -999999, 1, -999999] + - name: "ten-ascending" + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + - name: "ten-descending" + in: + nums: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + - name: "ten-alternating" + in: + nums: [100, -99, 98, -97, 96, -95, 94, -93, 92, -91] + - name: "fifteen-mixed" + in: + nums: [3, -8, 12, 0, -4, 7, -11, 20, -2, 5, -6, 9, -10, 1, 4] + - name: "twenty-zeros-edges" + in: + nums: [100, 0, 0, 0, 0, 0, 0, 0, 0, 0, -100, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - name: "twenty-four-sequence" + 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, + ] + - name: "thirty-large-mixed" + in: + nums: + [ + 1000000, + -1, + -2, + -3, + -4, + -5, + 999999, + -6, + -7, + -8, + -9, + -10, + 500000, + -11, + -12, + -13, + -14, + -15, + -500000, + 16, + 17, + 18, + 19, + 20, + -1000000, + 21, + 22, + 23, + 24, + 25, + ] + - name: "thirty-one-balanced" + in: + nums: + [ + 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: "length-1000-maximum-positive" + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1000000 + max: 1000000 + distinct: false + sorted: false + elemType: "int" + - name: "length-1000-maximum-negative" + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: -1000000 + max: -1000000 + distinct: false + sorted: false + elemType: "int" + - name: "length-1000-zero-baseline" + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 0 + max: 0 + distinct: false + sorted: false + elemType: "int" + - name: "length-999-full-value-range" + in: + nums: + gen: "array" + len: 999 + of: + gen: "int" + min: -1000000 + max: 1000000 + distinct: false + sorted: false + elemType: "int" + - name: "length-1000-small-values" + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: -1 + max: 1 + distinct: false + sorted: false + elemType: "int" diff --git a/tests/1001-1500/1480. running-sum-of-1d-array/sol.cpp b/tests/1001-1500/1480. running-sum-of-1d-array/sol.cpp new file mode 100644 index 00000000..cb46e50d --- /dev/null +++ b/tests/1001-1500/1480. running-sum-of-1d-array/sol.cpp @@ -0,0 +1,9 @@ +class Solution { +public: + vector runningSum(vector& nums) { + for (int i = 1; i < nums.size(); i++) { + nums[i] += nums[i - 1]; + } + return nums; + } +}; diff --git a/tests/1001-1500/1480. running-sum-of-1d-array/sol.cs b/tests/1001-1500/1480. running-sum-of-1d-array/sol.cs new file mode 100644 index 00000000..09504c23 --- /dev/null +++ b/tests/1001-1500/1480. running-sum-of-1d-array/sol.cs @@ -0,0 +1,8 @@ +public class Solution { + public int[] RunningSum(int[] nums) { + for (int i = 1; i < nums.Length; i++) { + nums[i] += nums[i - 1]; + } + return nums; + } +} diff --git a/tests/1001-1500/1480. running-sum-of-1d-array/sol.dart b/tests/1001-1500/1480. running-sum-of-1d-array/sol.dart new file mode 100644 index 00000000..faaeefc5 --- /dev/null +++ b/tests/1001-1500/1480. running-sum-of-1d-array/sol.dart @@ -0,0 +1,8 @@ +class Solution { + List runningSum(List nums) { + for (int i = 1; i < nums.length; i++) { + nums[i] += nums[i - 1]; + } + return nums; + } +} diff --git a/tests/1001-1500/1480. running-sum-of-1d-array/sol.go b/tests/1001-1500/1480. running-sum-of-1d-array/sol.go new file mode 100644 index 00000000..ba0a2cfe --- /dev/null +++ b/tests/1001-1500/1480. running-sum-of-1d-array/sol.go @@ -0,0 +1,6 @@ +func runningSum(nums []int) []int { + for i := 1; i < len(nums); i++ { + nums[i] += nums[i-1] + } + return nums +} diff --git a/tests/1001-1500/1480. running-sum-of-1d-array/sol.java b/tests/1001-1500/1480. running-sum-of-1d-array/sol.java new file mode 100644 index 00000000..5821eb86 --- /dev/null +++ b/tests/1001-1500/1480. running-sum-of-1d-array/sol.java @@ -0,0 +1,8 @@ +class Solution { + public int[] runningSum(int[] nums) { + for (int i = 1; i < nums.length; i++) { + nums[i] += nums[i - 1]; + } + return nums; + } +} diff --git a/tests/1001-1500/1480. running-sum-of-1d-array/sol.kt b/tests/1001-1500/1480. running-sum-of-1d-array/sol.kt new file mode 100644 index 00000000..da92d33e --- /dev/null +++ b/tests/1001-1500/1480. running-sum-of-1d-array/sol.kt @@ -0,0 +1,8 @@ +class Solution { + fun runningSum(nums: IntArray): IntArray { + for (i in 1 until nums.size) { + nums[i] += nums[i - 1] + } + return nums + } +} diff --git a/tests/1001-1500/1480. running-sum-of-1d-array/sol.py b/tests/1001-1500/1480. running-sum-of-1d-array/sol.py new file mode 100644 index 00000000..70582262 --- /dev/null +++ b/tests/1001-1500/1480. running-sum-of-1d-array/sol.py @@ -0,0 +1,7 @@ +class Solution: + def runningSum(self, nums): + + for i in range(1, len(nums)): + nums[i] += nums[i - 1] + + return nums diff --git a/tests/1001-1500/1480. running-sum-of-1d-array/sol.py2 b/tests/1001-1500/1480. running-sum-of-1d-array/sol.py2 new file mode 100644 index 00000000..a71a410f --- /dev/null +++ b/tests/1001-1500/1480. running-sum-of-1d-array/sol.py2 @@ -0,0 +1,9 @@ +class Solution(object): + def runningSum(self, nums): + """ + :type nums: List[int] + :rtype: List[int] + """ + for i in range(1, len(nums)): + nums[i] += nums[i - 1] + return nums diff --git a/tests/1001-1500/1480. running-sum-of-1d-array/sol.rb b/tests/1001-1500/1480. running-sum-of-1d-array/sol.rb new file mode 100644 index 00000000..c673de7d --- /dev/null +++ b/tests/1001-1500/1480. running-sum-of-1d-array/sol.rb @@ -0,0 +1,8 @@ +# @param {Integer[]} nums +# @return {Integer[]} +def running_sum(nums) + (1...nums.length).each do |i| + nums[i] += nums[i - 1] + end + nums +end diff --git a/tests/1001-1500/1480. running-sum-of-1d-array/sol.rs b/tests/1001-1500/1480. running-sum-of-1d-array/sol.rs new file mode 100644 index 00000000..957ce789 --- /dev/null +++ b/tests/1001-1500/1480. running-sum-of-1d-array/sol.rs @@ -0,0 +1,9 @@ +impl Solution { + pub fn running_sum(nums: Vec) -> Vec { + let mut nums = nums; + for i in 1..nums.len() { + nums[i] += nums[i - 1]; + } + nums + } +} diff --git a/tests/1001-1500/1480. running-sum-of-1d-array/sol.swift b/tests/1001-1500/1480. running-sum-of-1d-array/sol.swift new file mode 100644 index 00000000..2cf457fb --- /dev/null +++ b/tests/1001-1500/1480. running-sum-of-1d-array/sol.swift @@ -0,0 +1,9 @@ +class Solution { + func runningSum(_ nums: [Int]) -> [Int] { + var nums = nums + for i in 1..& arr, int k) { + std::unordered_map counts; + for (int num : arr) { + counts[num]++; + } + int remaining = counts.size(); + std::vector frequencies; + for (const auto& pair : counts) { + frequencies.push_back(pair.second); + } + std::sort(frequencies.begin(), frequencies.end()); + for (int count : frequencies) { + if (k < count) { + break; + } + k -= count; + remaining--; + } + return remaining; + } +}; diff --git a/tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.cs b/tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.cs new file mode 100644 index 00000000..1089e87e --- /dev/null +++ b/tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.cs @@ -0,0 +1,23 @@ +public class Solution { + public int FindLeastNumOfUniqueInts(int[] arr, int k) { + var counts = new Dictionary(); + foreach (int num in arr) { + if (counts.ContainsKey(num)) { + counts[num]++; + } else { + counts[num] = 1; + } + } + int remaining = counts.Count; + var frequencies = new List(counts.Values); + frequencies.Sort(); + foreach (int count in frequencies) { + if (k < count) { + break; + } + k -= count; + remaining--; + } + return remaining; + } +} diff --git a/tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.dart b/tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.dart new file mode 100644 index 00000000..9ab062c9 --- /dev/null +++ b/tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.dart @@ -0,0 +1,19 @@ +class Solution { + int findLeastNumOfUniqueInts(List arr, int k) { + Map counts = {}; + for (int n in arr) { + counts[n] = (counts[n] ?? 0) + 1; + } + + List frequencies = counts.values.toList()..sort(); + int remaining = frequencies.length; + + for (int freq in frequencies) { + if (k < freq) break; + k -= freq; + remaining--; + } + + return remaining; + } +} diff --git a/tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.go b/tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.go new file mode 100644 index 00000000..528651fc --- /dev/null +++ b/tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.go @@ -0,0 +1,20 @@ +func findLeastNumOfUniqueInts(arr []int, k int) int { + counts := make(map[int]int) + for _, num := range arr { + counts[num]++ + } + remaining := len(counts) + var freqs []int + for _, freq := range counts { + freqs = append(freqs, freq) + } + sort.Ints(freqs) + for _, count := range freqs { + if k < count { + break + } + k -= count + remaining-- + } + return remaining +} diff --git a/tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.java b/tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.java new file mode 100644 index 00000000..88b005ae --- /dev/null +++ b/tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.java @@ -0,0 +1,19 @@ +class Solution { + public int findLeastNumOfUniqueInts(int[] arr, int k) { + java.util.Map counts = new java.util.HashMap<>(); + for (int num : arr) { + counts.put(num, counts.getOrDefault(num, 0) + 1); + } + int remaining = counts.size(); + java.util.List frequencies = new java.util.ArrayList<>(counts.values()); + java.util.Collections.sort(frequencies); + for (int count : frequencies) { + if (k < count) { + break; + } + k -= count; + remaining--; + } + return remaining; + } +} diff --git a/tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.kt b/tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.kt new file mode 100644 index 00000000..dcd9e170 --- /dev/null +++ b/tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.kt @@ -0,0 +1,14 @@ +class Solution { + fun findLeastNumOfUniqueInts(arr: IntArray, k: Int): Int { + val counts = arr.toList().groupingBy { it }.eachCount() + var remaining = counts.size + var tempK = k + val sortedFreqs = counts.values.sorted() + for (count in sortedFreqs) { + if (tempK < count) break + tempK -= count + remaining-- + } + return remaining + } +} diff --git a/tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.py b/tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.py new file mode 100644 index 00000000..b2042415 --- /dev/null +++ b/tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.py @@ -0,0 +1,12 @@ +class Solution: + def findLeastNumOfUniqueInts(self, arr, k): + from collections import Counter + + counts = Counter(arr) + remaining = len(counts) + for count in sorted(counts.values()): + if k < count: + break + k -= count + remaining -= 1 + return remaining diff --git a/tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.py2 b/tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.py2 new file mode 100644 index 00000000..e8c89e44 --- /dev/null +++ b/tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.py2 @@ -0,0 +1,22 @@ +class Solution(object): + + def findLeastNumOfUniqueInts(self, arr, k): + + """ + + :type arr: List[int] + + :type k: int + + :rtype: int + + """ + from collections import Counter + counts = Counter(arr) + remaining = len(counts) + for count in sorted(counts.values()): + if k < count: + break + k -= count + remaining -= 1 + return remaining diff --git a/tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.rb b/tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.rb new file mode 100644 index 00000000..ec093a4e --- /dev/null +++ b/tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.rb @@ -0,0 +1,13 @@ +# @param {Integer[]} arr +# @param {Integer} k +# @return {Integer} +def find_least_num_of_unique_ints(arr, k) + counts = arr.tally + remaining = counts.size + counts.values.sort.each do |count| + break if k < count + k -= count + remaining -= 1 + end + remaining +end diff --git a/tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.rs b/tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.rs new file mode 100644 index 00000000..a436c11f --- /dev/null +++ b/tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.rs @@ -0,0 +1,21 @@ +impl Solution { + pub fn find_least_num_of_unique_ints(arr: Vec, k: i32) -> i32 { + use std::collections::HashMap; + let mut counts: HashMap = HashMap::new(); + for num in arr { + *counts.entry(num).or_insert(0) += 1; + } + let mut remaining = counts.len() as i32; + let mut freqs: Vec = counts.values().cloned().collect(); + freqs.sort(); + let mut k = k; + for count in freqs { + if k < count { + break; + } + k -= count; + remaining -= 1; + } + remaining + } +} diff --git a/tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.swift b/tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.swift new file mode 100644 index 00000000..366fa29b --- /dev/null +++ b/tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.swift @@ -0,0 +1,19 @@ +class Solution { + func findLeastNumOfUniqueInts(_ arr: [Int], _ k: Int) -> Int { + var counts: [Int: Int] = [:] + for num in arr { + counts[num, default: 0] += 1 + } + var remaining = counts.count + var tempK = k + let frequencies = counts.values.sorted() + for count in frequencies { + if tempK < count { + break + } + tempK -= count + remaining -= 1 + } + return remaining + } +} diff --git a/tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.ts b/tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.ts new file mode 100644 index 00000000..0fe87399 --- /dev/null +++ b/tests/1001-1500/1481. least-number-of-unique-integers-after-k-removals/sol.ts @@ -0,0 +1,16 @@ +function findLeastNumOfUniqueInts(arr: number[], k: number): number { + const counts: Map = new Map(); + for (const num of arr) { + counts.set(num, (counts.get(num) || 0) + 1); + } + let remaining = counts.size; + const frequencies = Array.from(counts.values()).sort((a, b) => a - b); + for (const count of frequencies) { + if (k < count) { + break; + } + k -= count; + remaining--; + } + return remaining; +} diff --git a/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/manifest.yaml b/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/manifest.yaml new file mode 100644 index 00000000..4264f5e3 --- /dev/null +++ b/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/manifest.yaml @@ -0,0 +1,282 @@ +entry: + id: 1482 + title: "minimum-number-of-days-to-make-m-bouquets" + params: + bloomDay: + type: array + items: + type: int + m: + type: int + k: + type: int + call: + cpp: "Solution().minDays({bloomDay}, {m}, {k})" + rust: "Solution::min_days({bloomDay}, {m}, {k})" + python3: "Solution().minDays({bloomDay}, {m}, {k})" + python2: "Solution().minDays({bloomDay}, {m}, {k})" + ruby: "min_days({bloomDay}, {m}, {k})" + java: "new Solution().minDays({bloomDay}, {m}, {k})" + csharp: "new Solution().MinDays({bloomDay}, {m}, {k})" + kotlin: "Solution().minDays({bloomDay}, {m}, {k})" + go: "minDays({bloomDay}, {m}, {k})" + dart: "Solution().minDays({bloomDay}, {m}, {k})" + swift: "Solution().minDays({bloomDay}, {m}, {k})" + typescript: "minDays({bloomDay}, {m}, {k})" +judge: + type: "exact" +limits: + time_ms: 900 + memory_mb: 256 +oracle: + python3: + call: "Checker().minDays(bloomDay, m, k, {result})" + checker: | + class Checker: + def minDays(self, bloomDay, m, k, result): + if m * k > len(bloomDay): + return result == -1 + low = min(bloomDay) + high = max(bloomDay) + while low < high: + day = (low + high) // 2 + bouquets = 0 + run = 0 + for bloom in bloomDay: + if bloom <= day: + run += 1 + if run == k: + bouquets += 1 + run = 0 + else: + run = 0 + if bouquets >= m: + high = day + else: + low = day + 1 + return result == low +seed: 1482 +tests: + - name: "official-one" + in: + bloomDay: [1, 10, 3, 10, 2] + m: 3 + k: 1 + out: 3 + - name: "official-two-impossible" + in: + bloomDay: [1, 10, 3, 10, 2] + m: 3 + k: 2 + out: -1 + - name: "official-three" + in: + bloomDay: [7, 7, 7, 7, 12, 7, 7] + m: 2 + k: 3 + out: 12 + - name: "single-flower" + in: + bloomDay: [5] + m: 1 + k: 1 + - name: "single-impossible" + in: + bloomDay: [5] + m: 2 + k: 1 + - name: "all-same-one" + in: + bloomDay: [4, 4, 4, 4] + m: 1 + k: 4 + - name: "all-same-many" + in: + bloomDay: [4, 4, 4, 4, 4, 4] + m: 3 + k: 2 + - name: "all-same-too-many" + in: + bloomDay: [4, 4, 4] + m: 2 + k: 2 + - name: "k-one" + in: + bloomDay: [9, 2, 6, 1, 8] + m: 4 + k: 1 + - name: "k-one-all" + in: + bloomDay: [9, 2, 6, 1, 8] + m: 5 + k: 1 + - name: "adjacent-ready" + in: + bloomDay: [1, 2, 3, 4, 5, 6] + m: 2 + k: 3 + - name: "adjacent-blocked" + in: + bloomDay: [1, 9, 1, 9, 1, 9] + m: 2 + k: 2 + - name: "two-runs" + in: + bloomDay: [2, 2, 9, 9, 2, 2] + m: 2 + k: 2 + - name: "three-runs" + in: + bloomDay: [3, 3, 3, 8, 3, 3, 3] + m: 2 + k: 3 + - name: "late-bridge" + in: + bloomDay: [1, 1, 10, 1, 1] + m: 1 + k: 5 + - name: "late-bridge-impossible" + in: + bloomDay: [1, 1, 10, 1, 1] + m: 2 + k: 2 + - name: "alternating-days" + in: + bloomDay: [10, 1, 10, 1, 10, 1] + m: 2 + k: 2 + - name: "smallest-day-answer" + in: + bloomDay: [1, 1, 1, 2, 2, 2] + m: 2 + k: 3 + - name: "largest-day-answer" + in: + bloomDay: [1, 2, 1, 2, 1, 2] + m: 2 + k: 3 + - name: "large-days" + in: + bloomDay: [1000000000, 999999999, 500000000, 1000000000] + m: 2 + k: 2 + - name: "near-billion" + in: + bloomDay: [999999998, 999999999, 1000000000] + m: 1 + k: 3 + - name: "capacity-exact" + in: + bloomDay: [6, 5, 4, 3, 2, 1] + m: 2 + k: 3 + - name: "capacity-short" + in: + bloomDay: [6, 5, 4, 3, 2] + m: 2 + k: 3 + - name: "one-long-bouquet" + in: + bloomDay: [2, 1, 3, 4, 5] + m: 1 + k: 5 + - name: "separated-singletons" + in: + bloomDay: [1, 9, 1, 9, 1] + m: 3 + k: 1 + - name: "separated-pairs" + in: + bloomDay: [1, 1, 9, 1, 1, 9] + m: 2 + k: 2 + - name: "three-bouquets-of-two" + in: + bloomDay: [2, 2, 4, 4, 6, 6] + m: 3 + k: 2 + - name: "competing-runs" + in: + bloomDay: [5, 1, 5, 1, 5, 1, 5] + m: 2 + k: 2 + - name: "all-early" + in: + bloomDay: [1, 1, 1, 1, 1, 10] + m: 2 + k: 3 + - name: "all-late" + in: + bloomDay: [10, 1, 1, 1, 1, 1] + m: 2 + k: 3 + - name: "mixed-five" + in: + bloomDay: [4, 8, 2, 6, 3, 7, 1, 5] + m: 2 + k: 2 + - name: "mixed-three" + in: + bloomDay: [8, 3, 7, 2, 6, 1, 5, 4] + m: 2 + k: 3 + - name: "minimum-values" + in: + bloomDay: [1, 1, 1, 1] + m: 4 + k: 1 + - name: "maximum-multiplicity" + in: + bloomDay: [1, 2, 3, 4, 5, 6, 7, 8] + m: 4 + k: 2 + - name: "alternating-three" + in: + bloomDay: [1, 4, 1, 4, 1, 4, 1, 4, 1] + m: 2 + k: 3 + - name: "late-single-flower" + in: + bloomDay: [1, 1, 1, 100] + m: 1 + k: 4 + - name: "all-flowers-single-bouquets-at-limit" + in: + bloomDay: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + sorted: false + elemType: "int" + m: 100000 + k: 1 + - name: "exact-capacity-at-limit" + in: + bloomDay: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + sorted: false + elemType: "int" + m: 33333 + k: 3 + - name: "minimum-day-single-bouquet" + in: + bloomDay: [1, 2, 1, 2, 1] + m: 1 + k: 3 + out: 2 + - name: "late-boundary-pair" + in: + bloomDay: [1, 1000000000, 1, 1] + m: 1 + k: 2 + out: 1 diff --git a/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.cpp b/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.cpp new file mode 100644 index 00000000..9d4d285e --- /dev/null +++ b/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + int minDays(vector& bloomDay, int m, int k) { + if ((long long)m * k > bloomDay.size()) return -1; + + auto f = [&](int timeLimit) -> bool { + int cntr = 0; + int bouquetCntr = 0; + for (int day : bloomDay) { + if (day <= timeLimit) { + cntr++; + if (cntr == k) { + bouquetCntr++; + cntr = 0; + } + } else { + cntr = 0; + } + } + return bouquetCntr >= m; + }; + + int s = *min_element(bloomDay.begin(), bloomDay.end()); + int e = *max_element(bloomDay.begin(), bloomDay.end()); + int ans = -1; + + while (s <= e) { + int mid = s + (e - s) / 2; + if (f(mid)) { + ans = mid; + e = mid - 1; + } else { + s = mid + 1; + } + } + + return ans; + } +}; diff --git a/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.cs b/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.cs new file mode 100644 index 00000000..5957125e --- /dev/null +++ b/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.cs @@ -0,0 +1,38 @@ +public class Solution { + public int MinDays(int[] bloomDay, int m, int k) { + if ((long)m * k > bloomDay.Length) return -1; + + bool f(int timeLimit) { + int cntr = 0; + int bouquetCntr = 0; + foreach (int day in bloomDay) { + if (day <= timeLimit) { + cntr++; + if (cntr == k) { + bouquetCntr++; + cntr = 0; + } + } else { + cntr = 0; + } + } + return bouquetCntr >= m; + } + + int s = bloomDay.Min(); + int e = bloomDay.Max(); + int ans = -1; + + while (s <= e) { + int mid = s + (e - s) / 2; + if (f(mid)) { + ans = mid; + e = mid - 1; + } else { + s = mid + 1; + } + } + + return ans; + } +} diff --git a/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.dart b/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.dart new file mode 100644 index 00000000..19e9e8f4 --- /dev/null +++ b/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.dart @@ -0,0 +1,38 @@ +class Solution { + int minDays(List bloomDay, int m, int k) { + if (m * k > bloomDay.length) return -1; + + bool f(int timeLimit) { + int cntr = 0; + int bouquetCntr = 0; + for (int day in bloomDay) { + if (day <= timeLimit) { + cntr++; + if (cntr == k) { + bouquetCntr++; + cntr = 0; + } + } else { + cntr = 0; + } + } + return bouquetCntr >= m; + } + + int s = bloomDay.reduce((a, b) => a < b ? a : b); + int e = bloomDay.reduce((a, b) => a > b ? a : b); + int ans = -1; + + while (s <= e) { + int mid = s + (e - s) ~/ 2; + if (f(mid)) { + ans = mid; + e = mid - 1; + } else { + s = mid + 1; + } + } + + return ans; + } +} diff --git a/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.go b/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.go new file mode 100644 index 00000000..372153b8 --- /dev/null +++ b/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.go @@ -0,0 +1,46 @@ +func minDays(bloomDay []int, m int, k int) int { + if m*k > len(bloomDay) { + return -1 + } + + f := func(timeLimit int) bool { + cntr := 0 + bouquetCntr := 0 + for _, day := range bloomDay { + if day <= timeLimit { + cntr++ + if cntr == k { + bouquetCntr++ + cntr = 0 + } + } else { + cntr = 0 + } + } + return bouquetCntr >= m + } + + s := bloomDay[0] + e := bloomDay[0] + for _, day := range bloomDay { + if day < s { + s = day + } + if day > e { + e = day + } + } + + ans := -1 + for s <= e { + mid := s + (e-s)/2 + if f(mid) { + ans = mid + e = mid - 1 + } else { + s = mid + 1 + } + } + + return ans +} diff --git a/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.java b/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.java new file mode 100644 index 00000000..669405da --- /dev/null +++ b/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.java @@ -0,0 +1,41 @@ +class Solution { + public int minDays(int[] bloomDay, int m, int k) { + if ((long) m * k > bloomDay.length) return -1; + + int s = Integer.MAX_VALUE; + int e = Integer.MIN_VALUE; + for (int day : bloomDay) { + s = Math.min(s, day); + e = Math.max(e, day); + } + + int ans = -1; + while (s <= e) { + int mid = s + (e - s) / 2; + if (f(bloomDay, m, k, mid)) { + ans = mid; + e = mid - 1; + } else { + s = mid + 1; + } + } + return ans; + } + + private boolean f(int[] bloomDay, int m, int k, int timeLimit) { + int cntr = 0; + int bouquetCntr = 0; + for (int day : bloomDay) { + if (day <= timeLimit) { + cntr++; + if (cntr == k) { + bouquetCntr++; + cntr = 0; + } + } else { + cntr = 0; + } + } + return bouquetCntr >= m; + } +} diff --git a/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.kt b/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.kt new file mode 100644 index 00000000..d3d1e85d --- /dev/null +++ b/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.kt @@ -0,0 +1,38 @@ +class Solution { + fun minDays(bloomDay: IntArray, m: Int, k: Int): Int { + if (m.toLong() * k > bloomDay.size) return -1 + + fun f(timeLimit: Int): Boolean { + var cntr = 0 + var bouquetCntr = 0 + for (day in bloomDay) { + if (day <= timeLimit) { + cntr++ + if (cntr == k) { + bouquetCntr++ + cntr = 0 + } + } else { + cntr = 0 + } + } + return bouquetCntr >= m + } + + var s = bloomDay.min() + var e = bloomDay.max() + var ans = -1 + + while (s <= e) { + val mid = s + (e - s) / 2 + if (f(mid)) { + ans = mid + e = mid - 1 + } else { + s = mid + 1 + } + } + + return ans + } +} diff --git a/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.py b/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.py new file mode 100644 index 00000000..ca5574e0 --- /dev/null +++ b/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.py @@ -0,0 +1,34 @@ +class Solution: + def f(self, bloomDay, m, k, timeLimit): + cntr = 0 + bouquetCntr = 0 + + for day in bloomDay: + if day <= timeLimit: + cntr += 1 + if cntr == k: + bouquetCntr += 1 + cntr = 0 + else: + cntr = 0 + + return bouquetCntr >= m + + def minDays(self, bloomDay, m, k): + if m * k > len(bloomDay): + return -1 + + s = min(bloomDay) + e = max(bloomDay) + ans = -1 + + while s <= e: + mid = s + (e - s) // 2 + + if self.f(bloomDay, m, k, mid): + ans = mid + e = mid - 1 + else: + s = mid + 1 + + return ans diff --git a/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.py2 b/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.py2 new file mode 100644 index 00000000..fefb7f15 --- /dev/null +++ b/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.py2 @@ -0,0 +1,37 @@ +class Solution(object): + def minDays(self, bloomDay, m, k): + """ + :type bloomDay: List[int] + :type m: int + :type k: int + :rtype: int + """ + if m * k > len(bloomDay): + return -1 + + def f(timeLimit): + cntr = 0 + bouquetCntr = 0 + for day in bloomDay: + if day <= timeLimit: + cntr += 1 + if cntr == k: + bouquetCntr += 1 + cntr = 0 + else: + cntr = 0 + return bouquetCntr >= m + + s = min(bloomDay) + e = max(bloomDay) + ans = -1 + + while s <= e: + mid = s + (e - s) // 2 + if f(mid): + ans = mid + e = mid - 1 + else: + s = mid + 1 + + return ans diff --git a/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.rb b/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.rb new file mode 100644 index 00000000..b159905d --- /dev/null +++ b/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.rb @@ -0,0 +1,40 @@ +# @param {Integer[]} bloom_day +# @param {Integer} m +# @param {Integer} k +# @return {Integer} +def min_days(bloom_day, m, k) + return -1 if m * k > bloom_day.length + + f = ->(time_limit) { + cntr = 0 + bouquet_cntr = 0 + bloom_day.each do |day| + if day <= time_limit + cntr += 1 + if cntr == k + bouquet_cntr += 1 + cntr = 0 + end + else + cntr = 0 + end + end + bouquet_cntr >= m + } + + s = bloom_day.min + e = bloom_day.max + ans = -1 + + while s <= e + mid = s + (e - s) / 2 + if f.call(mid) + ans = mid + e = mid - 1 + else + s = mid + 1 + end + end + + ans +end diff --git a/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.rs b/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.rs new file mode 100644 index 00000000..e25e3a68 --- /dev/null +++ b/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.rs @@ -0,0 +1,42 @@ +impl Solution { + pub fn min_days(bloom_day: Vec, m: i32, k: i32) -> i32 { + if (m as i64) * (k as i64) > bloom_day.len() as i64 { + return -1; + } + + let f = |time_limit: i32| -> bool { + let mut cntr = 0; + let mut bouquet_cntr = 0; + for &day in &bloom_day { + if day <= time_limit { + cntr += 1; + if cntr == k { + bouquet_cntr += 1; + cntr = 0; + } + } else { + cntr = 0; + } + } + bouquet_cntr >= m + }; + + let s = *bloom_day.iter().min().unwrap(); + let e = *bloom_day.iter().max().unwrap(); + let mut s = s; + let mut e = e; + let mut ans = -1; + + while s <= e { + let mid = s + (e - s) / 2; + if f(mid) { + ans = mid; + e = mid - 1; + } else { + s = mid + 1; + } + } + + ans + } +} diff --git a/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.swift b/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.swift new file mode 100644 index 00000000..7872ce84 --- /dev/null +++ b/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.swift @@ -0,0 +1,38 @@ +class Solution { + func minDays(_ bloomDay: [Int], _ m: Int, _ k: Int) -> Int { + if m * k > bloomDay.count { return -1 } + + func f(_ timeLimit: Int) -> Bool { + var cntr = 0 + var bouquetCntr = 0 + for day in bloomDay { + if day <= timeLimit { + cntr += 1 + if cntr == k { + bouquetCntr += 1 + cntr = 0 + } + } else { + cntr = 0 + } + } + return bouquetCntr >= m + } + + var s = bloomDay.min()! + var e = bloomDay.max()! + var ans = -1 + + while s <= e { + let mid = s + (e - s) / 2 + if f(mid) { + ans = mid + e = mid - 1 + } else { + s = mid + 1 + } + } + + return ans + } +} diff --git a/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.ts b/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.ts new file mode 100644 index 00000000..8d3eed94 --- /dev/null +++ b/tests/1001-1500/1482. minimum-number-of-days-to-make-m-bouquets/sol.ts @@ -0,0 +1,36 @@ +function minDays(bloomDay: number[], m: number, k: number): number { + if (m * k > bloomDay.length) return -1; + + const f = (timeLimit: number): boolean => { + let cntr = 0; + let bouquetCntr = 0; + for (const day of bloomDay) { + if (day <= timeLimit) { + cntr++; + if (cntr === k) { + bouquetCntr++; + cntr = 0; + } + } else { + cntr = 0; + } + } + return bouquetCntr >= m; + }; + + let s = Math.min(...bloomDay); + let e = Math.max(...bloomDay); + let ans = -1; + + while (s <= e) { + const mid = s + Math.floor((e - s) / 2); + if (f(mid)) { + ans = mid; + e = mid - 1; + } else { + s = mid + 1; + } + } + + return ans; +} diff --git a/tests/1001-1500/1486. xor-operation-in-an-array/manifest.yaml b/tests/1001-1500/1486. xor-operation-in-an-array/manifest.yaml new file mode 100644 index 00000000..8a95ab9e --- /dev/null +++ b/tests/1001-1500/1486. xor-operation-in-an-array/manifest.yaml @@ -0,0 +1,231 @@ +entry: + id: 1486 + title: xor-operation-in-an-array + params: + n: + type: int + start_value: + type: int + call: + cpp: "Solution().xorOperation({n}, {start_value})" + rust: "Solution::xor_operation({n}, {start_value})" + python3: "Solution().xorOperation({n}, {start_value})" + python2: "Solution().xorOperation({n}, {start_value})" + ruby: "xor_operation({n}, {start_value})" + java: "new Solution().xorOperation({n}, {start_value})" + csharp: "new Solution().XorOperation({n}, {start_value})" + kotlin: "Solution().xorOperation({n}, {start_value})" + go: "xorOperation({n}, {start_value})" + dart: "Solution().xorOperation({n}, {start_value})" + swift: "Solution().xorOperation({n}, {start_value})" + typescript: "xorOperation({n}, {start_value})" +judge: + type: exact +limits: + time_ms: 2000 + memory_mb: 128 +oracle: + python3: + call: "Checker().xorOperation(n, start_value, {result})" + checker: | + class Checker: + def xorOperation(self, n, start_value, result): + if type(result) is not int or not (1 <= n <= 1000) or not (0 <= start_value <= 1000): + return False + expected = 0 + for index in range(n): + expected ^= start_value + 2 * index + return result == expected +seed: 1486 +tests: + - name: prompt-example-one + in: + n: 5 + start_value: 0 + - name: prompt-example-two + in: + n: 4 + start_value: 3 + - name: minimum-zero + in: + n: 1 + start_value: 0 + - name: minimum-one + in: + n: 1 + start_value: 1 + - name: minimum-maximum-start + in: + n: 1 + start_value: 1000 + - name: two-zero-start + in: + n: 2 + start_value: 0 + - name: two-one-start + in: + n: 2 + start_value: 1 + - name: two-even-start + in: + n: 2 + start_value: 10 + - name: three-zero-start + in: + n: 3 + start_value: 0 + - name: three-odd-start + in: + n: 3 + start_value: 7 + - name: four-zero-start + in: + n: 4 + start_value: 0 + - name: four-even-start + in: + n: 4 + start_value: 8 + - name: four-odd-start + in: + n: 4 + start_value: 9 + - name: five-small-start + in: + n: 5 + start_value: 2 + - name: six-small-start + in: + n: 6 + start_value: 4 + - name: seven-bit-boundary + in: + n: 7 + start_value: 16 + - name: eight-bit-boundary + in: + n: 8 + start_value: 31 + - name: nine-mixed-bits + in: + n: 9 + start_value: 12 + - name: large-generated-a + seed: 148601 + in: + n: + gen: "int" + min: 800 + max: 1000 + start_value: + gen: "int" + min: 0 + max: 1000 + - name: sixteen-high-start + in: + n: 16 + start_value: 1000 + - name: seventeen-odd-start + in: + n: 17 + start_value: 127 + - name: twenty-small-start + in: + n: 20 + start_value: 6 + - name: twenty-one-high-start + in: + n: 21 + start_value: 999 + - name: thirty-two-zero-start + in: + n: 32 + start_value: 0 + - name: thirty-two-boundary-start + in: + n: 32 + start_value: 256 + - name: thirty-three-start + in: + n: 33 + start_value: 511 + - name: fifty-mixed + in: + n: 50 + start_value: 37 + - name: sixty-four-zero + in: + n: 64 + start_value: 0 + - name: sixty-five-high + in: + n: 65 + start_value: 900 + - name: one-hundred-mid + in: + n: 100 + start_value: 123 + - name: one-hundred-one-zero + in: + n: 101 + start_value: 0 + - name: five-hundred-mid + in: + n: 500 + start_value: 321 + - name: maximum-n-zero + in: + n: 1000 + start_value: 0 + - name: maximum-n-maximum-start + in: + n: 1000 + start_value: 1000 + - name: near-maximum-n-maximum-start + in: + n: 999 + start_value: 1000 + - name: large-generated-b + seed: 148602 + in: + n: + gen: "int" + min: 800 + max: 1000 + start_value: + gen: "int" + min: 0 + max: 1000 + - name: large-generated-c + seed: 148603 + in: + n: + gen: "int" + min: 800 + max: 1000 + start_value: + gen: "int" + min: 0 + max: 1000 + - name: large-generated-d + seed: 148604 + in: + n: + gen: "int" + min: 800 + max: 1000 + start_value: + gen: "int" + min: 0 + max: 1000 + - name: large-generated-e + seed: 148605 + in: + n: + gen: "int" + min: 800 + max: 1000 + start_value: + gen: "int" + min: 0 + max: 1000 diff --git a/tests/1001-1500/1486. xor-operation-in-an-array/sol.cpp b/tests/1001-1500/1486. xor-operation-in-an-array/sol.cpp new file mode 100644 index 00000000..93599d6e --- /dev/null +++ b/tests/1001-1500/1486. xor-operation-in-an-array/sol.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int xorOperation(int n, int start) { + int ans = 0; + while (n > 0) { + ans ^= start; + start += 2; + n--; + } + return ans; + } +}; diff --git a/tests/1001-1500/1486. xor-operation-in-an-array/sol.cs b/tests/1001-1500/1486. xor-operation-in-an-array/sol.cs new file mode 100644 index 00000000..ecf88803 --- /dev/null +++ b/tests/1001-1500/1486. xor-operation-in-an-array/sol.cs @@ -0,0 +1,11 @@ +public class Solution { + public int XorOperation(int n, int start) { + int ans = 0; + while (n > 0) { + ans ^= start; + start += 2; + n--; + } + return ans; + } +} diff --git a/tests/1001-1500/1486. xor-operation-in-an-array/sol.dart b/tests/1001-1500/1486. xor-operation-in-an-array/sol.dart new file mode 100644 index 00000000..e2fc0879 --- /dev/null +++ b/tests/1001-1500/1486. xor-operation-in-an-array/sol.dart @@ -0,0 +1,11 @@ +class Solution { + int xorOperation(int n, int start) { + int ans = 0; + while (n > 0) { + ans ^= start; + start += 2; + n--; + } + return ans; + } +} diff --git a/tests/1001-1500/1486. xor-operation-in-an-array/sol.go b/tests/1001-1500/1486. xor-operation-in-an-array/sol.go new file mode 100644 index 00000000..3e096fef --- /dev/null +++ b/tests/1001-1500/1486. xor-operation-in-an-array/sol.go @@ -0,0 +1,9 @@ +func xorOperation(n int, start int) int { + ans := 0 + for n > 0 { + ans ^= start + start += 2 + n-- + } + return ans +} diff --git a/tests/1001-1500/1486. xor-operation-in-an-array/sol.java b/tests/1001-1500/1486. xor-operation-in-an-array/sol.java new file mode 100644 index 00000000..d20026fc --- /dev/null +++ b/tests/1001-1500/1486. xor-operation-in-an-array/sol.java @@ -0,0 +1,11 @@ +class Solution { + public int xorOperation(int n, int start) { + int ans = 0; + while (n > 0) { + ans ^= start; + start += 2; + n--; + } + return ans; + } +} diff --git a/tests/1001-1500/1486. xor-operation-in-an-array/sol.kt b/tests/1001-1500/1486. xor-operation-in-an-array/sol.kt new file mode 100644 index 00000000..b47a1174 --- /dev/null +++ b/tests/1001-1500/1486. xor-operation-in-an-array/sol.kt @@ -0,0 +1,13 @@ +class Solution { + fun xorOperation(n: Int, start: Int): Int { + var ans = 0 + var currentStart = start + var remaining = n + while (remaining > 0) { + ans = ans xor currentStart + currentStart += 2 + remaining-- + } + return ans + } +} diff --git a/tests/1001-1500/1486. xor-operation-in-an-array/sol.py b/tests/1001-1500/1486. xor-operation-in-an-array/sol.py new file mode 100644 index 00000000..e59e0a58 --- /dev/null +++ b/tests/1001-1500/1486. xor-operation-in-an-array/sol.py @@ -0,0 +1,10 @@ +class Solution: + def xorOperation(self, n: int, start: int) -> int: + ans = 0 + + while n: + ans ^= start + start += 2 + n -= 1 + + return ans diff --git a/tests/1001-1500/1486. xor-operation-in-an-array/sol.py2 b/tests/1001-1500/1486. xor-operation-in-an-array/sol.py2 new file mode 100644 index 00000000..b869b80e --- /dev/null +++ b/tests/1001-1500/1486. xor-operation-in-an-array/sol.py2 @@ -0,0 +1,13 @@ +class Solution(object): + def xorOperation(self, n, start): + """ + :type n: int + :type start: int + :rtype: int + """ + ans = 0 + while n: + ans ^= start + start += 2 + n -= 1 + return ans diff --git a/tests/1001-1500/1486. xor-operation-in-an-array/sol.rb b/tests/1001-1500/1486. xor-operation-in-an-array/sol.rb new file mode 100644 index 00000000..294f220f --- /dev/null +++ b/tests/1001-1500/1486. xor-operation-in-an-array/sol.rb @@ -0,0 +1,12 @@ +# @param {Integer} n +# @param {Integer} start +# @return {Integer} +def xor_operation(n, start) + ans = 0 + while n > 0 + ans ^= start + start += 2 + n -= 1 + end + ans +end diff --git a/tests/1001-1500/1486. xor-operation-in-an-array/sol.rs b/tests/1001-1500/1486. xor-operation-in-an-array/sol.rs new file mode 100644 index 00000000..3bb6e6a7 --- /dev/null +++ b/tests/1001-1500/1486. xor-operation-in-an-array/sol.rs @@ -0,0 +1,13 @@ +impl Solution { + pub fn xor_operation(n: i32, start: i32) -> i32 { + let mut ans = 0; + let mut current_start = start; + let mut remaining = n; + while remaining > 0 { + ans ^= current_start; + current_start += 2; + remaining -= 1; + } + ans + } +} diff --git a/tests/1001-1500/1486. xor-operation-in-an-array/sol.swift b/tests/1001-1500/1486. xor-operation-in-an-array/sol.swift new file mode 100644 index 00000000..e1205f1b --- /dev/null +++ b/tests/1001-1500/1486. xor-operation-in-an-array/sol.swift @@ -0,0 +1,13 @@ +class Solution { + func xorOperation(_ n: Int, _ start: Int) -> Int { + var ans = 0 + var currentStart = start + var remaining = n + while remaining > 0 { + ans ^= currentStart + currentStart += 2 + remaining -= 1 + } + return ans + } +} diff --git a/tests/1001-1500/1486. xor-operation-in-an-array/sol.ts b/tests/1001-1500/1486. xor-operation-in-an-array/sol.ts new file mode 100644 index 00000000..dabc1da6 --- /dev/null +++ b/tests/1001-1500/1486. xor-operation-in-an-array/sol.ts @@ -0,0 +1,9 @@ +function xorOperation(n: number, start: number): number { + let ans = 0; + while (n > 0) { + ans ^= start; + start += 2; + n--; + } + return ans; +} diff --git a/tests/1001-1500/1487. making-file-names-unique/manifest.yaml b/tests/1001-1500/1487. making-file-names-unique/manifest.yaml new file mode 100644 index 00000000..4850ec53 --- /dev/null +++ b/tests/1001-1500/1487. making-file-names-unique/manifest.yaml @@ -0,0 +1,258 @@ +entry: + id: 1487 + title: "making-file-names-unique" + params: + names: + type: array + items: + type: string + call: + cpp: "Solution().getFolderNames({names})" + rust: "Solution::get_folder_names({names})" + python3: "Solution().getFolderNames({names})" + python2: "Solution().getFolderNames({names})" + ruby: "get_folder_names({names})" + java: "new Solution().getFolderNames({names})" + csharp: "new Solution().GetFolderNames({names})" + kotlin: "Solution().getFolderNames({names})" + go: "getFolderNames({names})" + dart: "Solution().getFolderNames({names})" + swift: "Solution().getFolderNames({names})" + typescript: "getFolderNames({names})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().getFolderNames(names, {result})" + checker: | + class Checker: + def getFolderNames(self, names, result): + used = set() + next_suffix = {} + expected = [] + for name in names: + if name not in used: + chosen = name + next_suffix.setdefault(name, 1) + else: + suffix = next_suffix.get(name, 1) + chosen = name + "(" + str(suffix) + ")" + while chosen in used: + suffix += 1 + chosen = name + "(" + str(suffix) + ")" + next_suffix[name] = suffix + 1 + next_suffix.setdefault(chosen, 1) + used.add(chosen) + expected.append(chosen) + return result == expected + +seed: 1487 + +tests: + - name: "example-one" + in: + names: ["pes", "fifa", "gta", "pes(2019)"] + out: ["pes", "fifa", "gta", "pes(2019)"] + - name: "example-two" + in: + names: ["gta", "gta(1)", "gta", "avalon"] + out: ["gta", "gta(1)", "gta(2)", "avalon"] + - name: "example-three" + in: + names: + ["onepiece", "onepiece(1)", "onepiece(2)", "onepiece(3)", "onepiece"] + out: + ["onepiece", "onepiece(1)", "onepiece(2)", "onepiece(3)", "onepiece(4)"] + - name: "single-name" + in: + names: ["file"] + - name: "single-suffixed-name" + in: + names: ["file(1)"] + - name: "two-duplicates" + in: + names: ["a", "a"] + - name: "three-duplicates" + in: + names: ["a", "a", "a"] + - name: "reserved-one" + in: + names: ["a", "a(1)", "a"] + - name: "reserved-gap" + in: + names: ["a", "a(2)", "a", "a"] + - name: "reserved-many" + in: + names: ["a", "a(1)", "a(2)", "a(3)", "a"] + - name: "interleaved-bases" + in: + names: ["a", "b", "a", "b", "a", "b"] + - name: "suffix-first" + in: + names: ["x(1)", "x", "x"] + - name: "suffix-collides-later" + in: + names: ["x", "x", "x(1)", "x"] + - name: "nested-looking" + in: + names: ["a", "a(1)", "a(1)", "a", "a(1)"] + - name: "different-parentheses" + in: + names: ["doc", "doc(1)", "doc(1)(1)", "doc", "doc(1)"] + - name: "spaces" + in: + names: ["my file", "my file", "my file(1)", "my file"] + - name: "hyphenated" + in: + names: ["my-file", "my-file", "my-file(2)", "my-file"] + - name: "case-sensitive" + in: + names: ["File", "file", "File", "file"] + - name: "numeric-text" + in: + names: ["123", "123", "123(1)", "123"] + - name: "long-base" + in: + names: + ["abcdefghijklmnopqrst", "abcdefghijklmnopqrst", "abcdefghijklmnopqrst"] + - name: "many-bases" + in: + names: ["a", "b", "c", "d", "e", "a", "b", "c", "d", "e"] + - name: "five-preassigned" + in: + names: ["p", "p(1)", "p(2)", "p(3)", "p(4)", "p"] + - name: "nonsequential-reservations" + in: + names: ["q", "q(5)", "q(3)", "q(1)", "q", "q", "q"] + - name: "suffix-chain" + in: + names: ["z", "z", "z(1)", "z(2)", "z(3)", "z", "z"] + - name: "two-level-collision" + in: + names: ["a", "a", "a(2)", "a(1)", "a", "a(2)"] + - name: "mixed-words" + in: + names: ["alpha", "beta", "alpha", "gamma", "beta", "alpha"] + - name: "underscore" + in: + names: ["x_y", "x_y", "x_y(1)", "x_y(3)", "x_y"] + - name: "dash-and-space" + in: + names: ["a-b c", "a-b c", "a-b c(1)", "a-b c(2)", "a-b c"] + - name: "ten-repeated" + in: + names: + [ + "same", + "same", + "same", + "same", + "same", + "same", + "same", + "same", + "same", + "same", + ] + - name: "repeated-with-all-suffixes" + in: + names: ["r", "r(1)", "r(2)", "r(3)", "r(4)", "r(5)", "r", "r", "r"] + - name: "alternating-reserved" + in: + names: ["a", "b", "a(1)", "b(1)", "a", "b", "a(2)", "b(2)"] + - name: "mixed-suffix-bases" + in: + names: ["one", "one(1)", "two", "one", "two(1)", "two", "one"] + - name: "large-suffix-start" + in: + names: ["folder(999)", "folder", "folder", "folder(1000)", "folder"] + - name: "thirty-two-pattern" + in: + names: + [ + "a", + "b", + "a", + "c", + "b", + "a", + "c", + "a", + "b", + "c", + "a", + "b", + "a", + "c", + "b", + "a", + "c", + "b", + "a", + "b", + "c", + "a", + "a", + "b", + "c", + "b", + "a", + "c", + "a", + "b", + "c", + "a", + ] + - name: "late-preassigned-suffix" + in: + names: + [ + "project", + "project(1)", + "project(4)", + "project", + "project(2)", + "project", + "project", + ] + - name: "suffix-created-before-explicit-name" + in: + names: ["a", "a", "a(1)", "a", "a(2)", "a(1)", "a"] + - name: "parenthesized-base-collision" + in: + names: ["x(1)", "x(1)", "x", "x", "x(1)", "x"] + - name: "digits-and-parentheses" + in: + names: ["v9", "v9(1)", "v9", "v9(2)", "v9", "v9(1)", "v9(3)"] + - name: "maximum-repeated-name-stress" + seed: 1487001 + in: + names: + gen: "array" + len: 1000 + of: + gen: "str" + len: 20 + alphabet: "z" + distinct: false + sorted: false + elemType: "string" + - name: "maximum-generated-array-stress" + seed: 1487002 + in: + names: + gen: "array" + len: 1000 + of: + gen: "str" + len: 10 + alphabet: "abc12" + distinct: false + sorted: false + elemType: "string" diff --git a/tests/1001-1500/1487. making-file-names-unique/sol.cpp b/tests/1001-1500/1487. making-file-names-unique/sol.cpp new file mode 100644 index 00000000..123e08ac --- /dev/null +++ b/tests/1001-1500/1487. making-file-names-unique/sol.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + vector getFolderNames(vector& names) { + unordered_map nameCount; + vector result; + + for (const string& name : names) { + if (nameCount.find(name) == nameCount.end()) { + result.push_back(name); + nameCount[name] = 1; + } else { + int k = nameCount[name]; + while (nameCount.find(name + "(" + to_string(k) + ")") != nameCount.end()) { + k++; + } + string newName = name + "(" + to_string(k) + ")"; + result.push_back(newName); + nameCount[name] = k + 1; + nameCount[newName] = 1; + } + } + + return result; + } +}; diff --git a/tests/1001-1500/1487. making-file-names-unique/sol.cs b/tests/1001-1500/1487. making-file-names-unique/sol.cs new file mode 100644 index 00000000..d9b87409 --- /dev/null +++ b/tests/1001-1500/1487. making-file-names-unique/sol.cs @@ -0,0 +1,25 @@ +public class Solution { + public string[] GetFolderNames(string[] names) { + Dictionary nameCount = new Dictionary(); + string[] result = new string[names.Length]; + int idx = 0; + + foreach (string name in names) { + if (!nameCount.ContainsKey(name)) { + result[idx++] = name; + nameCount[name] = 1; + } else { + int k = nameCount[name]; + while (nameCount.ContainsKey(name + "(" + k + ")")) { + k++; + } + string newName = name + "(" + k + ")"; + result[idx++] = newName; + nameCount[name] = k + 1; + nameCount[newName] = 1; + } + } + + return result; + } +} diff --git a/tests/1001-1500/1487. making-file-names-unique/sol.dart b/tests/1001-1500/1487. making-file-names-unique/sol.dart new file mode 100644 index 00000000..846a24f7 --- /dev/null +++ b/tests/1001-1500/1487. making-file-names-unique/sol.dart @@ -0,0 +1,24 @@ +class Solution { + List getFolderNames(List names) { + Map nameCount = {}; + List result = []; + + for (String name in names) { + if (!nameCount.containsKey(name)) { + result.add(name); + nameCount[name] = 1; + } else { + int k = nameCount[name]!; + while (nameCount.containsKey('$name($k)')) { + k++; + } + String newName = '$name($k)'; + result.add(newName); + nameCount[name] = k + 1; + nameCount[newName] = 1; + } + } + + return result; + } +} diff --git a/tests/1001-1500/1487. making-file-names-unique/sol.go b/tests/1001-1500/1487. making-file-names-unique/sol.go new file mode 100644 index 00000000..2b729852 --- /dev/null +++ b/tests/1001-1500/1487. making-file-names-unique/sol.go @@ -0,0 +1,26 @@ +func getFolderNames(names []string) []string { + nameCount := make(map[string]int) + result := make([]string, 0, len(names)) + + for _, name := range names { + if _, exists := nameCount[name]; !exists { + result = append(result, name) + nameCount[name] = 1 + } else { + k := nameCount[name] + for { + candidate := fmt.Sprintf("%s(%d)", name, k) + if _, exists := nameCount[candidate]; !exists { + break + } + k++ + } + newName := fmt.Sprintf("%s(%d)", name, k) + result = append(result, newName) + nameCount[name] = k + 1 + nameCount[newName] = 1 + } + } + + return result +} diff --git a/tests/1001-1500/1487. making-file-names-unique/sol.java b/tests/1001-1500/1487. making-file-names-unique/sol.java new file mode 100644 index 00000000..ea571162 --- /dev/null +++ b/tests/1001-1500/1487. making-file-names-unique/sol.java @@ -0,0 +1,25 @@ +class Solution { + public String[] getFolderNames(String[] names) { + Map nameCount = new HashMap<>(); + String[] result = new String[names.length]; + int idx = 0; + + for (String name : names) { + if (!nameCount.containsKey(name)) { + result[idx++] = name; + nameCount.put(name, 1); + } else { + int k = nameCount.get(name); + while (nameCount.containsKey(name + "(" + k + ")")) { + k++; + } + String newName = name + "(" + k + ")"; + result[idx++] = newName; + nameCount.put(name, k + 1); + nameCount.put(newName, 1); + } + } + + return result; + } +} diff --git a/tests/1001-1500/1487. making-file-names-unique/sol.kt b/tests/1001-1500/1487. making-file-names-unique/sol.kt new file mode 100644 index 00000000..91c479c0 --- /dev/null +++ b/tests/1001-1500/1487. making-file-names-unique/sol.kt @@ -0,0 +1,24 @@ +class Solution { + fun getFolderNames(names: Array): Array { + val nameCount = mutableMapOf() + val result = mutableListOf() + + for (name in names) { + if (!nameCount.containsKey(name)) { + result.add(name) + nameCount[name] = 1 + } else { + var k = nameCount[name]!! + while (nameCount.containsKey("$name($k)")) { + k++ + } + val newName = "$name($k)" + result.add(newName) + nameCount[name] = k + 1 + nameCount[newName] = 1 + } + } + + return result.toTypedArray() + } +} diff --git a/tests/1001-1500/1487. making-file-names-unique/sol.py b/tests/1001-1500/1487. making-file-names-unique/sol.py new file mode 100644 index 00000000..302a57c5 --- /dev/null +++ b/tests/1001-1500/1487. making-file-names-unique/sol.py @@ -0,0 +1,23 @@ +class Solution(object): + def getFolderNames(self, names): + """ + :type names: List[str] + :rtype: List[str] + """ + name_count = dict() + result = [] + + for name in names: + if name not in name_count: + result.append(name) + name_count[name] = 1 + else: + k = name_count[name] + while "%s(%d)" % (name, k) in name_count: + k += 1 + new_name = "%s(%d)" % (name, k) + result.append(new_name) + name_count[name] = k + 1 + name_count[new_name] = 1 + + return result diff --git a/tests/1001-1500/1487. making-file-names-unique/sol.py2 b/tests/1001-1500/1487. making-file-names-unique/sol.py2 new file mode 100644 index 00000000..302a57c5 --- /dev/null +++ b/tests/1001-1500/1487. making-file-names-unique/sol.py2 @@ -0,0 +1,23 @@ +class Solution(object): + def getFolderNames(self, names): + """ + :type names: List[str] + :rtype: List[str] + """ + name_count = dict() + result = [] + + for name in names: + if name not in name_count: + result.append(name) + name_count[name] = 1 + else: + k = name_count[name] + while "%s(%d)" % (name, k) in name_count: + k += 1 + new_name = "%s(%d)" % (name, k) + result.append(new_name) + name_count[name] = k + 1 + name_count[new_name] = 1 + + return result diff --git a/tests/1001-1500/1487. making-file-names-unique/sol.rb b/tests/1001-1500/1487. making-file-names-unique/sol.rb new file mode 100644 index 00000000..9d3a9f09 --- /dev/null +++ b/tests/1001-1500/1487. making-file-names-unique/sol.rb @@ -0,0 +1,24 @@ +# @param {String[]} names +# @return {String[]} +def get_folder_names(names) + name_count = {} + result = [] + + names.each do |name| + if !name_count.key?(name) + result << name + name_count[name] = 1 + else + k = name_count[name] + while name_count.key?("#{name}(#{k})") + k += 1 + end + new_name = "#{name}(#{k})" + result << new_name + name_count[name] = k + 1 + name_count[new_name] = 1 + end + end + + result +end diff --git a/tests/1001-1500/1487. making-file-names-unique/sol.rs b/tests/1001-1500/1487. making-file-names-unique/sol.rs new file mode 100644 index 00000000..1fb876fa --- /dev/null +++ b/tests/1001-1500/1487. making-file-names-unique/sol.rs @@ -0,0 +1,26 @@ +impl Solution { + pub fn get_folder_names(names: Vec) -> Vec { + use std::collections::HashMap; + + let mut name_count: HashMap = HashMap::new(); + let mut result: Vec = Vec::new(); + + for name in names { + if !name_count.contains_key(&name) { + result.push(name.clone()); + name_count.insert(name, 1); + } else { + let mut k = *name_count.get(&name).unwrap(); + while name_count.contains_key(&format!("{}({})", name, k)) { + k += 1; + } + let new_name = format!("{}({})", name, k); + result.push(new_name.clone()); + name_count.insert(name, k + 1); + name_count.insert(new_name, 1); + } + } + + result + } +} diff --git a/tests/1001-1500/1487. making-file-names-unique/sol.swift b/tests/1001-1500/1487. making-file-names-unique/sol.swift new file mode 100644 index 00000000..a57d0b94 --- /dev/null +++ b/tests/1001-1500/1487. making-file-names-unique/sol.swift @@ -0,0 +1,24 @@ +class Solution { + func getFolderNames(_ names: [String]) -> [String] { + var nameCount = [String: Int]() + var result = [String]() + + for name in names { + if nameCount[name] == nil { + result.append(name) + nameCount[name] = 1 + } else { + var k = nameCount[name]! + while nameCount["\(name)(\(k))"] != nil { + k += 1 + } + let newName = "\(name)(\(k))" + result.append(newName) + nameCount[name] = k + 1 + nameCount[newName] = 1 + } + } + + return result + } +} diff --git a/tests/1001-1500/1487. making-file-names-unique/sol.ts b/tests/1001-1500/1487. making-file-names-unique/sol.ts new file mode 100644 index 00000000..1ce5fbbc --- /dev/null +++ b/tests/1001-1500/1487. making-file-names-unique/sol.ts @@ -0,0 +1,22 @@ +function getFolderNames(names: string[]): string[] { + const nameCount = new Map(); + const result: string[] = []; + + for (const name of names) { + if (!nameCount.has(name)) { + result.push(name); + nameCount.set(name, 1); + } else { + let k = nameCount.get(name)!; + while (nameCount.has(`${name}(${k})`)) { + k++; + } + const newName = `${name}(${k})`; + result.push(newName); + nameCount.set(name, k + 1); + nameCount.set(newName, 1); + } + } + + return result; +} diff --git a/tests/1001-1500/1488. avoid-flood-in-the-city/manifest.yaml b/tests/1001-1500/1488. avoid-flood-in-the-city/manifest.yaml new file mode 100644 index 00000000..d1093c2a --- /dev/null +++ b/tests/1001-1500/1488. avoid-flood-in-the-city/manifest.yaml @@ -0,0 +1,247 @@ +entry: + id: 1488 + title: "avoid-flood-in-the-city" + params: + rains: + type: array + items: + type: int + call: + cpp: "Solution().avoidFlood({rains})" + rust: "Solution::avoid_flood({rains})" + python3: "Solution().avoidFlood({rains})" + python2: "Solution().avoidFlood({rains})" + ruby: "avoid_flood({rains})" + java: "new Solution().avoidFlood({rains})" + csharp: "new Solution().AvoidFlood({rains})" + kotlin: "Solution().avoidFlood({rains})" + go: "avoidFlood({rains})" + dart: "Solution().avoidFlood({rains})" + swift: "Solution().avoidFlood({rains})" + typescript: "avoidFlood({rains})" +judge: + type: "exact" +limits: + time_ms: 1000 + memory_mb: 300 +oracle: + python3: + call: "Checker().avoidFlood(rains, {result})" + checker: | + class Checker: + def avoidFlood(self, rains, result): + if not isinstance(result, list): + return False + if result == []: + size = len(rains) + tree = [0] * (size + 1) + + def update(index, delta): + index += 1 + while index <= size: + tree[index] += delta + index += index & -index + + def prefix(end): + total = 0 + while end > 0: + total += tree[end] + end -= end & -end + return total + + def kth(order): + index = 0 + bit = 1 << (size.bit_length() - 1) + while bit: + next_index = index + bit + if next_index <= size and tree[next_index] < order: + index = next_index + order -= tree[next_index] + bit >>= 1 + return index + + available = 0 + last_rain = {} + for day, lake in enumerate(rains): + if lake == 0: + update(day, 1) + available += 1 + elif lake in last_rain: + before = prefix(last_rain[lake] + 1) + if available <= before: + return True + update(kth(before + 1), -1) + available -= 1 + last_rain[lake] = day + else: + last_rain[lake] = day + return False + if len(result) != len(rains): + return False + full = set() + for day, lake in enumerate(rains): + selected = result[day] + if lake > 0: + if selected != -1 or lake in full: + return False + full.add(lake) + else: + if selected <= 0: + return False + full.discard(selected) + return True +seed: 1488 +tests: + - name: "official-no-repeat" + in: + rains: [1, 2, 3, 4] + - name: "official-repeatable" + in: + rains: [1, 2, 0, 0, 2, 1] + - name: "official-impossible" + in: + rains: [1, 2, 0, 1, 2] + - name: "single-rain" + in: + rains: [7] + - name: "single-dry" + in: + rains: [0] + - name: "rain-dry-rain" + in: + rains: [4, 0, 4] + - name: "dry-before-rain" + in: + rains: [0, 5] + - name: "many-dry-days" + in: + rains: [0, 0, 0, 8] + - name: "two-lakes-one-dry" + in: + rains: [1, 2, 0, 1, 2] + - name: "two-lakes-two-dry" + in: + rains: [1, 2, 0, 0, 1, 2] + - name: "same-lake-spaced" + in: + rains: [3, 0, 0, 3, 0, 3] + - name: "same-lake-no-dry" + in: + rains: [3, 3] + - name: "three-lakes-cyclic" + in: + rains: [1, 2, 3, 0, 1, 0, 2, 0, 3] + - name: "three-lakes-short" + in: + rains: [1, 2, 3, 0, 1, 2, 3] + - name: "dry-reused-choice" + in: + rains: [5, 0, 5, 0, 6, 0, 6] + - name: "large-lake-id" + in: + rains: [1000000000, 0, 1000000000] + - name: "several-large-ids" + in: + rains: [999999999, 888888888, 0, 999999999, 0, 888888888] + - name: "dry-after-every-rain" + in: + rains: [1, 0, 2, 0, 3, 0, 4] + - name: "dry-days-too-late" + in: + rains: [1, 2, 1, 0, 2] + - name: "one-dry-for-two-repeats" + in: + rains: [1, 2, 0, 1, 2, 1] + - name: "four-lake-cycle" + in: + rains: [1, 2, 3, 4, 0, 1, 0, 2, 0, 3, 0, 4] + - name: "four-lake-cycle-short" + in: + rains: [1, 2, 3, 4, 0, 1, 2, 3, 4] + - name: "repeated-single-lake" + in: + rains: [9, 0, 9, 0, 9, 0, 9] + - name: "zero-heavy-prefix" + in: + rains: [0, 0, 1, 2, 0, 1, 2] + - name: "zero-heavy-between" + in: + rains: [1, 0, 0, 0, 1, 0, 0, 1] + - name: "alternating-lakes" + in: + rains: [1, 2, 1, 2, 0, 0] + - name: "alternating-with-space" + in: + rains: [1, 2, 0, 1, 2, 0] + - name: "five-lakes-all-repeat" + in: + rains: [1, 2, 3, 4, 5, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5] + - name: "five-lakes-insufficient" + in: + rains: [1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5] + - name: "dry-empty-lake-allowed" + in: + rains: [0, 1, 0, 2] + - name: "dry-selection-must-be-positive" + in: + rains: [1, 0, 2, 0, 1, 2] + - name: "late-single-repeat" + in: + rains: [6, 0, 0, 0, 0, 6] + - name: "multiple-independent-repeats" + in: + rains: [1, 0, 2, 0, 3, 0, 1, 2, 3] + - name: "nested-repeats" + in: + rains: [1, 2, 0, 3, 0, 2, 0, 1, 3] + - name: "long-safe-sequence" + in: + rains: [1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 1, 0, 2, 0, 3] + - name: "long-impossible-sequence" + in: + rains: [1, 2, 3, 1, 2, 3, 0, 0] + - name: "maximum-all-dry-days" + seed: 148801 + in: + rains: + gen: "array" + len: 100000 + of: + gen: "int" + min: 0 + max: 0 + elemType: "int" + - name: "maximum-single-lake-repeat" + seed: 148802 + in: + rains: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 1 + elemType: "int" + - name: "maximum-distinct-lakes" + seed: 148803 + in: + rains: + gen: "array" + len: 100000 + distinct: true + of: + gen: "int" + min: 1 + max: 1000000000 + elemType: "int" + - name: "maximum-boundary-values" + seed: 148804 + in: + rains: + gen: "array" + len: 100000 + of: + gen: "int" + min: 0 + max: 1000000000 + elemType: "int" diff --git a/tests/1001-1500/1488. avoid-flood-in-the-city/sol.cpp b/tests/1001-1500/1488. avoid-flood-in-the-city/sol.cpp new file mode 100644 index 00000000..2e4d296b --- /dev/null +++ b/tests/1001-1500/1488. avoid-flood-in-the-city/sol.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + vector avoidFlood(vector& rains) { + int n = rains.size(); + vector res(n, -1); + unordered_map full; + set dry; + for (int i = 0; i < n; i++) { + int lake = rains[i]; + if (lake == 0) { + dry.insert(i); + res[i] = 1; + } else if (full.count(lake)) { + auto it = dry.upper_bound(full[lake]); + if (it == dry.end()) return {}; + int j = *it; + res[j] = lake; + dry.erase(it); + full[lake] = i; + } else { + full[lake] = i; + } + } + return res; + } +}; diff --git a/tests/1001-1500/1488. avoid-flood-in-the-city/sol.cs b/tests/1001-1500/1488. avoid-flood-in-the-city/sol.cs new file mode 100644 index 00000000..98ff37b4 --- /dev/null +++ b/tests/1001-1500/1488. avoid-flood-in-the-city/sol.cs @@ -0,0 +1,26 @@ +public class Solution { + public int[] AvoidFlood(int[] rains) { + int n = rains.Length; + int[] res = new int[n]; + Array.Fill(res, -1); + var full = new Dictionary(); + var dry = new SortedSet(); + for (int i = 0; i < n; i++) { + int lake = rains[i]; + if (lake == 0) { + dry.Add(i); + res[i] = 1; + } else if (full.ContainsKey(lake)) { + var view = dry.GetViewBetween(full[lake] + 1, int.MaxValue); + if (view.Count == 0) return new int[0]; + int j = view.Min; + res[j] = lake; + dry.Remove(j); + full[lake] = i; + } else { + full[lake] = i; + } + } + return res; + } +} diff --git a/tests/1001-1500/1488. avoid-flood-in-the-city/sol.dart b/tests/1001-1500/1488. avoid-flood-in-the-city/sol.dart new file mode 100644 index 00000000..a8aec449 --- /dev/null +++ b/tests/1001-1500/1488. avoid-flood-in-the-city/sol.dart @@ -0,0 +1,37 @@ +class Solution { + List avoidFlood(List rains) { + int n = rains.length; + List res = List.filled(n, -1); + Map full = {}; + List dry = []; + for (int i = 0; i < n; i++) { + int lake = rains[i]; + if (lake == 0) { + dry.add(i); + res[i] = 1; + } else if (full.containsKey(lake)) { + int prev = full[lake]!; + // binary search for first index > prev + int left = 0, right = dry.length; + while (left < right) { + int mid = left + (right - left) ~/ 2; + if (dry[mid] <= prev) { + left = mid + 1; + } else { + right = mid; + } + } + if (left == dry.length) { + return []; + } + int j = dry[left]; + res[j] = lake; + dry.removeAt(left); + full[lake] = i; + } else { + full[lake] = i; + } + } + return res; + } +} diff --git a/tests/1001-1500/1488. avoid-flood-in-the-city/sol.go b/tests/1001-1500/1488. avoid-flood-in-the-city/sol.go new file mode 100644 index 00000000..fbe367df --- /dev/null +++ b/tests/1001-1500/1488. avoid-flood-in-the-city/sol.go @@ -0,0 +1,36 @@ +func avoidFlood(rains []int) []int { + n := len(rains) + res := make([]int, n) + for i := range res { + res[i] = -1 + } + full := make(map[int]int) + dry := []int{} + for i, lake := range rains { + if lake == 0 { + dry = append(dry, i) + res[i] = 1 + } else if prev, ok := full[lake]; ok { + // binary search for first index > prev + left, right := 0, len(dry) + for left < right { + mid := left + (right-left)/2 + if dry[mid] <= prev { + left = mid + 1 + } else { + right = mid + } + } + if left == len(dry) { + return []int{} + } + j := dry[left] + res[j] = lake + dry = append(dry[:left], dry[left+1:]...) + full[lake] = i + } else { + full[lake] = i + } + } + return res +} diff --git a/tests/1001-1500/1488. avoid-flood-in-the-city/sol.java b/tests/1001-1500/1488. avoid-flood-in-the-city/sol.java new file mode 100644 index 00000000..407de531 --- /dev/null +++ b/tests/1001-1500/1488. avoid-flood-in-the-city/sol.java @@ -0,0 +1,29 @@ +import java.util.*; + +class Solution { + public int[] avoidFlood(int[] rains) { + int n = rains.length; + int[] res = new int[n]; + Arrays.fill(res, -1); + Map full = new HashMap<>(); + TreeSet dry = new TreeSet<>(); + for (int i = 0; i < n; i++) { + int lake = rains[i]; + if (lake == 0) { + dry.add(i); + res[i] = 1; + } else if (full.containsKey(lake)) { + Integer j = dry.higher(full.get(lake)); + if (j == null) { + return new int[0]; + } + res[j] = lake; + dry.remove(j); + full.put(lake, i); + } else { + full.put(lake, i); + } + } + return res; + } +} diff --git a/tests/1001-1500/1488. avoid-flood-in-the-city/sol.kt b/tests/1001-1500/1488. avoid-flood-in-the-city/sol.kt new file mode 100644 index 00000000..bffc8ff3 --- /dev/null +++ b/tests/1001-1500/1488. avoid-flood-in-the-city/sol.kt @@ -0,0 +1,25 @@ +import java.util.* + +class Solution { + fun avoidFlood(rains: IntArray): IntArray { + val n = rains.size + val res = IntArray(n) { -1 } + val full = mutableMapOf() + val dry = TreeSet() + for (i in 0 until n) { + val lake = rains[i] + if (lake == 0) { + dry.add(i) + res[i] = 1 + } else if (full.containsKey(lake)) { + val j = dry.higher(full[lake]!!) ?: return intArrayOf() + res[j] = lake + dry.remove(j) + full[lake] = i + } else { + full[lake] = i + } + } + return res + } +} diff --git a/tests/1001-1500/1488. avoid-flood-in-the-city/sol.py b/tests/1001-1500/1488. avoid-flood-in-the-city/sol.py new file mode 100644 index 00000000..d0a133d4 --- /dev/null +++ b/tests/1001-1500/1488. avoid-flood-in-the-city/sol.py @@ -0,0 +1,21 @@ +from bisect import bisect_right +from sortedcontainers import SortedList + + +class Solution: + def avoidFlood(self, rains: List[int]) -> List[int]: + res, full, dry = [-1] * len(rains), {}, SortedList() + for i, lake in enumerate(rains): + if lake == 0: + dry.add(i) + res[i] = 1 + elif lake in full: + j = dry.bisect_right(full[lake]) + if j == len(dry): + return [] + res[dry[j]] = lake + dry.pop(j) + full[lake] = i + else: + full[lake] = i + return res diff --git a/tests/1001-1500/1488. avoid-flood-in-the-city/sol.py2 b/tests/1001-1500/1488. avoid-flood-in-the-city/sol.py2 new file mode 100644 index 00000000..c6eaeb36 --- /dev/null +++ b/tests/1001-1500/1488. avoid-flood-in-the-city/sol.py2 @@ -0,0 +1,24 @@ +class Solution(object): + def avoidFlood(self, rains): + """ + :type rains: List[int] + :rtype: List[int] + """ + from sortedcontainers import SortedList + res = [-1] * len(rains) + full = {} + dry = SortedList() + for i, lake in enumerate(rains): + if lake == 0: + dry.add(i) + res[i] = 1 + elif lake in full: + j = dry.bisect_right(full[lake]) + if j == len(dry): + return [] + res[dry[j]] = lake + dry.pop(j) + full[lake] = i + else: + full[lake] = i + return res diff --git a/tests/1001-1500/1488. avoid-flood-in-the-city/sol.rb b/tests/1001-1500/1488. avoid-flood-in-the-city/sol.rb new file mode 100644 index 00000000..367b6ec6 --- /dev/null +++ b/tests/1001-1500/1488. avoid-flood-in-the-city/sol.rb @@ -0,0 +1,60 @@ +# @param {Integer[]} rains +# @return {Integer[]} +def avoid_flood(rains) + res = Array.new(rains.size, -1) + full = {} + size = rains.size + tree = Array.new(size + 1, 0) + + add = lambda do |index, delta| + index += 1 + while index <= size + tree[index] += delta + index += index & -index + end + end + + prefix = lambda do |count| + total = 0 + while count > 0 + total += tree[count] + count -= count & -count + end + total + end + + kth = lambda do |rank| + index = 0 + step = 1 + step <<= 1 while (step << 1) <= size + while step > 0 + next_index = index + step + if next_index <= size && tree[next_index] < rank + index = next_index + rank -= tree[next_index] + end + step >>= 1 + end + index + end + + rains.each_with_index do |lake, i| + if lake == 0 + add.call(i, 1) + res[i] = 1 + elsif full.key?(lake) + before = prefix.call(full[lake] + 1) + available = prefix.call(size) - before + if available == 0 + return [] + end + j = kth.call(before + 1) + res[j] = lake + add.call(j, -1) + full[lake] = i + else + full[lake] = i + end + end + res +end diff --git a/tests/1001-1500/1488. avoid-flood-in-the-city/sol.rs b/tests/1001-1500/1488. avoid-flood-in-the-city/sol.rs new file mode 100644 index 00000000..89a6d109 --- /dev/null +++ b/tests/1001-1500/1488. avoid-flood-in-the-city/sol.rs @@ -0,0 +1,30 @@ +use std::collections::{HashMap, BTreeSet}; + +impl Solution { + pub fn avoid_flood(rains: Vec) -> Vec { + let n = rains.len(); + let mut res = vec![-1; n]; + let mut full: HashMap = HashMap::new(); + let mut dry: BTreeSet = BTreeSet::new(); + for i in 0..n { + let lake = rains[i]; + if lake == 0 { + dry.insert(i); + res[i] = 1; + } else if let Some(&prev) = full.get(&lake) { + let j = dry.range((prev + 1)..).next().copied(); + match j { + Some(idx) => { + res[idx] = lake; + dry.remove(&idx); + full.insert(lake, i); + } + None => return vec![], + } + } else { + full.insert(lake, i); + } + } + res + } +} diff --git a/tests/1001-1500/1488. avoid-flood-in-the-city/sol.swift b/tests/1001-1500/1488. avoid-flood-in-the-city/sol.swift new file mode 100644 index 00000000..113387e9 --- /dev/null +++ b/tests/1001-1500/1488. avoid-flood-in-the-city/sol.swift @@ -0,0 +1,36 @@ +class Solution { + func avoidFlood(_ rains: [Int]) -> [Int] { + let n = rains.count + var res = Array(repeating: -1, count: n) + var full = [Int: Int]() + var dry = [Int]() + for i in 0.. prev + var left = 0, right = dry.count + while left < right { + let mid = left + (right - left) / 2 + if dry[mid] <= prev { + left = mid + 1 + } else { + right = mid + } + } + if left == dry.count { + return [] + } + let j = dry[left] + res[j] = lake + dry.remove(at: left) + full[lake] = i + } else { + full[lake] = i + } + } + return res + } +} diff --git a/tests/1001-1500/1488. avoid-flood-in-the-city/sol.ts b/tests/1001-1500/1488. avoid-flood-in-the-city/sol.ts new file mode 100644 index 00000000..5a644979 --- /dev/null +++ b/tests/1001-1500/1488. avoid-flood-in-the-city/sol.ts @@ -0,0 +1,36 @@ +function avoidFlood(rains: number[]): number[] { + const n = rains.length; + const res: number[] = new Array(n).fill(-1); + const full = new Map(); + const dry: number[] = []; + for (let i = 0; i < n; i++) { + const lake = rains[i]; + if (lake === 0) { + dry.push(i); + res[i] = 1; + } else if (full.has(lake)) { + const prev = full.get(lake)!; + // binary search for first index > prev + let left = 0, + right = dry.length; + while (left < right) { + const mid = left + Math.floor((right - left) / 2); + if (dry[mid] <= prev) { + left = mid + 1; + } else { + right = mid; + } + } + if (left === dry.length) { + return []; + } + const j = dry[left]; + res[j] = lake; + dry.splice(left, 1); + full.set(lake, i); + } else { + full.set(lake, i); + } + } + return res; +} diff --git a/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/manifest.yaml b/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/manifest.yaml new file mode 100644 index 00000000..c9fda69e --- /dev/null +++ b/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/manifest.yaml @@ -0,0 +1,863 @@ +entry: + id: 1489 + title: "find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree" + params: + n: + type: int + edges: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().findCriticalAndPseudoCriticalEdges({n}, {edges})" + rust: "Solution::find_critical_and_pseudo_critical_edges({n}, {edges})" + python3: "Solution().findCriticalAndPseudoCriticalEdges({n}, {edges})" + python2: "Solution().findCriticalAndPseudoCriticalEdges({n}, {edges})" + ruby: "find_critical_and_pseudo_critical_edges({n}, {edges})" + java: "new Solution().findCriticalAndPseudoCriticalEdges({n}, {edges})" + csharp: "new Solution().FindCriticalAndPseudoCriticalEdges({n}, {edges})" + kotlin: "Solution().findCriticalAndPseudoCriticalEdges({n}, {edges})" + go: "findCriticalAndPseudoCriticalEdges({n}, {edges})" + dart: "Solution().findCriticalAndPseudoCriticalEdges({n}, {edges})" + swift: "Solution().findCriticalAndPseudoCriticalEdges({n}, {edges})" + typescript: "findCriticalAndPseudoCriticalEdges({n}, {edges})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().findCriticalAndPseudoCriticalEdges(n, edges, {result})" + checker: | + class Checker: + def findCriticalAndPseudoCriticalEdges(self, n, edges, result): + if not isinstance(result, list) or len(result) != 2: + return False + def mst(block=-1, force=-1): + parent = list(range(n)) + def find(x): + while parent[x] != x: + parent[x] = parent[parent[x]] + x = parent[x] + return x + def join(a, b): + a, b = find(a), find(b) + if a == b: + return False + parent[a] = b + return True + total = 0 + used = 0 + if force >= 0: + a, b, w = edges[force] + if join(a, b): + total += w + used += 1 + for i, (a, b, w) in sorted(enumerate(edges), key=lambda item: item[1][2]): + if i == block or i == force: + continue + if join(a, b): + total += w + used += 1 + return total if used == n - 1 else None + base = mst() + critical = [] + pseudo = [] + for i in range(len(edges)): + if mst(block=i) != base: + critical.append(i) + elif mst(force=i) == base: + pseudo.append(i) + try: + return sorted(result[0]) == critical and sorted(result[1]) == pseudo + except (TypeError, ValueError): + return False + +seed: 1489 + +tests: + - name: "example_one" + in: + n: 5 + edges: + elemType: "int" + value: + - [0, 1, 1] + - [1, 2, 1] + - [2, 3, 2] + - [0, 3, 2] + - [0, 4, 3] + - [3, 4, 3] + - [1, 4, 6] + - name: "example_two_equal_cycle" + in: + n: 4 + edges: + elemType: "int" + value: + - [0, 1, 1] + - [1, 2, 1] + - [2, 3, 1] + - [0, 3, 1] + - name: "single_mst_tree" + in: + n: 4 + edges: + elemType: "int" + value: + - [0, 1, 1] + - [1, 2, 2] + - [2, 3, 3] + - name: "two_vertices_one_edge" + in: + n: 2 + edges: + elemType: "int" + value: + - [0, 1, 1000] + - name: "triangle_unique_light" + in: + n: 3 + edges: + elemType: "int" + value: + - [0, 1, 1] + - [1, 2, 2] + - [0, 2, 9] + - name: "triangle_all_equal" + in: + n: 3 + edges: + elemType: "int" + value: + - [0, 1, 7] + - [1, 2, 7] + - [0, 2, 7] + - name: "triangle_two_equal" + in: + n: 3 + edges: + elemType: "int" + value: + - [0, 1, 1] + - [1, 2, 1] + - [0, 2, 5] + - name: "square_unique_diagonals" + in: + n: 4 + edges: + elemType: "int" + value: + - [0, 1, 1] + - [1, 2, 2] + - [2, 3, 3] + - [0, 3, 10] + - [0, 2, 8] + - [1, 3, 9] + - name: "square_equal_cycle" + in: + n: 4 + edges: + elemType: "int" + value: + - [0, 1, 4] + - [1, 2, 4] + - [2, 3, 4] + - [0, 3, 4] + - name: "square_two_mst_choices" + in: + n: 4 + edges: + elemType: "int" + value: + - [0, 1, 1] + - [1, 2, 1] + - [2, 3, 2] + - [0, 3, 2] + - [0, 2, 5] + - name: "star_tree" + in: + n: 5 + edges: + elemType: "int" + value: + - [0, 1, 1] + - [0, 2, 2] + - [0, 3, 3] + - [0, 4, 4] + - name: "star_with_heavy_chords" + in: + n: 5 + edges: + elemType: "int" + value: + - [0, 1, 1] + - [0, 2, 1] + - [0, 3, 1] + - [0, 4, 1] + - [1, 2, 8] + - [2, 3, 9] + - [3, 4, 10] + - name: "five_cycle_equal" + in: + n: 5 + edges: + elemType: "int" + value: + - [0, 1, 2] + - [1, 2, 2] + - [2, 3, 2] + - [3, 4, 2] + - [0, 4, 2] + - name: "five_cycle_chord" + in: + n: 5 + edges: + elemType: "int" + value: + - [0, 1, 1] + - [1, 2, 1] + - [2, 3, 1] + - [3, 4, 1] + - [0, 4, 1] + - [0, 2, 5] + - [1, 3, 6] + - name: "parallel_weight_levels" + in: + n: 5 + edges: + elemType: "int" + value: + - [0, 1, 1] + - [0, 2, 1] + - [1, 2, 1] + - [1, 3, 2] + - [2, 4, 2] + - [3, 4, 2] + - name: "six_vertex_tree_plus_edges" + in: + n: 6 + edges: + elemType: "int" + value: + - [0, 1, 3] + - [1, 2, 1] + - [2, 3, 4] + - [3, 4, 2] + - [4, 5, 5] + - [0, 2, 6] + - [1, 4, 7] + - [2, 5, 8] + - name: "six_vertex_equal_layers" + in: + n: 6 + edges: + elemType: "int" + value: + - [0, 1, 1] + - [0, 2, 1] + - [1, 3, 2] + - [2, 4, 2] + - [3, 5, 3] + - [4, 5, 3] + - name: "six_complete_small_weights" + in: + n: 6 + edges: + elemType: "int" + value: + - [0, 1, 1] + - [0, 2, 2] + - [0, 3, 3] + - [0, 4, 4] + - [0, 5, 5] + - [1, 2, 6] + - [1, 3, 7] + - [1, 4, 8] + - [1, 5, 9] + - [2, 3, 10] + - [2, 4, 11] + - [2, 5, 12] + - [3, 4, 13] + - [3, 5, 14] + - [4, 5, 15] + - name: "seven_path" + in: + n: 7 + edges: + elemType: "int" + value: + - [0, 1, 1] + - [1, 2, 2] + - [2, 3, 3] + - [3, 4, 4] + - [4, 5, 5] + - [5, 6, 6] + - name: "seven_path_shortcuts" + in: + n: 7 + edges: + elemType: "int" + value: + - [0, 1, 1] + - [1, 2, 1] + - [2, 3, 1] + - [3, 4, 1] + - [4, 5, 1] + - [5, 6, 1] + - [0, 6, 2] + - [1, 5, 2] + - name: "seven_two_clusters" + in: + n: 7 + edges: + elemType: "int" + value: + - [0, 1, 1] + - [1, 2, 1] + - [0, 2, 1] + - [3, 4, 1] + - [4, 5, 1] + - [3, 5, 1] + - [2, 3, 5] + - [1, 4, 5] + - [0, 6, 7] + - name: "eight_binary_equal" + in: + n: 8 + edges: + elemType: "int" + value: + - [0, 1, 3] + - [0, 2, 3] + - [1, 3, 3] + - [1, 4, 3] + - [2, 5, 3] + - [2, 6, 3] + - [3, 7, 3] + - [4, 7, 3] + - [5, 7, 3] + - [6, 7, 3] + - name: "eight_cycle_heavy_chords" + in: + n: 8 + edges: + elemType: "int" + value: + - [0, 1, 1] + - [1, 2, 2] + - [2, 3, 3] + - [3, 4, 4] + - [4, 5, 5] + - [5, 6, 6] + - [6, 7, 7] + - [0, 7, 20] + - [0, 4, 12] + - [2, 6, 13] + - name: "nine_star_equal" + in: + n: 9 + edges: + elemType: "int" + value: + - [0, 1, 5] + - [0, 2, 5] + - [0, 3, 5] + - [0, 4, 5] + - [0, 5, 5] + - [0, 6, 5] + - [0, 7, 5] + - [0, 8, 5] + - name: "nine_grid_like" + in: + n: 9 + edges: + elemType: "int" + value: + - [0, 1, 1] + - [1, 2, 1] + - [3, 4, 1] + - [4, 5, 1] + - [6, 7, 1] + - [7, 8, 1] + - [0, 3, 2] + - [1, 4, 2] + - [2, 5, 2] + - [3, 6, 2] + - [4, 7, 2] + - [5, 8, 2] + - name: "ten_path_equal_pairs" + in: + n: 10 + edges: + elemType: "int" + value: + - [0, 1, 1] + - [1, 2, 1] + - [2, 3, 2] + - [3, 4, 2] + - [4, 5, 3] + - [5, 6, 3] + - [6, 7, 4] + - [7, 8, 4] + - [8, 9, 5] + - [0, 9, 8] + - [1, 8, 7] + - name: "ten_two_equal_blocks" + in: + n: 10 + edges: + elemType: "int" + value: + - [0, 1, 1] + - [0, 2, 1] + - [1, 2, 1] + - [3, 4, 2] + - [3, 5, 2] + - [4, 5, 2] + - [6, 7, 3] + - [6, 8, 3] + - [7, 8, 3] + - [2, 3, 4] + - [5, 6, 4] + - [0, 9, 6] + - name: "eleven_chain_chords" + in: + n: 11 + edges: + elemType: "int" + value: + - [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] + - [0, 5, 5] + - [5, 10, 5] + - name: "twelve_tree_only" + in: + n: 12 + edges: + elemType: "int" + value: + - [0, 1, 12] + - [1, 2, 11] + - [2, 3, 10] + - [3, 4, 9] + - [4, 5, 8] + - [5, 6, 7] + - [6, 7, 6] + - [7, 8, 5] + - [8, 9, 4] + - [9, 10, 3] + - [10, 11, 2] + - name: "twelve_dense_light_edges" + in: + n: 12 + edges: + elemType: "int" + value: + - [0, 1, 1] + - [0, 2, 1] + - [1, 2, 1] + - [3, 4, 1] + - [3, 5, 1] + - [4, 5, 1] + - [6, 7, 1] + - [6, 8, 1] + - [7, 8, 1] + - [9, 10, 1] + - [9, 11, 1] + - [10, 11, 1] + - [2, 3, 4] + - [5, 6, 4] + - [8, 9, 4] + - name: "thirteen_mixed_weights" + in: + n: 13 + edges: + elemType: "int" + value: + - [0, 1, 10] + - [1, 2, 1] + - [2, 3, 10] + - [3, 4, 1] + - [4, 5, 10] + - [5, 6, 1] + - [6, 7, 10] + - [7, 8, 1] + - [8, 9, 10] + - [9, 10, 1] + - [10, 11, 10] + - [11, 12, 1] + - [0, 12, 20] + - [2, 10, 3] + - name: "fourteen_ring" + in: + n: 14 + edges: + elemType: "int" + value: + - [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] + - [0, 13, 3] + - [0, 7, 4] + - name: "fifteen_hub_and_cycles" + in: + n: 15 + edges: + elemType: "int" + value: + - [0, 1, 1] + - [0, 2, 1] + - [0, 3, 1] + - [0, 4, 1] + - [1, 5, 2] + - [2, 6, 2] + - [3, 7, 2] + - [4, 8, 2] + - [5, 6, 2] + - [6, 7, 2] + - [7, 8, 2] + - [5, 8, 2] + - [9, 10, 3] + - [10, 11, 3] + - [11, 12, 3] + - [12, 13, 3] + - [13, 14, 3] + - [8, 9, 4] + - name: "sixteen_equal_completeish" + in: + n: 16 + edges: + elemType: "int" + value: + - [0, 1, 1] + - [0, 2, 1] + - [0, 3, 1] + - [1, 2, 1] + - [1, 3, 1] + - [2, 3, 1] + - [4, 5, 2] + - [4, 6, 2] + - [5, 6, 2] + - [7, 8, 3] + - [7, 9, 3] + - [8, 9, 3] + - [3, 4, 5] + - [6, 7, 5] + - [9, 10, 5] + - [10, 11, 6] + - [11, 12, 6] + - [12, 13, 6] + - [13, 14, 6] + - [14, 15, 6] + - name: "twenty_long_tree_plus_chords" + in: + n: 20 + edges: + elemType: "int" + value: + - [0, 1, 1] + - [1, 2, 2] + - [2, 3, 3] + - [3, 4, 4] + - [4, 5, 5] + - [5, 6, 6] + - [6, 7, 7] + - [7, 8, 8] + - [8, 9, 9] + - [9, 10, 10] + - [10, 11, 11] + - [11, 12, 12] + - [12, 13, 13] + - [13, 14, 14] + - [14, 15, 15] + - [15, 16, 16] + - [16, 17, 17] + - [17, 18, 18] + - [18, 19, 19] + - [0, 19, 20] + - [0, 10, 21] + - [5, 15, 22] + - name: "six_vertex_bridge_tie" + in: + n: 6 + edges: + elemType: "int" + value: + - [0, 1, 1] + - [1, 2, 1] + - [0, 2, 1] + - [2, 3, 4] + - [2, 4, 4] + - [3, 4, 4] + - [3, 5, 9] + - [4, 5, 9] + - [0, 5, 20] + - name: "five_complete_weight_layers" + in: + n: 5 + edges: + elemType: "int" + value: + - [0, 1, 1] + - [0, 2, 1] + - [0, 3, 2] + - [0, 4, 2] + - [1, 2, 1] + - [1, 3, 2] + - [1, 4, 3] + - [2, 3, 2] + - [2, 4, 2] + - [3, 4, 2] + - name: "eight_boundary_weight_graph" + in: + n: 8 + edges: + elemType: "int" + value: + - [0, 1, 1000] + - [1, 2, 999] + - [2, 3, 998] + - [3, 4, 997] + - [4, 5, 996] + - [5, 6, 995] + - [6, 7, 994] + - [0, 2, 1] + - [2, 4, 1] + - [4, 6, 1] + - [1, 7, 2] + - [0, 7, 3] + - name: "hundred_vertex_unit_path" + in: + n: 100 + edges: + elemType: "int" + value: + - [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] + - [19, 20, 1] + - [20, 21, 1] + - [21, 22, 1] + - [22, 23, 1] + - [23, 24, 1] + - [24, 25, 1] + - [25, 26, 1] + - [26, 27, 1] + - [27, 28, 1] + - [28, 29, 1] + - [29, 30, 1] + - [30, 31, 1] + - [31, 32, 1] + - [32, 33, 1] + - [33, 34, 1] + - [34, 35, 1] + - [35, 36, 1] + - [36, 37, 1] + - [37, 38, 1] + - [38, 39, 1] + - [39, 40, 1] + - [40, 41, 1] + - [41, 42, 1] + - [42, 43, 1] + - [43, 44, 1] + - [44, 45, 1] + - [45, 46, 1] + - [46, 47, 1] + - [47, 48, 1] + - [48, 49, 1] + - [49, 50, 1] + - [50, 51, 1] + - [51, 52, 1] + - [52, 53, 1] + - [53, 54, 1] + - [54, 55, 1] + - [55, 56, 1] + - [56, 57, 1] + - [57, 58, 1] + - [58, 59, 1] + - [59, 60, 1] + - [60, 61, 1] + - [61, 62, 1] + - [62, 63, 1] + - [63, 64, 1] + - [64, 65, 1] + - [65, 66, 1] + - [66, 67, 1] + - [67, 68, 1] + - [68, 69, 1] + - [69, 70, 1] + - [70, 71, 1] + - [71, 72, 1] + - [72, 73, 1] + - [73, 74, 1] + - [74, 75, 1] + - [75, 76, 1] + - [76, 77, 1] + - [77, 78, 1] + - [78, 79, 1] + - [79, 80, 1] + - [80, 81, 1] + - [81, 82, 1] + - [82, 83, 1] + - [83, 84, 1] + - [84, 85, 1] + - [85, 86, 1] + - [86, 87, 1] + - [87, 88, 1] + - [88, 89, 1] + - [89, 90, 1] + - [90, 91, 1] + - [91, 92, 1] + - [92, 93, 1] + - [93, 94, 1] + - [94, 95, 1] + - [95, 96, 1] + - [96, 97, 1] + - [97, 98, 1] + - [98, 99, 1] + - name: "hundred_vertex_boundary_path" + in: + n: 100 + edges: + elemType: "int" + value: + - [0, 1, 1] + - [1, 2, 2] + - [2, 3, 3] + - [3, 4, 4] + - [4, 5, 5] + - [5, 6, 6] + - [6, 7, 7] + - [7, 8, 8] + - [8, 9, 9] + - [9, 10, 10] + - [10, 11, 11] + - [11, 12, 12] + - [12, 13, 13] + - [13, 14, 14] + - [14, 15, 15] + - [15, 16, 16] + - [16, 17, 17] + - [17, 18, 18] + - [18, 19, 19] + - [19, 20, 20] + - [20, 21, 21] + - [21, 22, 22] + - [22, 23, 23] + - [23, 24, 24] + - [24, 25, 25] + - [25, 26, 26] + - [26, 27, 27] + - [27, 28, 28] + - [28, 29, 29] + - [29, 30, 30] + - [30, 31, 31] + - [31, 32, 32] + - [32, 33, 33] + - [33, 34, 34] + - [34, 35, 35] + - [35, 36, 36] + - [36, 37, 37] + - [37, 38, 38] + - [38, 39, 39] + - [39, 40, 40] + - [40, 41, 41] + - [41, 42, 42] + - [42, 43, 43] + - [43, 44, 44] + - [44, 45, 45] + - [45, 46, 46] + - [46, 47, 47] + - [47, 48, 48] + - [48, 49, 49] + - [49, 50, 50] + - [50, 51, 51] + - [51, 52, 52] + - [52, 53, 53] + - [53, 54, 54] + - [54, 55, 55] + - [55, 56, 56] + - [56, 57, 57] + - [57, 58, 58] + - [58, 59, 59] + - [59, 60, 60] + - [60, 61, 61] + - [61, 62, 62] + - [62, 63, 63] + - [63, 64, 64] + - [64, 65, 65] + - [65, 66, 66] + - [66, 67, 67] + - [67, 68, 68] + - [68, 69, 69] + - [69, 70, 70] + - [70, 71, 71] + - [71, 72, 72] + - [72, 73, 73] + - [73, 74, 74] + - [74, 75, 75] + - [75, 76, 76] + - [76, 77, 77] + - [77, 78, 78] + - [78, 79, 79] + - [79, 80, 80] + - [80, 81, 81] + - [81, 82, 82] + - [82, 83, 83] + - [83, 84, 84] + - [84, 85, 85] + - [85, 86, 86] + - [86, 87, 87] + - [87, 88, 88] + - [88, 89, 89] + - [89, 90, 90] + - [90, 91, 91] + - [91, 92, 92] + - [92, 93, 93] + - [93, 94, 94] + - [94, 95, 95] + - [95, 96, 96] + - [96, 97, 97] + - [97, 98, 98] + - [98, 99, 1000] diff --git a/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.cpp b/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.cpp new file mode 100644 index 00000000..9a4b6f9b --- /dev/null +++ b/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.cpp @@ -0,0 +1,67 @@ +class Solution { +private: + class UnionFind { + public: + vector parent; + UnionFind(int n) { + parent.resize(n); + for (int i = 0; i < n; i++) { + parent[i] = i; + } + } + int findParent(int p) { + if (parent[p] == p) return p; + parent[p] = findParent(parent[p]); + return parent[p]; + } + void unionNodes(int u, int v) { + int pu = findParent(u); + int pv = findParent(v); + parent[pu] = pv; + } + }; + + int findMST(int n, vector>& edges, int block, int e) { + UnionFind uf(n); + int weight = 0; + if (e != -1) { + weight += edges[e][2]; + uf.unionNodes(edges[e][0], edges[e][1]); + } + for (int i = 0; i < edges.size(); i++) { + if (i == block) continue; + if (uf.findParent(edges[i][0]) == uf.findParent(edges[i][1])) continue; + uf.unionNodes(edges[i][0], edges[i][1]); + weight += edges[i][2]; + } + for (int i = 0; i < n; i++) { + if (uf.findParent(i) != uf.findParent(0)) return INT_MAX; + } + return weight; + } + +public: + vector> findCriticalAndPseudoCriticalEdges(int n, vector>& edges) { + vector critical, pseudoCritical; + int m = edges.size(); + vector> edgesWithIdx(m, vector(4)); + for (int i = 0; i < m; i++) { + edgesWithIdx[i][0] = edges[i][0]; + edgesWithIdx[i][1] = edges[i][1]; + edgesWithIdx[i][2] = edges[i][2]; + edgesWithIdx[i][3] = i; + } + sort(edgesWithIdx.begin(), edgesWithIdx.end(), [](vector& a, vector& b) { + return a[2] < b[2]; + }); + int mstwt = findMST(n, edgesWithIdx, -1, -1); + for (int i = 0; i < m; i++) { + if (mstwt < findMST(n, edgesWithIdx, i, -1)) { + critical.push_back(edgesWithIdx[i][3]); + } else if (mstwt == findMST(n, edgesWithIdx, -1, i)) { + pseudoCritical.push_back(edgesWithIdx[i][3]); + } + } + return {critical, pseudoCritical}; + } +}; diff --git a/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.cs b/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.cs new file mode 100644 index 00000000..a5f94f7d --- /dev/null +++ b/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.cs @@ -0,0 +1,60 @@ +public class Solution { + private class UnionFind { + private int[] parent; + public UnionFind(int n) { + parent = new int[n]; + for (int i = 0; i < n; i++) { + parent[i] = i; + } + } + public int FindParent(int p) { + if (parent[p] == p) return p; + parent[p] = FindParent(parent[p]); + return parent[p]; + } + public void Union(int u, int v) { + int pu = FindParent(u); + int pv = FindParent(v); + parent[pu] = pv; + } + } + + private int FindMST(int n, int[][] edges, int block, int e) { + UnionFind uf = new UnionFind(n); + int weight = 0; + if (e != -1) { + weight += edges[e][2]; + uf.Union(edges[e][0], edges[e][1]); + } + for (int i = 0; i < edges.Length; i++) { + if (i == block) continue; + if (uf.FindParent(edges[i][0]) == uf.FindParent(edges[i][1])) continue; + uf.Union(edges[i][0], edges[i][1]); + weight += edges[i][2]; + } + for (int i = 0; i < n; i++) { + if (uf.FindParent(i) != uf.FindParent(0)) return int.MaxValue; + } + return weight; + } + + public IList> FindCriticalAndPseudoCriticalEdges(int n, int[][] edges) { + List critical = new List(); + List pseudoCritical = new List(); + int m = edges.Length; + int[][] edgesWithIdx = new int[m][]; + for (int i = 0; i < m; i++) { + edgesWithIdx[i] = new int[] { edges[i][0], edges[i][1], edges[i][2], i }; + } + Array.Sort(edgesWithIdx, (a, b) => a[2].CompareTo(b[2])); + int mstwt = FindMST(n, edgesWithIdx, -1, -1); + for (int i = 0; i < m; i++) { + if (mstwt < FindMST(n, edgesWithIdx, i, -1)) { + critical.Add(edgesWithIdx[i][3]); + } else if (mstwt == FindMST(n, edgesWithIdx, -1, i)) { + pseudoCritical.Add(edgesWithIdx[i][3]); + } + } + return new List> { critical, pseudoCritical }; + } +} diff --git a/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.dart b/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.dart new file mode 100644 index 00000000..be594977 --- /dev/null +++ b/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.dart @@ -0,0 +1,46 @@ +class UnionFind { + List parent; + UnionFind(int n) : parent = List.generate(n, (i) => i); + int findParent(int p) => parent[p] == p ? p : parent[p] = findParent(parent[p]); + void union(int u, int v) => parent[findParent(u)] = findParent(v); +} + +class Solution { + List> findCriticalAndPseudoCriticalEdges(int n, List> edges) { + + int findMST(int block, int e) { + UnionFind uf = UnionFind(n); + int weight = 0; + if (e != -1) { + weight += edges[e][2]; + uf.union(edges[e][0], edges[e][1]); + } + for (int i = 0; i < edges.length; i++) { + if (i == block) continue; + if (uf.findParent(edges[i][0]) == uf.findParent(edges[i][1])) continue; + uf.union(edges[i][0], edges[i][1]); + weight += edges[i][2]; + } + for (int i = 0; i < n; i++) { + if (uf.findParent(i) != uf.findParent(0)) return 2147483647; + } + return weight; + } + + for (int i = 0; i < edges.length; i++) { + edges[i].add(i); + } + edges.sort((a, b) => a[2].compareTo(b[2])); + int mstwt = findMST(-1, -1); + List critical = []; + List pseudoCritical = []; + for (int i = 0; i < edges.length; i++) { + if (mstwt < findMST(i, -1)) { + critical.add(edges[i][3]); + } else if (mstwt == findMST(-1, i)) { + pseudoCritical.add(edges[i][3]); + } + } + return [critical, pseudoCritical]; + } +} diff --git a/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.go b/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.go new file mode 100644 index 00000000..2b1fa5e5 --- /dev/null +++ b/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.go @@ -0,0 +1,67 @@ +func findCriticalAndPseudoCriticalEdges(n int, edges [][]int) [][]int { + type UnionFind struct { + parent []int + } + newUnionFind := func(n int) *UnionFind { + parent := make([]int, n) + for i := 0; i < n; i++ { + parent[i] = i + } + return &UnionFind{parent} + } + var findParent func(uf *UnionFind, p int) int + findParent = func(uf *UnionFind, p int) int { + if uf.parent[p] == p { + return p + } + uf.parent[p] = findParent(uf, uf.parent[p]) + return uf.parent[p] + } + union := func(uf *UnionFind, u, v int) { + pu, pv := findParent(uf, u), findParent(uf, v) + uf.parent[pu] = pv + } + + findMST := func(block, e int) int { + uf := newUnionFind(n) + weight := 0 + if e != -1 { + weight += edges[e][2] + union(uf, edges[e][0], edges[e][1]) + } + for i := 0; i < len(edges); i++ { + if i == block { + continue + } + if findParent(uf, edges[i][0]) == findParent(uf, edges[i][1]) { + continue + } + union(uf, edges[i][0], edges[i][1]) + weight += edges[i][2] + } + for i := 0; i < n; i++ { + if findParent(uf, i) != findParent(uf, 0) { + return int(^uint(0) >> 1) + } + } + return weight + } + + for i := range edges { + edges[i] = append(edges[i], i) + } + sort.Slice(edges, func(i, j int) bool { + return edges[i][2] < edges[j][2] + }) + mstwt := findMST(-1, -1) + critical := []int{} + pseudoCritical := []int{} + for i := range edges { + if mstwt < findMST(i, -1) { + critical = append(critical, edges[i][3]) + } else if mstwt == findMST(-1, i) { + pseudoCritical = append(pseudoCritical, edges[i][3]) + } + } + return [][]int{critical, pseudoCritical} +} diff --git a/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.java b/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.java new file mode 100644 index 00000000..85d8ce9a --- /dev/null +++ b/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.java @@ -0,0 +1,66 @@ +class Solution { + private class UnionFind { + int[] parent; + UnionFind(int n) { + parent = new int[n]; + for (int i = 0; i < n; i++) { + parent[i] = i; + } + } + int findParent(int p) { + if (parent[p] == p) return p; + parent[p] = findParent(parent[p]); + return parent[p]; + } + void union(int u, int v) { + int pu = findParent(u); + int pv = findParent(v); + parent[pu] = pv; + } + } + + private int findMST(int n, int[][] edges, int block, int e) { + UnionFind uf = new UnionFind(n); + int weight = 0; + if (e != -1) { + weight += edges[e][2]; + uf.union(edges[e][0], edges[e][1]); + } + for (int i = 0; i < edges.length; i++) { + if (i == block) continue; + if (uf.findParent(edges[i][0]) == uf.findParent(edges[i][1])) continue; + uf.union(edges[i][0], edges[i][1]); + weight += edges[i][2]; + } + for (int i = 0; i < n; i++) { + if (uf.findParent(i) != uf.findParent(0)) return Integer.MAX_VALUE; + } + return weight; + } + + public List> findCriticalAndPseudoCriticalEdges(int n, int[][] edges) { + List critical = new ArrayList<>(); + List pseudoCritical = new ArrayList<>(); + int m = edges.length; + int[][] edgesWithIdx = new int[m][4]; + for (int i = 0; i < m; i++) { + edgesWithIdx[i][0] = edges[i][0]; + edgesWithIdx[i][1] = edges[i][1]; + edgesWithIdx[i][2] = edges[i][2]; + edgesWithIdx[i][3] = i; + } + Arrays.sort(edgesWithIdx, (a, b) -> Integer.compare(a[2], b[2])); + int mstwt = findMST(n, edgesWithIdx, -1, -1); + for (int i = 0; i < m; i++) { + if (mstwt < findMST(n, edgesWithIdx, i, -1)) { + critical.add(edgesWithIdx[i][3]); + } else if (mstwt == findMST(n, edgesWithIdx, -1, i)) { + pseudoCritical.add(edgesWithIdx[i][3]); + } + } + List> result = new ArrayList<>(); + result.add(critical); + result.add(pseudoCritical); + return result; + } +} diff --git a/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.kt b/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.kt new file mode 100644 index 00000000..9b7133e9 --- /dev/null +++ b/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.kt @@ -0,0 +1,57 @@ +class Solution { + private class UnionFind(n: Int) { + private val parent = IntArray(n) { it } + fun findParent(p: Int): Int { + if (parent[p] == p) return p + parent[p] = findParent(parent[p]) + return parent[p] + } + fun union(u: Int, v: Int) { + val pu = findParent(u) + val pv = findParent(v) + parent[pu] = pv + } + } + + private fun findMST(n: Int, edges: Array, block: Int, e: Int): Int { + val uf = UnionFind(n) + var weight = 0 + if (e != -1) { + weight += edges[e][2] + uf.union(edges[e][0], edges[e][1]) + } + for (i in edges.indices) { + if (i == block) continue + if (uf.findParent(edges[i][0]) == uf.findParent(edges[i][1])) continue + uf.union(edges[i][0], edges[i][1]) + weight += edges[i][2] + } + for (i in 0 until n) { + if (uf.findParent(i) != uf.findParent(0)) return Int.MAX_VALUE + } + return weight + } + + fun findCriticalAndPseudoCriticalEdges(n: Int, edges: Array): List> { + val critical = mutableListOf() + val pseudoCritical = mutableListOf() + val m = edges.size + val edgesWithIdx = Array(m) { IntArray(4) } + for (i in 0 until m) { + edgesWithIdx[i][0] = edges[i][0] + edgesWithIdx[i][1] = edges[i][1] + edgesWithIdx[i][2] = edges[i][2] + edgesWithIdx[i][3] = i + } + edgesWithIdx.sortBy { it[2] } + val mstwt = findMST(n, edgesWithIdx, -1, -1) + for (i in 0 until m) { + if (mstwt < findMST(n, edgesWithIdx, i, -1)) { + critical.add(edgesWithIdx[i][3]) + } else if (mstwt == findMST(n, edgesWithIdx, -1, i)) { + pseudoCritical.add(edgesWithIdx[i][3]) + } + } + return listOf(critical, pseudoCritical) + } +} diff --git a/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.py b/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.py new file mode 100644 index 00000000..2817d09f --- /dev/null +++ b/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.py @@ -0,0 +1,88 @@ +class UnionFind: + # Constructor to initialize the UnionFind (Disjoint Set) structure + def __init__(self, n): + # Initialize each node to be its own parent (self-loop) + self.parent = list(range(n)) + + # Method to find the root (parent) of a node with path compression + def find_parent(self, p): + # If the node is its own parent, return it + if self.parent[p] == p: + return p + # Path compression: make the parent of p the root of the set + self.parent[p] = self.find_parent(self.parent[p]) + return self.parent[p] + + # Method to unify two nodes by connecting their sets + def union(self, u, v): + # Find the root of u and the root of v + pu, pv = self.find_parent(u), self.find_parent(v) + # Merge the two sets by making one root the parent of the other + self.parent[pu] = pv + + +class Solution: + # A static method to compare two edges based on their weights (used in sorting) + @staticmethod + def cmp(a, b): + return a[2] < b[2] # Compare based on the weight (third element of the edge) + + # Method to find critical and pseudo-critical edges in the Minimum Spanning Tree (MST) + def findCriticalAndPseudoCriticalEdges(self, n, edges): + critical = [] # List to store critical edges + pseudo_critical = [] # List to store pseudo-critical edges + + # Add an index to each edge to track its original position + for i in range(len(edges)): + edges[i].append(i) + + # Sort the edges based on their weights + edges.sort(key=lambda x: x[2]) + + # Find the total weight of the Minimum Spanning Tree (MST) without any exclusions + mstwt = self.find_MST(n, edges, -1, -1) + + # Iterate over all edges to find critical and pseudo-critical ones + for i in range(len(edges)): + # Check if excluding this edge increases the MST weight (i.e., it's critical) + if mstwt < self.find_MST(n, edges, i, -1): + critical.append(edges[i][3]) # Append the index of the critical edge + # Check if including this edge keeps the MST weight the same (i.e., it's pseudo-critical) + elif mstwt == self.find_MST(n, edges, -1, i): + pseudo_critical.append( + edges[i][3] + ) # Append the index of the pseudo-critical edge + + # Return the list of critical and pseudo-critical edges + return [critical, pseudo_critical] + + # Helper method to find the weight of the MST + # 'block' is the edge to exclude, 'e' is the edge to force include + def find_MST(self, n, edges, block, e): + uf = UnionFind(n) # Initialize the UnionFind structure for 'n' nodes + weight = 0 # Initialize the total weight of the MST + + # If 'e' is not -1, include that edge first + if e != -1: + weight += edges[e][2] # Add the weight of the edge 'e' + uf.union(edges[e][0], edges[e][1]) # Union the nodes of edge 'e' + + # Iterate through all edges to build the MST + for i in range(len(edges)): + # Skip the blocked edge + if i == block: + continue + # If the edge forms a cycle, skip it + if uf.find_parent(edges[i][0]) == uf.find_parent(edges[i][1]): + continue + # Otherwise, union the nodes and add the edge weight to the total + uf.union(edges[i][0], edges[i][1]) + weight += edges[i][2] + + # Check if all nodes are connected (i.e., the graph forms a spanning tree) + for i in range(n): + if uf.find_parent(i) != uf.find_parent(0): + return float("inf") # If not all nodes are connected, return infinity + + # Return the total weight of the MST + return weight diff --git a/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.py2 b/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.py2 new file mode 100644 index 00000000..56d8cb82 --- /dev/null +++ b/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.py2 @@ -0,0 +1,49 @@ +class Solution(object): + def findCriticalAndPseudoCriticalEdges(self, n, edges): + """ + :type n: int + :type edges: List[List[int]] + :rtype: List[List[int]] + """ + class UnionFind: + def __init__(self, n): + self.parent = list(range(n)) + def find_parent(self, p): + if self.parent[p] == p: + return p + self.parent[p] = self.find_parent(self.parent[p]) + return self.parent[p] + def union(self, u, v): + pu, pv = self.find_parent(u), self.find_parent(v) + self.parent[pu] = pv + + def find_MST(block, e): + uf = UnionFind(n) + weight = 0 + if e != -1: + weight += edges[e][2] + uf.union(edges[e][0], edges[e][1]) + for i in range(len(edges)): + if i == block: + continue + if uf.find_parent(edges[i][0]) == uf.find_parent(edges[i][1]): + continue + uf.union(edges[i][0], edges[i][1]) + weight += edges[i][2] + for i in range(n): + if uf.find_parent(i) != uf.find_parent(0): + return float('inf') + return weight + + critical = [] + pseudo_critical = [] + for i in range(len(edges)): + edges[i].append(i) + edges.sort(key=lambda x: x[2]) + mstwt = find_MST(-1, -1) + for i in range(len(edges)): + if mstwt < find_MST(i, -1): + critical.append(edges[i][3]) + elif mstwt == find_MST(-1, i): + pseudo_critical.append(edges[i][3]) + return [critical, pseudo_critical] diff --git a/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.rb b/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.rb new file mode 100644 index 00000000..078751fa --- /dev/null +++ b/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.rb @@ -0,0 +1,43 @@ +class UnionFind + def initialize(n); @parent = (0...n).to_a; end + def find_parent(p); @parent[p] == p ? p : @parent[p] = find_parent(@parent[p]); end + def union(u, v); @parent[find_parent(u)] = find_parent(v); end +end + +# @param {Integer} n +# @param {Integer[][]} edges +# @return {Integer[][]} +def find_critical_and_pseudo_critical_edges(n, edges) + def find_mst(n, edges, block, e) + uf = UnionFind.new(n) + weight = 0 + if e != -1 + weight += edges[e][2] + uf.union(edges[e][0], edges[e][1]) + end + edges.each_with_index do |edge, i| + next if i == block + next if uf.find_parent(edge[0]) == uf.find_parent(edge[1]) + uf.union(edge[0], edge[1]) + weight += edge[2] + end + (0...n).each do |i| + return Float::INFINITY if uf.find_parent(i) != uf.find_parent(0) + end + weight + end + + edges.each_with_index { |edge, i| edge << i } + edges.sort_by! { |e| e[2] } + mstwt = find_mst(n, edges, -1, -1) + critical = [] + pseudo_critical = [] + edges.each_with_index do |edge, i| + if mstwt < find_mst(n, edges, i, -1) + critical << edge[3] + elsif mstwt == find_mst(n, edges, -1, i) + pseudo_critical << edge[3] + end + end + [critical, pseudo_critical] +end diff --git a/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.rs b/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.rs new file mode 100644 index 00000000..15324fae --- /dev/null +++ b/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.rs @@ -0,0 +1,67 @@ +impl Solution { + pub fn find_critical_and_pseudo_critical_edges(n: i32, edges: Vec>) -> Vec> { + struct UnionFind { + parent: Vec, + } + impl UnionFind { + fn new(n: usize) -> Self { + UnionFind { parent: (0..n).collect() } + } + fn find_parent(&mut self, p: usize) -> usize { + if self.parent[p] == p { + return p; + } + self.parent[p] = self.find_parent(self.parent[p]); + self.parent[p] + } + fn union(&mut self, u: usize, v: usize) { + let pu = self.find_parent(u); + let pv = self.find_parent(v); + self.parent[pu] = pv; + } + } + + fn find_mst(n: usize, edges: &Vec>, block: i32, e: i32) -> i32 { + let mut uf = UnionFind::new(n); + let mut weight = 0; + if e != -1 { + let e = e as usize; + weight += edges[e][2] as i32; + uf.union(edges[e][0], edges[e][1]); + } + for i in 0..edges.len() { + if i as i32 == block { + continue; + } + if uf.find_parent(edges[i][0]) == uf.find_parent(edges[i][1]) { + continue; + } + uf.union(edges[i][0], edges[i][1]); + weight += edges[i][2] as i32; + } + for i in 0..n { + if uf.find_parent(i) != uf.find_parent(0) { + return i32::MAX; + } + } + weight + } + + let n = n as usize; + let mut edges_with_idx: Vec> = edges.iter().enumerate().map(|(i, e)| { + vec![e[0] as usize, e[1] as usize, e[2] as usize, i] + }).collect(); + edges_with_idx.sort_by(|a, b| a[2].cmp(&b[2])); + let mstwt = find_mst(n, &edges_with_idx, -1, -1); + let mut critical = vec![]; + let mut pseudo_critical = vec![]; + for i in 0..edges_with_idx.len() { + if mstwt < find_mst(n, &edges_with_idx, i as i32, -1) { + critical.push(edges_with_idx[i][3] as i32); + } else if mstwt == find_mst(n, &edges_with_idx, -1, i as i32) { + pseudo_critical.push(edges_with_idx[i][3] as i32); + } + } + vec![critical, pseudo_critical] + } +} diff --git a/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.swift b/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.swift new file mode 100644 index 00000000..e01bc5c8 --- /dev/null +++ b/tests/1001-1500/1489. find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/sol.swift @@ -0,0 +1,57 @@ +class Solution { + class UnionFind { + var parent: [Int] + init(_ n: Int) { + parent = Array(0.. Int { + if parent[p] == p { return p } + parent[p] = findParent(parent[p]) + return parent[p] + } + func union(_ u: Int, _ v: Int) { + let pu = findParent(u) + let pv = findParent(v) + parent[pu] = pv + } + } + + func findMST(_ n: Int, _ edges: [[Int]], _ block: Int, _ e: Int) -> Int { + let uf = UnionFind(n) + var weight = 0 + if e != -1 { + weight += edges[e][2] + uf.union(edges[e][0], edges[e][1]) + } + for i in 0.. [[Int]] { + var edgesWithIdx = edges.enumerated().map { pair in + var edge = pair.element + edge.append(pair.offset) + return edge + } + edgesWithIdx.sort { $0[2] < $1[2] } + let mstwt = findMST(n, edgesWithIdx, -1, -1) + var critical = [Int]() + var pseudoCritical = [Int]() + for i in 0.. i); + } + findParent(p: number): number { + if (this.parent[p] === p) return p; + this.parent[p] = this.findParent(this.parent[p]); + return this.parent[p]; + } + union(u: number, v: number): void { + const pu = this.findParent(u); + const pv = this.findParent(v); + this.parent[pu] = pv; + } + } + + const findMST = (block: number, e: number): number => { + const uf = new UnionFind(n); + let weight = 0; + if (e !== -1) { + weight += edges[e][2]; + uf.union(edges[e][0], edges[e][1]); + } + for (let i = 0; i < edges.length; i++) { + if (i === block) continue; + if (uf.findParent(edges[i][0]) === uf.findParent(edges[i][1])) continue; + uf.union(edges[i][0], edges[i][1]); + weight += edges[i][2]; + } + for (let i = 0; i < n; i++) { + if (uf.findParent(i) !== uf.findParent(0)) return Infinity; + } + return weight; + }; + + for (let i = 0; i < edges.length; i++) { + edges[i].push(i); + } + edges.sort((a, b) => a[2] - b[2]); + const mstwt = findMST(-1, -1); + const critical: number[] = []; + const pseudoCritical: number[] = []; + for (let i = 0; i < edges.length; i++) { + if (mstwt < findMST(i, -1)) { + critical.push(edges[i][3]); + } else if (mstwt === findMST(-1, i)) { + pseudoCritical.push(edges[i][3]); + } + } + return [critical, pseudoCritical]; +} diff --git a/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/manifest.yaml b/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/manifest.yaml new file mode 100644 index 00000000..ac499355 --- /dev/null +++ b/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/manifest.yaml @@ -0,0 +1,227 @@ +entry: + id: 1491 + title: "average-salary-excluding-the-minimum-and-maximum-salary" + params: + salary: + type: array + items: + type: int + call: + cpp: "Solution().average({salary})" + rust: "Solution::average({salary})" + python3: "Solution().average({salary})" + python2: "Solution().average({salary})" + ruby: "average({salary})" + java: "new Solution().average({salary})" + csharp: "new Solution().Average({salary})" + kotlin: "Solution().average({salary})" + go: "average({salary})" + dart: "Solution().average({salary})" + swift: "Solution().average({salary})" + typescript: "average({salary})" +judge: + type: exact +limits: + time_ms: 300 + memory_mb: 300 +oracle: + python3: + call: "Checker().average(salary, {result})" + checker: | + class Checker: + def average(self, salary, result): + if not isinstance(result, (int, float)): + return False + expected = (sum(salary) - min(salary) - max(salary)) / (len(salary) - 2) + return abs(result - expected) <= 1e-5 +seed: 1491 +tests: + - name: ex1 + in: + salary: [4000, 3000, 1000, 2000] + out: 2500.0 + - name: ex2 + in: + salary: [1000, 2000, 3000] + out: 2000.0 + - name: three + in: + salary: [1000, 1500, 2000] + - name: four + in: + salary: [1000, 2000, 3000, 4000] + - name: consecutive + in: + salary: [1000, 1001, 1002, 1003, 1004] + - name: wide + in: + salary: [1000, 5000, 10000, 50000] + - name: odd_average + in: + salary: [1000, 2000, 3001, 4000, 5000] + - name: even_average + in: + salary: [1000, 2001, 3000, 4000] + - name: high_values + in: + salary: [999990, 999991, 999992, 999993] + - name: min_values + in: + salary: [1000, 1001, 1002, 1003] + - name: six_a + in: + salary: [1100, 2200, 3300, 4400, 5500, 6600] + - name: six_b + in: + salary: [1000, 2345, 3456, 4567, 5678, 6789] + - name: seven_a + in: + salary: [1000, 1200, 1400, 1600, 1800, 2000, 2200] + - name: seven_b + in: + salary: [1111, 2222, 3333, 4444, 5555, 6666, 7777] + - name: eight_a + in: + salary: [1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700] + - name: eight_b + in: + salary: [2000, 3001, 4002, 5003, 6004, 7005, 8006, 9007] + - name: mixed_a + in: + salary: [1000, 1234, 2345, 3456, 4567] + - name: mixed_b + in: + salary: [1500, 2700, 3900, 5100, 6300] + - name: mixed_c + in: + salary: [1000, 2500, 5000, 7500, 10000, 12500] + - name: mixed_d + in: + salary: [1001, 2003, 3007, 4011, 5013] + - name: mixed_e + in: + salary: [9999, 19999, 29999, 39999, 49999] + - name: nine_a + in: + salary: [1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000] + - name: nine_b + in: + salary: [1234, 2345, 3456, 4567, 5678, 6789, 7890, 8901, 9900] + - name: ten_a + in: + salary: [1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700, 1800, 1900] + - name: ten_b + in: + salary: [5000, 6000, 7000, 8000, 9000, 10000, 11000, 12000, 13000, 14000] + - name: fractions_a + in: + salary: [1000, 1001, 1004, 1007, 1010] + - name: fractions_b + in: + salary: [2000, 2002, 2005, 2009] + - name: fractions_c + in: + salary: [3000, 3001, 3005, 3010, 3011, 3017] + - name: high_spread + in: + salary: [1000, 100000, 250000, 500000, 999999] + - name: close_high + in: + salary: [999900, 999901, 999902, 999903, 999904] + - name: eleven + in: + salary: [1000, 1111, 1222, 1333, 1444, 1555, 1666, 1777, 1888, 1999, 2110] + - name: twelve + in: + salary: + [1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000, 5500, 6000, 6500] + - name: fourteen + in: + salary: + [ + 1000, + 1100, + 1200, + 1300, + 1400, + 1500, + 1600, + 1700, + 1800, + 1900, + 2000, + 2100, + 2200, + 2300, + ] + - name: final_a + in: + salary: [1000, 3456, 7890, 12345, 67890] + - name: final_b + in: + salary: [2100, 3210, 4320, 5430, 6540, 7650] + - name: generated_min_length + seed: 149101 + in: + salary: + gen: array + len: 3 + of: + gen: int + min: 1000 + max: 1000000 + distinct: true + sorted: false + elemType: int + - name: generated_max_length_a + seed: 149102 + in: + salary: + gen: array + len: 100 + of: + gen: int + min: 1000 + max: 1000000 + distinct: true + sorted: false + elemType: int + - name: generated_max_length_b + seed: 149103 + in: + salary: + gen: array + len: 100 + of: + gen: int + min: 1000 + max: 1000000 + distinct: true + sorted: false + elemType: int + - name: generated_mid_length + seed: 149104 + in: + salary: + gen: array + len: 57 + of: + gen: int + min: 1000 + max: 1000000 + distinct: true + sorted: false + elemType: int + - name: generated_boundary_length + seed: 149105 + in: + salary: + gen: array + len: 99 + of: + gen: int + min: 1000 + max: 1000000 + distinct: true + sorted: false + elemType: int diff --git a/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.cpp b/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.cpp new file mode 100644 index 00000000..6857d4b8 --- /dev/null +++ b/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + double average(vector& salary) { + int max_val = *max_element(salary.begin(), salary.end()); + int min_val = *min_element(salary.begin(), salary.end()); + double total = 0.0; + int count = 0; + for (int s : salary) { + if (s != max_val && s != min_val) { + total += s; + count++; + } + } + return total / count; + } +}; diff --git a/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.cs b/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.cs new file mode 100644 index 00000000..f185bb29 --- /dev/null +++ b/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.cs @@ -0,0 +1,19 @@ +public class Solution { + public double Average(int[] salary) { + int max = salary[0]; + int min = salary[0]; + foreach (int s in salary) { + if (s > max) max = s; + if (s < min) min = s; + } + double total = 0.0; + int count = 0; + foreach (int s in salary) { + if (s != max && s != min) { + total += s; + count++; + } + } + return total / count; + } +} diff --git a/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.dart b/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.dart new file mode 100644 index 00000000..41264d31 --- /dev/null +++ b/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.dart @@ -0,0 +1,19 @@ +class Solution { + double average(List salary) { + int max = salary[0]; + int min = salary[0]; + for (int s in salary) { + if (s > max) max = s; + if (s < min) min = s; + } + double total = 0.0; + int count = 0; + for (int s in salary) { + if (s != max && s != min) { + total += s; + count++; + } + } + return total / count; + } +} diff --git a/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.go b/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.go new file mode 100644 index 00000000..01798562 --- /dev/null +++ b/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.go @@ -0,0 +1,21 @@ +func average(salary []int) float64 { + max := salary[0] + min := salary[0] + for _, s := range salary { + if s > max { + max = s + } + if s < min { + min = s + } + } + total := 0.0 + count := 0 + for _, s := range salary { + if s != max && s != min { + total += float64(s) + count++ + } + } + return total / float64(count) +} diff --git a/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.java b/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.java new file mode 100644 index 00000000..229a3394 --- /dev/null +++ b/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.java @@ -0,0 +1,19 @@ +class Solution { + public double average(int[] salary) { + int max = salary[0]; + int min = salary[0]; + for (int s : salary) { + if (s > max) max = s; + if (s < min) min = s; + } + double total = 0.0; + int count = 0; + for (int s : salary) { + if (s != max && s != min) { + total += s; + count++; + } + } + return total / count; + } +} diff --git a/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.kt b/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.kt new file mode 100644 index 00000000..00e44b66 --- /dev/null +++ b/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.kt @@ -0,0 +1,15 @@ +class Solution { + fun average(salary: IntArray): Double { + val max = salary.max() + val min = salary.min() + var total = 0.0 + var count = 0 + for (s in salary) { + if (s != max && s != min) { + total += s + count++ + } + } + return total / count + } +} diff --git a/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.py b/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.py new file mode 100644 index 00000000..534bb1d4 --- /dev/null +++ b/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.py @@ -0,0 +1,12 @@ +class Solution: + def average(self, salary: List[int]) -> float: + res = max(salary) + res1 = min(salary) + salary.remove(res) + salary.remove(res1) + Total = 0.00000 + for i in salary: + Total = Total + i + + M = Total / len(salary) + return M diff --git a/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.py2 b/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.py2 new file mode 100644 index 00000000..479074ef --- /dev/null +++ b/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def average(self, salary): + """ + :type salary: List[int] + :rtype: float + """ + res = max(salary) + res1 = min(salary) + salary.remove(res) + salary.remove(res1) + Total = 0.00000 + for i in salary: + Total = Total + i + + M = Total / len(salary) + return M diff --git a/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.rb b/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.rb new file mode 100644 index 00000000..bc8a60a6 --- /dev/null +++ b/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.rb @@ -0,0 +1,14 @@ +# @param {Integer[]} salary +# @return {Float} +def average(salary) + res = salary.max + res1 = salary.min + salary.delete(res) + salary.delete(res1) + total = 0.0 + salary.each do |i| + total = total + i + end + m = total / salary.length + return m +end diff --git a/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.rs b/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.rs new file mode 100644 index 00000000..c5ec7867 --- /dev/null +++ b/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn average(salary: Vec) -> f64 { + let max = *salary.iter().max().unwrap(); + let min = *salary.iter().min().unwrap(); + let mut total = 0.0; + let mut count = 0; + for &s in &salary { + if s != max && s != min { + total += s as f64; + count += 1; + } + } + total / count as f64 + } +} diff --git a/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.swift b/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.swift new file mode 100644 index 00000000..adaa64e6 --- /dev/null +++ b/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.swift @@ -0,0 +1,15 @@ +class Solution { + func average(_ salary: [Int]) -> Double { + let max = salary.max()! + let min = salary.min()! + var total = 0.0 + var count = 0 + for s in salary { + if s != max && s != min { + total += Double(s) + count += 1 + } + } + return total / Double(count) + } +} diff --git a/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.ts b/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.ts new file mode 100644 index 00000000..216bf33d --- /dev/null +++ b/tests/1001-1500/1491. average-salary-excluding-the-minimum-and-maximum-salary/sol.ts @@ -0,0 +1,13 @@ +function average(salary: number[]): number { + const max = Math.max(...salary); + const min = Math.min(...salary); + let total = 0.0; + let count = 0; + for (const s of salary) { + if (s !== max && s !== min) { + total += s; + count++; + } + } + return total / count; +} diff --git a/tests/1001-1500/1492. the-kth-factor-of-n/manifest.yaml b/tests/1001-1500/1492. the-kth-factor-of-n/manifest.yaml new file mode 100644 index 00000000..761e1928 --- /dev/null +++ b/tests/1001-1500/1492. the-kth-factor-of-n/manifest.yaml @@ -0,0 +1,266 @@ +entry: + id: 1492 + title: "the-kth-factor-of-n" + params: + n: + type: int + k: + type: int + call: + cpp: "Solution().kthFactor({n}, {k})" + rust: "Solution::kth_factor({n}, {k})" + python3: "Solution().kthFactor({n}, {k})" + python2: "Solution().kthFactor({n}, {k})" + ruby: "kth_factor({n}, {k})" + java: "new Solution().kthFactor({n}, {k})" + csharp: "new Solution().KthFactor({n}, {k})" + kotlin: "Solution().kthFactor({n}, {k})" + go: "kthFactor({n}, {k})" + dart: "Solution().kthFactor({n}, {k})" + swift: "Solution().kthFactor({n}, {k})" + typescript: "kthFactor({n}, {k})" +judge: + type: exact +limits: + time_ms: 300 + memory_mb: 300 +oracle: + python3: + call: "Checker().kthFactor(n, k, {result})" + checker: | + class Checker: + def kthFactor(self, n, k, result): + factors = [i for i in range(1, n+1) if n % i == 0] + return result == (factors[k-1] if k <= len(factors) else -1) +seed: 1492 +tests: + - name: ex1 + in: + n: 12 + k: 3 + out: 3 + - name: ex2 + in: + n: 7 + k: 2 + out: 7 + - name: ex3 + in: + n: 4 + k: 4 + out: -1 + - name: one_first + in: + n: 1 + k: 1 + out: 1 + - name: prime_first + in: + n: 13 + k: 1 + out: 1 + - name: prime_second + in: + n: 13 + k: 2 + out: 13 + - name: square + in: + n: 16 + k: 4 + out: 8 + - name: power_two + in: + n: 32 + k: 3 + out: 4 + - name: highly_composite + in: + n: 360 + k: 12 + out: 18 + - name: k_one + in: + n: 1000 + k: 1 + out: 1 + - name: k_n + in: + n: 1000 + k: 1000 + out: -1 + - name: no_k + in: + n: 100 + k: 20 + out: -1 + - name: three_factors + in: + n: 49 + k: 3 + out: 49 + - name: even_n + in: + n: 24 + k: 5 + out: 6 + - name: odd_n + in: + n: 45 + k: 6 + out: 45 + - name: composite_a + in: + n: 18 + k: 5 + out: 9 + - name: composite_b + in: + n: 25 + k: 4 + out: -1 + - name: composite_c + in: + n: 27 + k: 6 + out: -1 + - name: composite_d + in: + n: 64 + k: 7 + out: 64 + - name: composite_e + in: + n: 81 + k: 5 + out: 81 + - name: composite_f + in: + n: 100 + k: 9 + out: 100 + - name: boundary_a + in: + n: 999 + k: 2 + out: 3 + - name: boundary_b + in: + n: 997 + k: 2 + out: 997 + - name: boundary_c + in: + n: 512 + k: 10 + out: 512 + - name: boundary_d + in: + n: 729 + k: 8 + out: -1 + - name: factor_position_a + in: + n: 48 + k: 8 + out: 16 + - name: factor_position_b + in: + n: 72 + k: 10 + out: 24 + - name: factor_position_c + in: + n: 96 + k: 12 + out: 96 + - name: final_a + in: + n: 840 + k: 16 + out: 28 + - name: final_b + in: + n: 999 + k: 4 + out: 27 + - name: max_composite_last + in: + n: 1000 + k: 16 + out: 1000 + - name: max_prime_missing + in: + n: 997 + k: 997 + out: -1 + - name: large_odd_middle + in: + n: 999 + k: 6 + out: 111 + - name: large_square_last + in: + n: 961 + k: 3 + out: 961 + - name: many_divisors_position + in: + n: 720 + k: 20 + out: 48 + - name: generated_large_low_k + seed: 149201 + in: + n: + gen: "int" + min: 900 + max: 1000 + k: + gen: "int" + min: 1 + max: 900 + - name: generated_large_mid_k + seed: 149202 + in: + n: + gen: "int" + min: 950 + max: 1000 + k: + gen: "int" + min: 300 + max: 950 + - name: generated_large_high_k + seed: 149203 + in: + n: + gen: "int" + min: 980 + max: 1000 + k: + gen: "int" + min: 700 + max: 980 + - name: generated_max_n + seed: 149204 + in: + n: + gen: "int" + min: 1000 + max: 1000 + k: + gen: "int" + min: 1 + max: 1000 + - name: generated_large_tail + seed: 149205 + in: + n: + gen: "int" + min: 990 + max: 1000 + k: + gen: "int" + min: 900 + max: 990 diff --git a/tests/1001-1500/1492. the-kth-factor-of-n/sol.cpp b/tests/1001-1500/1492. the-kth-factor-of-n/sol.cpp new file mode 100644 index 00000000..5e2d4807 --- /dev/null +++ b/tests/1001-1500/1492. the-kth-factor-of-n/sol.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int kthFactor(int n, int k) { + vector ab; + for (int i = 1; i <= n; i++) { + if (n % i == 0) { + ab.push_back(i); + } + } + if (ab.size() < k) { + return -1; + } else { + return ab[k - 1]; + } + } +}; diff --git a/tests/1001-1500/1492. the-kth-factor-of-n/sol.cs b/tests/1001-1500/1492. the-kth-factor-of-n/sol.cs new file mode 100644 index 00000000..7acc1bc2 --- /dev/null +++ b/tests/1001-1500/1492. the-kth-factor-of-n/sol.cs @@ -0,0 +1,15 @@ +public class Solution { + public int KthFactor(int n, int k) { + var ab = new System.Collections.Generic.List(); + for (int i = 1; i <= n; i++) { + if (n % i == 0) { + ab.Add(i); + } + } + if (ab.Count < k) { + return -1; + } else { + return ab[k - 1]; + } + } +} diff --git a/tests/1001-1500/1492. the-kth-factor-of-n/sol.dart b/tests/1001-1500/1492. the-kth-factor-of-n/sol.dart new file mode 100644 index 00000000..d3069781 --- /dev/null +++ b/tests/1001-1500/1492. the-kth-factor-of-n/sol.dart @@ -0,0 +1,15 @@ +class Solution { + int kthFactor(int n, int k) { + List ab = []; + for (int i = 1; i <= n; i++) { + if (n % i == 0) { + ab.add(i); + } + } + if (ab.length < k) { + return -1; + } else { + return ab[k - 1]; + } + } +} diff --git a/tests/1001-1500/1492. the-kth-factor-of-n/sol.go b/tests/1001-1500/1492. the-kth-factor-of-n/sol.go new file mode 100644 index 00000000..e20b9c41 --- /dev/null +++ b/tests/1001-1500/1492. the-kth-factor-of-n/sol.go @@ -0,0 +1,12 @@ +func kthFactor(n int, k int) int { + ab := []int{} + for i := 1; i <= n; i++ { + if n % i == 0 { + ab = append(ab, i) + } + } + if len(ab) < k { + return -1 + } + return ab[k-1] +} diff --git a/tests/1001-1500/1492. the-kth-factor-of-n/sol.java b/tests/1001-1500/1492. the-kth-factor-of-n/sol.java new file mode 100644 index 00000000..f0296aaf --- /dev/null +++ b/tests/1001-1500/1492. the-kth-factor-of-n/sol.java @@ -0,0 +1,15 @@ +class Solution { + public int kthFactor(int n, int k) { + java.util.ArrayList ab = new java.util.ArrayList<>(); + for (int i = 1; i <= n; i++) { + if (n % i == 0) { + ab.add(i); + } + } + if (ab.size() < k) { + return -1; + } else { + return ab.get(k - 1); + } + } +} diff --git a/tests/1001-1500/1492. the-kth-factor-of-n/sol.kt b/tests/1001-1500/1492. the-kth-factor-of-n/sol.kt new file mode 100644 index 00000000..a4d65410 --- /dev/null +++ b/tests/1001-1500/1492. the-kth-factor-of-n/sol.kt @@ -0,0 +1,11 @@ +class Solution { + fun kthFactor(n: Int, k: Int): Int { + val ab = mutableListOf() + for (i in 1..n) { + if (n % i == 0) { + ab.add(i) + } + } + return if (ab.size < k) -1 else ab[k - 1] + } +} diff --git a/tests/1001-1500/1492. the-kth-factor-of-n/sol.py b/tests/1001-1500/1492. the-kth-factor-of-n/sol.py new file mode 100644 index 00000000..186d79a7 --- /dev/null +++ b/tests/1001-1500/1492. the-kth-factor-of-n/sol.py @@ -0,0 +1,12 @@ +class Solution: + def kthFactor(self, n: int, k: int) -> int: + ab = [] + for i in range(1, n + 1): + if n % i == 0: + ab.append(i) + else: + continue + if len(ab) < k: + return -1 + else: + return ab[k - 1] diff --git a/tests/1001-1500/1492. the-kth-factor-of-n/sol.py2 b/tests/1001-1500/1492. the-kth-factor-of-n/sol.py2 new file mode 100644 index 00000000..c86d7061 --- /dev/null +++ b/tests/1001-1500/1492. the-kth-factor-of-n/sol.py2 @@ -0,0 +1,15 @@ +class Solution(object): + def kthFactor(self, n, k): + """ + :type n: int + :type k: int + :rtype: int + """ + ab = [] + for i in range(1, n + 1): + if n % i == 0: + ab.append(i) + if len(ab) < k: + return -1 + else: + return ab[k - 1] diff --git a/tests/1001-1500/1492. the-kth-factor-of-n/sol.rb b/tests/1001-1500/1492. the-kth-factor-of-n/sol.rb new file mode 100644 index 00000000..98c9a7d8 --- /dev/null +++ b/tests/1001-1500/1492. the-kth-factor-of-n/sol.rb @@ -0,0 +1,11 @@ +# @param {Integer} n +# @param {Integer} k +# @return {Integer} +def kth_factor(n, k) + ab = [] + (1..n).each do |i| + ab << i if n % i == 0 + end + return -1 if ab.length < k + ab[k - 1] +end diff --git a/tests/1001-1500/1492. the-kth-factor-of-n/sol.rs b/tests/1001-1500/1492. the-kth-factor-of-n/sol.rs new file mode 100644 index 00000000..00412ec7 --- /dev/null +++ b/tests/1001-1500/1492. the-kth-factor-of-n/sol.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn kth_factor(n: i32, k: i32) -> i32 { + let mut ab = Vec::new(); + for i in 1..=n { + if n % i == 0 { + ab.push(i); + } + } + if (ab.len() as i32) < k { + -1 + } else { + ab[(k - 1) as usize] + } + } +} diff --git a/tests/1001-1500/1492. the-kth-factor-of-n/sol.swift b/tests/1001-1500/1492. the-kth-factor-of-n/sol.swift new file mode 100644 index 00000000..50fe3cdb --- /dev/null +++ b/tests/1001-1500/1492. the-kth-factor-of-n/sol.swift @@ -0,0 +1,15 @@ +class Solution { + func kthFactor(_ n: Int, _ k: Int) -> Int { + var ab: [Int] = [] + for i in 1...n { + if n % i == 0 { + ab.append(i) + } + } + if ab.count < k { + return -1 + } else { + return ab[k - 1] + } + } +} diff --git a/tests/1001-1500/1492. the-kth-factor-of-n/sol.ts b/tests/1001-1500/1492. the-kth-factor-of-n/sol.ts new file mode 100644 index 00000000..d197c52a --- /dev/null +++ b/tests/1001-1500/1492. the-kth-factor-of-n/sol.ts @@ -0,0 +1,13 @@ +function kthFactor(n: number, k: number): number { + const ab: number[] = []; + for (let i = 1; i <= n; i++) { + if (n % i === 0) { + ab.push(i); + } + } + if (ab.length < k) { + return -1; + } else { + return ab[k - 1]; + } +} diff --git a/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/manifest.yaml b/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/manifest.yaml new file mode 100644 index 00000000..353f6cc4 --- /dev/null +++ b/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/manifest.yaml @@ -0,0 +1,269 @@ +entry: + id: 1493 + title: "longest-subarray-of-1s-after-deleting-one-element" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().longestSubarray({nums})" + rust: "Solution::longest_subarray({nums})" + python3: "Solution().longestSubarray({nums})" + python2: "Solution().longestSubarray({nums})" + ruby: "longest_subarray({nums})" + java: "new Solution().longestSubarray({nums})" + csharp: "new Solution().LongestSubarray({nums})" + kotlin: "Solution().longestSubarray({nums})" + go: "longestSubarray({nums})" + dart: "Solution().longestSubarray({nums})" + swift: "Solution().longestSubarray({nums})" + typescript: "longestSubarray({nums})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().longestSubarray(nums, {result})" + checker: | + class Checker: + def longestSubarray(self, nums, result): + runs = [] + index = 0 + while index < len(nums): + if nums[index] == 1: + start = index + while index < len(nums) and nums[index] == 1: + index += 1 + runs.append((start, index - start)) + else: + index += 1 + + if not runs: + expected = 0 + elif len(runs) == 1 and runs[0][0] == 0 and runs[0][1] == len(nums): + expected = len(nums) - 1 + else: + expected = max(length for _, length in runs) + for (left_start, left_length), (right_start, right_length) in zip(runs, runs[1:]): + if right_start == left_start + left_length + 1: + expected = max(expected, left_length + right_length) + return result == expected + +seed: 1493 + +tests: + - name: "example-one" + in: + nums: [1, 1, 0, 1] + out: 3 + - name: "example-two" + in: + nums: [0, 1, 1, 1, 0, 1, 1, 0, 1] + out: 5 + - name: "example-three" + in: + nums: [1, 1, 1] + out: 2 + - name: "single-one" + in: + nums: [1] + - name: "single-zero" + in: + nums: [0] + - name: "two-ones" + in: + nums: [1, 1] + - name: "two-zeros" + in: + nums: [0, 0] + - name: "one-one-one-zero" + in: + nums: [1, 1, 1, 0] + - name: "zero-one-one-one" + in: + nums: [0, 1, 1, 1] + - name: "zero-between-runs" + in: + nums: [1, 1, 0, 1, 1] + - name: "two-zeros-between" + in: + nums: [1, 1, 0, 0, 1, 1] + - name: "all-zeros" + in: + nums: [0, 0, 0, 0, 0] + - name: "all-ones-five" + in: + nums: [1, 1, 1, 1, 1] + - name: "alternating-six" + in: + nums: [1, 0, 1, 0, 1, 0] + - name: "alternating-start-zero" + in: + nums: [0, 1, 0, 1, 0, 1, 0] + - name: "long-left-run" + in: + nums: [1, 1, 1, 1, 0, 1] + - name: "long-right-run" + in: + nums: [1, 0, 1, 1, 1, 1] + - name: "middle-run-wins" + in: + nums: [0, 1, 1, 0, 1, 1, 1, 0] + - name: "equal-runs" + in: + nums: [1, 1, 0, 1, 1, 0, 1, 1] + - name: "single-zero-long" + in: + nums: [1, 1, 1, 1, 1, 0, 1, 1, 1] + - name: "zeros-at-ends" + in: + nums: [0, 1, 1, 1, 1, 0] + - name: "short-runs" + in: + nums: [1, 0, 1, 1, 0, 1, 1, 1, 0, 1] + - name: "mostly-ones" + in: + nums: [1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1] + - name: "mostly-zeros" + in: + nums: [0, 0, 1, 0, 0, 1, 0, 0, 0] + - name: "nine-alternating" + in: + nums: [1, 0, 1, 0, 1, 0, 1, 0, 1] + - name: "ten-ones-then-zero" + in: + nums: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0] + - name: "zero-then-ten-ones" + in: + nums: [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - name: "two-long-runs" + in: + nums: [1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0] + - name: "late-single-zero" + in: + nums: [1, 1, 1, 1, 1, 1, 1, 0] + - name: "early-single-zero" + in: + nums: [0, 1, 1, 1, 1, 1, 1, 1] + - name: "twenty-pattern" + in: + nums: [1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1] + - name: "thirty-pattern" + in: + nums: + [ + 0, + 1, + 1, + 1, + 0, + 1, + 1, + 0, + 1, + 1, + 1, + 1, + 1, + 0, + 1, + 1, + 0, + 1, + 1, + 1, + 0, + 0, + 1, + 1, + 1, + 1, + 0, + 1, + 1, + 1, + ] + - name: "large-generated-binary" + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 0 + max: 1 + distinct: false + sorted: false + elemType: "int" + - name: "large-generated-unary" + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 1 + distinct: false + sorted: false + elemType: "int" + - name: "single-zero-in-balanced-runs" + in: + nums: [1, 1, 1, 0, 1, 1, 1, 1] + - name: "two-zero-gap-with-long-runs" + in: + nums: [1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1] + - name: "isolated-one-among-zeros" + in: + nums: [0, 0, 0, 1, 0, 0, 0] + - name: "generated-small-binary" + seed: 14931 + in: + nums: + gen: "array" + len: + gen: "int" + min: 1 + max: 25 + of: + gen: "int" + min: 0 + max: 1 + distinct: false + sorted: false + elemType: "int" + - name: "generated-medium-binary" + seed: 14932 + in: + nums: + gen: "array" + len: + gen: "int" + min: 500 + max: 2000 + of: + gen: "int" + min: 0 + max: 1 + distinct: false + sorted: false + elemType: "int" + - name: "generated-one-heavy-binary" + seed: 14933 + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 0 + max: 1 + distinct: false + sorted: false + elemType: "int" diff --git a/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.cpp b/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.cpp new file mode 100644 index 00000000..39cf0547 --- /dev/null +++ b/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int longestSubarray(vector& nums) { + int left = 0, zeros = 0, res = 0; + for (int right = 0; right < nums.size(); right++) { + if (nums[right] == 0) zeros++; + while (zeros > 1) { + if (nums[left] == 0) zeros--; + left++; + } + res = max(res, right - left); + } + return res; + } +}; diff --git a/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.cs b/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.cs new file mode 100644 index 00000000..693f0783 --- /dev/null +++ b/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.cs @@ -0,0 +1,14 @@ +public class Solution { + public int LongestSubarray(int[] nums) { + int left = 0, zeros = 0, res = 0; + for (int right = 0; right < nums.Length; right++) { + if (nums[right] == 0) zeros++; + while (zeros > 1) { + if (nums[left] == 0) zeros--; + left++; + } + res = Math.Max(res, right - left); + } + return res; + } +} diff --git a/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.dart b/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.dart new file mode 100644 index 00000000..bc660c79 --- /dev/null +++ b/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.dart @@ -0,0 +1,14 @@ +class Solution { + int longestSubarray(List nums) { + int left = 0, zeros = 0, res = 0; + for (int right = 0; right < nums.length; right++) { + if (nums[right] == 0) zeros++; + while (zeros > 1) { + if (nums[left] == 0) zeros--; + left++; + } + if (right - left > res) res = right - left; + } + return res; + } +} diff --git a/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.go b/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.go new file mode 100644 index 00000000..56f0412a --- /dev/null +++ b/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.go @@ -0,0 +1,18 @@ +func longestSubarray(nums []int) int { + left, zeros, res := 0, 0, 0 + for right := 0; right < len(nums); right++ { + if nums[right] == 0 { + zeros++ + } + for zeros > 1 { + if nums[left] == 0 { + zeros-- + } + left++ + } + if right-left > res { + res = right - left + } + } + return res +} diff --git a/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.java b/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.java new file mode 100644 index 00000000..d7fb97aa --- /dev/null +++ b/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.java @@ -0,0 +1,18 @@ +class Solution { + public int longestSubarray(int[] nums) { + int left = 0, zeros = 0, res = 0; + for (int right = 0; right < nums.length; right++) { + if (nums[right] == 0) { + zeros++; + } + while (zeros > 1) { + if (nums[left] == 0) { + zeros--; + } + left++; + } + res = Math.max(res, right - left); + } + return res; + } +} diff --git a/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.kt b/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.kt new file mode 100644 index 00000000..5e23ca60 --- /dev/null +++ b/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun longestSubarray(nums: IntArray): Int { + var left = 0 + var zeros = 0 + var res = 0 + for (right in nums.indices) { + if (nums[right] == 0) zeros++ + while (zeros > 1) { + if (nums[left] == 0) zeros-- + left++ + } + res = maxOf(res, right - left) + } + return res + } +} diff --git a/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.py b/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.py new file mode 100644 index 00000000..ea38d6fc --- /dev/null +++ b/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.py @@ -0,0 +1,19 @@ +from typing import List + + +class Solution: + def longestSubarray(self, nums: List[int]) -> int: + left, zeros, res = 0, 0, 0 + + for right in range(len(nums)): + if nums[right] == 0: + zeros += 1 + + while zeros > 1: + if nums[left] == 0: + zeros -= 1 + left += 1 + + res = max(res, right - left) + + return res diff --git a/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.py2 b/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.py2 new file mode 100644 index 00000000..4d0ecd51 --- /dev/null +++ b/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def longestSubarray(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + left, zeros, res = 0, 0, 0 + for right in range(len(nums)): + if nums[right] == 0: + zeros += 1 + while zeros > 1: + if nums[left] == 0: + zeros -= 1 + left += 1 + res = max(res, right - left) + return res diff --git a/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.rb b/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.rb new file mode 100644 index 00000000..52e99973 --- /dev/null +++ b/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.rb @@ -0,0 +1,16 @@ +# @param {Integer[]} nums +# @return {Integer} +def longest_subarray(nums) + left = 0 + zeros = 0 + res = 0 + (0...nums.length).each do |right| + zeros += 1 if nums[right] == 0 + while zeros > 1 + zeros -= 1 if nums[left] == 0 + left += 1 + end + res = [res, right - left].max + end + res +end diff --git a/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.rs b/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.rs new file mode 100644 index 00000000..428157e9 --- /dev/null +++ b/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.rs @@ -0,0 +1,20 @@ +impl Solution { + pub fn longest_subarray(nums: Vec) -> i32 { + let mut left = 0; + let mut zeros = 0; + let mut res = 0; + for right in 0..nums.len() { + if nums[right] == 0 { + zeros += 1; + } + while zeros > 1 { + if nums[left] == 0 { + zeros -= 1; + } + left += 1; + } + res = res.max((right - left) as i32); + } + res + } +} diff --git a/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.swift b/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.swift new file mode 100644 index 00000000..d3cb85ae --- /dev/null +++ b/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.swift @@ -0,0 +1,18 @@ +class Solution { + func longestSubarray(_ nums: [Int]) -> Int { + var left = 0, zeros = 0, res = 0 + for right in 0.. 1 { + if nums[left] == 0 { + zeros -= 1 + } + left += 1 + } + res = max(res, right - left) + } + return res + } +} diff --git a/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.ts b/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.ts new file mode 100644 index 00000000..cb0b04a3 --- /dev/null +++ b/tests/1001-1500/1493. longest-subarray-of-1s-after-deleting-one-element/sol.ts @@ -0,0 +1,14 @@ +function longestSubarray(nums: number[]): number { + let left = 0, + zeros = 0, + res = 0; + for (let right = 0; right < nums.length; right++) { + if (nums[right] === 0) zeros++; + while (zeros > 1) { + if (nums[left] === 0) zeros--; + left++; + } + res = Math.max(res, right - left); + } + return res; +} diff --git a/tests/1001-1500/1494. parallel-courses-ii/manifest.yaml b/tests/1001-1500/1494. parallel-courses-ii/manifest.yaml new file mode 100644 index 00000000..c1714838 --- /dev/null +++ b/tests/1001-1500/1494. parallel-courses-ii/manifest.yaml @@ -0,0 +1,702 @@ +entry: + id: 1494 + title: "parallel-courses-ii" + params: + n: + type: int + relations: + type: array + items: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().minNumberOfSemesters({n}, {relations}, {k})" + rust: "Solution::min_number_of_semesters({n}, {relations}, {k})" + python3: "Solution().minNumberOfSemesters({n}, {relations}, {k})" + python2: "Solution().minNumberOfSemesters({n}, {relations}, {k})" + ruby: "min_number_of_semesters({n}, {relations}, {k})" + java: "new Solution().minNumberOfSemesters({n}, {relations}, {k})" + csharp: "new Solution().MinNumberOfSemesters({n}, {relations}, {k})" + kotlin: "Solution().minNumberOfSemesters({n}, {relations}, {k})" + go: "minNumberOfSemesters({n}, {relations}, {k})" + dart: "Solution().minNumberOfSemesters({n}, {relations}, {k})" + swift: "Solution().minNumberOfSemesters({n}, {relations}, {k})" + typescript: "minNumberOfSemesters({n}, {relations}, {k})" +judge: + type: "exact" +limits: + time_ms: 1200 + memory_mb: 300 +oracle: + python3: + call: "Checker().minNumberOfSemesters(n, relations, k, {result})" + checker: | + class Checker: + def minNumberOfSemesters(self, n, relations, k, result): + prerequisites = [0] * n + for before, after in relations: + prerequisites[after - 1] |= 1 << (before - 1) + full = (1 << n) - 1 + memo = {} + def solve(done): + if done == full: + return 0 + if done in memo: + return memo[done] + available = 0 + for course in range(n): + bit = 1 << course + if not done & bit and prerequisites[course] & ~done == 0: + available |= bit + choices = [] + sub = available + while sub: + if sub.bit_count() <= k: + choices.append(sub) + sub = (sub - 1) & available + best = 10 ** 9 + for choice in choices: + best = min(best, 1 + solve(done | choice)) + memo[done] = best + return best + return result == solve(0) +seed: 1494 +tests: + - name: "official-one" + in: + n: 4 + relations: + - [2, 1] + - [3, 1] + - [1, 4] + k: 2 + out: 3 + - name: "official-two" + in: + n: 5 + relations: + - [2, 1] + - [3, 1] + - [4, 1] + - [1, 5] + k: 2 + out: 4 + - name: "single-course" + in: + n: 1 + relations: [] + k: 1 + out: 1 + - name: "two-independent" + in: + n: 2 + relations: [] + k: 1 + - name: "two-independent-all" + in: + n: 2 + relations: [] + k: 2 + - name: "two-chain" + in: + n: 2 + relations: + - [1, 2] + k: 2 + - name: "long-chain-k-one" + in: + n: 6 + relations: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + k: 1 + - name: "long-chain-wide-k" + in: + n: 6 + relations: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + k: 6 + - name: "all-independent-three" + in: + n: 6 + relations: [] + k: 3 + - name: "all-independent-five" + in: + n: 7 + relations: [] + k: 5 + - name: "fork" + in: + n: 5 + relations: + - [1, 2] + - [1, 3] + - [1, 4] + k: 2 + - name: "join" + in: + n: 5 + relations: + - [1, 5] + - [2, 5] + - [3, 5] + - [4, 5] + k: 2 + - name: "diamond" + in: + n: 4 + relations: + - [1, 2] + - [1, 3] + - [2, 4] + - [3, 4] + k: 2 + - name: "diamond-k-one" + in: + n: 4 + relations: + - [1, 2] + - [1, 3] + - [2, 4] + - [3, 4] + k: 1 + - name: "two-components" + in: + n: 6 + relations: + - [1, 2] + - [3, 4] + - [4, 5] + k: 2 + - name: "three-components" + in: + n: 8 + relations: + - [1, 2] + - [3, 4] + - [5, 6] + k: 3 + - name: "layered" + in: + n: 8 + relations: + - [1, 3] + - [1, 4] + - [2, 4] + - [2, 5] + - [3, 6] + - [4, 6] + - [5, 7] + - [6, 8] + k: 2 + - name: "layered-wide" + in: + n: 8 + relations: + - [1, 4] + - [2, 4] + - [3, 4] + - [1, 5] + - [2, 5] + - [3, 5] + - [4, 6] + - [5, 7] + - [6, 8] + - [7, 8] + k: 3 + - name: "reverse-numbered-chain" + in: + n: 5 + relations: + - [5, 4] + - [4, 3] + - [3, 2] + - [2, 1] + k: 2 + - name: "sparse-high-labels" + in: + n: 10 + relations: + - [8, 9] + - [9, 10] + - [2, 6] + k: 2 + - name: "many-prerequisites" + in: + n: 7 + relations: + - [1, 7] + - [2, 7] + - [3, 7] + - [4, 7] + - [5, 7] + - [6, 7] + k: 3 + - name: "many-successors" + in: + n: 8 + relations: + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [1, 6] + - [1, 7] + - [1, 8] + k: 2 + - name: "nested-chain-branch" + in: + n: 9 + relations: + - [1, 2] + - [2, 3] + - [3, 4] + - [3, 5] + - [5, 6] + - [4, 7] + - [6, 8] + - [7, 9] + k: 2 + - name: "nested-chain-branch-wide" + in: + n: 9 + relations: + - [1, 2] + - [1, 3] + - [2, 4] + - [3, 5] + - [4, 6] + - [5, 6] + - [6, 7] + - [6, 8] + - [7, 9] + k: 3 + - name: "six-node-dense-dag" + in: + n: 6 + relations: + - [1, 2] + - [1, 3] + - [1, 4] + - [2, 4] + - [2, 5] + - [3, 5] + - [4, 6] + - [5, 6] + k: 2 + - name: "six-node-dense-k-three" + in: + n: 6 + relations: + - [1, 2] + - [1, 3] + - [1, 4] + - [2, 4] + - [2, 5] + - [3, 5] + - [4, 6] + - [5, 6] + k: 3 + - name: "independent-plus-chain" + in: + n: 9 + relations: + - [1, 2] + - [2, 3] + - [4, 5] + - [6, 7] + - [7, 8] + k: 2 + - name: "alternating-branches" + in: + n: 10 + relations: + - [1, 3] + - [3, 5] + - [5, 7] + - [2, 4] + - [4, 6] + - [6, 8] + - [8, 10] + k: 2 + - name: "four-level-funnel" + in: + n: 10 + relations: + - [1, 5] + - [2, 5] + - [3, 6] + - [4, 6] + - [5, 7] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + k: 2 + - name: "ten-independent-k-four" + in: + n: 10 + relations: [] + k: 4 + - name: "ten-independent-k-one" + in: + n: 10 + relations: [] + k: 1 + - name: "max-node-chain" + in: + n: 15 + relations: + - [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] + k: 5 + - name: "max-node-independent" + in: + n: 15 + relations: [] + k: 7 + - name: "late-join" + in: + n: 8 + relations: + - [1, 4] + - [2, 4] + - [3, 5] + - [4, 6] + - [5, 6] + - [6, 7] + - [7, 8] + k: 2 + - name: "two-independent-forks" + in: + n: 10 + relations: + - [1, 2] + - [1, 3] + - [2, 4] + - [3, 5] + - [6, 7] + - [6, 8] + - [7, 9] + - [8, 10] + k: 3 + - name: "maximum-independent-all" + in: + n: 15 + relations: [] + k: 15 + - name: "complete-dag-wide" + in: + n: 15 + relations: + - [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] + - [2, 3] + - [2, 4] + - [2, 5] + - [2, 6] + - [2, 7] + - [2, 8] + - [2, 9] + - [2, 10] + - [2, 11] + - [2, 12] + - [2, 13] + - [2, 14] + - [2, 15] + - [3, 4] + - [3, 5] + - [3, 6] + - [3, 7] + - [3, 8] + - [3, 9] + - [3, 10] + - [3, 11] + - [3, 12] + - [3, 13] + - [3, 14] + - [3, 15] + - [4, 5] + - [4, 6] + - [4, 7] + - [4, 8] + - [4, 9] + - [4, 10] + - [4, 11] + - [4, 12] + - [4, 13] + - [4, 14] + - [4, 15] + - [5, 6] + - [5, 7] + - [5, 8] + - [5, 9] + - [5, 10] + - [5, 11] + - [5, 12] + - [5, 13] + - [5, 14] + - [5, 15] + - [6, 7] + - [6, 8] + - [6, 9] + - [6, 10] + - [6, 11] + - [6, 12] + - [6, 13] + - [6, 14] + - [6, 15] + - [7, 8] + - [7, 9] + - [7, 10] + - [7, 11] + - [7, 12] + - [7, 13] + - [7, 14] + - [7, 15] + - [8, 9] + - [8, 10] + - [8, 11] + - [8, 12] + - [8, 13] + - [8, 14] + - [8, 15] + - [9, 10] + - [9, 11] + - [9, 12] + - [9, 13] + - [9, 14] + - [9, 15] + - [10, 11] + - [10, 12] + - [10, 13] + - [10, 14] + - [10, 15] + - [11, 12] + - [11, 13] + - [11, 14] + - [11, 15] + - [12, 13] + - [12, 14] + - [12, 15] + - [13, 14] + - [13, 15] + - [14, 15] + k: 15 + - name: "complete-dag-narrow" + in: + n: 15 + relations: + - [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] + - [2, 3] + - [2, 4] + - [2, 5] + - [2, 6] + - [2, 7] + - [2, 8] + - [2, 9] + - [2, 10] + - [2, 11] + - [2, 12] + - [2, 13] + - [2, 14] + - [2, 15] + - [3, 4] + - [3, 5] + - [3, 6] + - [3, 7] + - [3, 8] + - [3, 9] + - [3, 10] + - [3, 11] + - [3, 12] + - [3, 13] + - [3, 14] + - [3, 15] + - [4, 5] + - [4, 6] + - [4, 7] + - [4, 8] + - [4, 9] + - [4, 10] + - [4, 11] + - [4, 12] + - [4, 13] + - [4, 14] + - [4, 15] + - [5, 6] + - [5, 7] + - [5, 8] + - [5, 9] + - [5, 10] + - [5, 11] + - [5, 12] + - [5, 13] + - [5, 14] + - [5, 15] + - [6, 7] + - [6, 8] + - [6, 9] + - [6, 10] + - [6, 11] + - [6, 12] + - [6, 13] + - [6, 14] + - [6, 15] + - [7, 8] + - [7, 9] + - [7, 10] + - [7, 11] + - [7, 12] + - [7, 13] + - [7, 14] + - [7, 15] + - [8, 9] + - [8, 10] + - [8, 11] + - [8, 12] + - [8, 13] + - [8, 14] + - [8, 15] + - [9, 10] + - [9, 11] + - [9, 12] + - [9, 13] + - [9, 14] + - [9, 15] + - [10, 11] + - [10, 12] + - [10, 13] + - [10, 14] + - [10, 15] + - [11, 12] + - [11, 13] + - [11, 14] + - [11, 15] + - [12, 13] + - [12, 14] + - [12, 15] + - [13, 14] + - [13, 15] + - [14, 15] + k: 1 + - name: "maximum-three-layers" + in: + n: 15 + relations: + - [1, 6] + - [1, 7] + - [1, 8] + - [1, 9] + - [1, 10] + - [2, 6] + - [2, 7] + - [2, 8] + - [2, 9] + - [2, 10] + - [3, 6] + - [3, 7] + - [3, 8] + - [3, 9] + - [3, 10] + - [4, 6] + - [4, 7] + - [4, 8] + - [4, 9] + - [4, 10] + - [5, 6] + - [5, 7] + - [5, 8] + - [5, 9] + - [5, 10] + - [6, 11] + - [6, 12] + - [6, 13] + - [6, 14] + - [6, 15] + - [7, 11] + - [7, 12] + - [7, 13] + - [7, 14] + - [7, 15] + - [8, 11] + - [8, 12] + - [8, 13] + - [8, 14] + - [8, 15] + - [9, 11] + - [9, 12] + - [9, 13] + - [9, 14] + - [9, 15] + - [10, 11] + - [10, 12] + - [10, 13] + - [10, 14] + - [10, 15] + k: 4 + - name: "maximum-parallel-chains" + in: + n: 15 + relations: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + - [11, 12] + - [12, 13] + - [13, 14] + - [14, 15] + k: 3 diff --git a/tests/1001-1500/1494. parallel-courses-ii/sol.cpp b/tests/1001-1500/1494. parallel-courses-ii/sol.cpp new file mode 100644 index 00000000..d702e45e --- /dev/null +++ b/tests/1001-1500/1494. parallel-courses-ii/sol.cpp @@ -0,0 +1,66 @@ +class Solution { +public: + int minNumberOfSemesters(int n, vector>& relations, int k) { + vector> graph(n); + vector inDegrees(n, 0); + for (auto& rel : relations) { + int prev = rel[0] - 1; + int next = rel[1] - 1; + inDegrees[next]++; + graph[prev].push_back(next); + } + + unordered_map memo; + + function)> recurse = [&](int mask, vector inDeg) -> int { + if (mask == 0) return 0; + string key = to_string(mask) + "-"; + for (int d : inDeg) key += to_string(d) + ","; + if (memo.count(key)) return memo[key]; + + vector nodes; + for (int i = 0; i < n; i++) { + if ((mask & (1 << i)) && inDeg[i] == 0) { + nodes.push_back(i); + } + } + + int ans = INT_MAX; + int combLimit = min(k, (int)nodes.size()); + vector> combos = getCombinations(nodes, combLimit); + for (auto& kNodes : combos) { + int newMask = mask; + vector newInDeg = inDeg; + for (int node : kNodes) { + newMask ^= (1 << node); + for (int child : graph[node]) { + newInDeg[child]--; + } + } + ans = min(ans, 1 + recurse(newMask, newInDeg)); + } + return memo[key] = ans; + }; + + return recurse((1 << n) - 1, inDegrees); + } + +private: + vector> getCombinations(vector& arr, int k) { + vector> result; + vector current; + function backtrack = [&](int start) { + if (current.size() == k) { + result.push_back(current); + return; + } + for (int i = start; i < arr.size(); i++) { + current.push_back(arr[i]); + backtrack(i + 1); + current.pop_back(); + } + }; + backtrack(0); + return result; + } +}; diff --git a/tests/1001-1500/1494. parallel-courses-ii/sol.cs b/tests/1001-1500/1494. parallel-courses-ii/sol.cs new file mode 100644 index 00000000..8b99f8ec --- /dev/null +++ b/tests/1001-1500/1494. parallel-courses-ii/sol.cs @@ -0,0 +1,71 @@ +public class Solution { + private int n; + private int k; + private List[] graph; + private Dictionary memo; + + public int MinNumberOfSemesters(int n, int[][] relations, int k) { + this.n = n; + this.k = k; + graph = new List[n]; + for (int i = 0; i < n; i++) { + graph[i] = new List(); + } + int[] inDegrees = new int[n]; + foreach (var rel in relations) { + int prev = rel[0] - 1; + int next = rel[1] - 1; + inDegrees[next]++; + graph[prev].Add(next); + } + memo = new Dictionary(); + return Recurse((1 << n) - 1, inDegrees); + } + + private int Recurse(int mask, int[] inDegrees) { + if (mask == 0) return 0; + string key = mask + string.Join(",", inDegrees); + if (memo.ContainsKey(key)) return memo[key]; + + List nodes = new List(); + for (int i = 0; i < n; i++) { + if ((mask & (1 << i)) != 0 && inDegrees[i] == 0) { + nodes.Add(i); + } + } + int ans = int.MaxValue; + int combLimit = Math.Min(k, nodes.Count); + var combos = GetCombinations(nodes, combLimit); + foreach (var kNodes in combos) { + int newMask = mask; + int[] newInDeg = (int[])inDegrees.Clone(); + foreach (int node in kNodes) { + newMask ^= (1 << node); + foreach (int child in graph[node]) { + newInDeg[child]--; + } + } + ans = Math.Min(ans, 1 + Recurse(newMask, newInDeg)); + } + memo[key] = ans; + return ans; + } + + private List> GetCombinations(List arr, int k) { + var result = new List>(); + Backtrack(arr, k, 0, new List(), result); + return result; + } + + private void Backtrack(List arr, int k, int start, List current, List> result) { + if (current.Count == k) { + result.Add(new List(current)); + return; + } + for (int i = start; i < arr.Count; i++) { + current.Add(arr[i]); + Backtrack(arr, k, i + 1, current, result); + current.RemoveAt(current.Count - 1); + } + } +} diff --git a/tests/1001-1500/1494. parallel-courses-ii/sol.dart b/tests/1001-1500/1494. parallel-courses-ii/sol.dart new file mode 100644 index 00000000..b280291e --- /dev/null +++ b/tests/1001-1500/1494. parallel-courses-ii/sol.dart @@ -0,0 +1,67 @@ +class Solution { + late int n; + late int k; + late List> graph; + late Map memo; + + int minNumberOfSemesters(int n, List> relations, int k) { + this.n = n; + this.k = k; + graph = List.generate(n, (_) => []); + List inDegrees = List.filled(n, 0); + for (var rel in relations) { + int prev = rel[0] - 1; + int next = rel[1] - 1; + inDegrees[next]++; + graph[prev].add(next); + } + memo = {}; + return recurse((1 << n) - 1, inDegrees); + } + + int recurse(int mask, List inDegrees) { + if (mask == 0) return 0; + String key = '$mask-${inDegrees.toString()}'; + if (memo.containsKey(key)) return memo[key]!; + + List nodes = []; + for (int i = 0; i < n; i++) { + if ((mask & (1 << i)) != 0 && inDegrees[i] == 0) { + nodes.add(i); + } + } + int ans = 1 << 60; + int combLimit = k < nodes.length ? k : nodes.length; + List> combos = getCombinations(nodes, combLimit); + for (var kNodes in combos) { + int newMask = mask; + List newInDeg = List.from(inDegrees); + for (var node in kNodes) { + newMask ^= (1 << node); + for (var child in graph[node]) { + newInDeg[child]--; + } + } + ans = min(ans, 1 + recurse(newMask, newInDeg)); + } + memo[key] = ans; + return ans; + } + + List> getCombinations(List nodes, int k) { + List> result = []; + void helper(int start, List current) { + if (current.length == k) { + result.add(List.from(current)); + return; + } + for (int i = start; i < nodes.length; i++) { + current.add(nodes[i]); + helper(i + 1, current); + current.removeLast(); + } + } + helper(0, []); + return result; + } +} diff --git a/tests/1001-1500/1494. parallel-courses-ii/sol.go b/tests/1001-1500/1494. parallel-courses-ii/sol.go new file mode 100644 index 00000000..e531ed3e --- /dev/null +++ b/tests/1001-1500/1494. parallel-courses-ii/sol.go @@ -0,0 +1,81 @@ +func minNumberOfSemesters(n int, relations [][]int, k int) int { + graph := make([][]int, n) + inDegrees := make([]int, n) + for _, rel := range relations { + prev := rel[0] - 1 + next := rel[1] - 1 + inDegrees[next]++ + graph[prev] = append(graph[prev], next) + } + + memo := make(map[string]int) + + var recurse func(int, []int) int + recurse = func(mask int, inDeg []int) int { + if mask == 0 { + return 0 + } + key := fmt.Sprintf("%d-%v", mask, inDeg) + if val, ok := memo[key]; ok { + return val + } + + nodes := []int{} + for i := 0; i < n; i++ { + if (mask & (1 << i)) != 0 && inDeg[i] == 0 { + nodes = append(nodes, i) + } + } + + ans := int(^uint(0) >> 1) // max int + combLimit := k + if len(nodes) < combLimit { + combLimit = len(nodes) + } + + combos := combinations(nodes, combLimit) + for _, kNodes := range combos { + newMask := mask + newInDeg := make([]int, len(inDeg)) + copy(newInDeg, inDeg) + for _, node := range kNodes { + newMask ^= (1 << node) + for _, child := range graph[node] { + newInDeg[child]-- + } + } + ans = min(ans, 1 + recurse(newMask, newInDeg)) + } + memo[key] = ans + return ans + } + + return recurse((1<> graph; + private Map memo; + + public int minNumberOfSemesters(int n, int[][] relations, int k) { + this.n = n; + this.k = k; + this.graph = new ArrayList<>(); + for (int i = 0; i < n; i++) { + graph.add(new ArrayList<>()); + } + int[] inDegrees = new int[n]; + for (int[] rel : relations) { + int prev = rel[0] - 1; + int next = rel[1] - 1; + inDegrees[next]++; + graph.get(prev).add(next); + } + memo = new HashMap<>(); + return recurse((1 << n) - 1, inDegrees); + } + + private int recurse(int mask, int[] inDegrees) { + if (mask == 0) return 0; + String key = mask + Arrays.toString(inDegrees); + if (memo.containsKey(key)) return memo.get(key); + + List nodes = new ArrayList<>(); + for (int i = 0; i < n; i++) { + if ((mask & (1 << i)) != 0 && inDegrees[i] == 0) { + nodes.add(i); + } + } + int ans = Integer.MAX_VALUE; + int combLimit = Math.min(k, nodes.size()); + List> combinations = getCombinations(nodes, combLimit); + for (List kNodes : combinations) { + int newMask = mask; + int[] newInDeg = inDegrees.clone(); + for (int node : kNodes) { + newMask ^= (1 << node); + for (int child : graph.get(node)) { + newInDeg[child]--; + } + } + ans = Math.min(ans, 1 + recurse(newMask, newInDeg)); + } + memo.put(key, ans); + return ans; + } + + private void getCombinationsHelper(List nodes, int start, int k, List current, List> result) { + if (k == 0) { + result.add(new ArrayList<>(current)); + return; + } + for (int i = start; i < nodes.size(); i++) { + current.add(nodes.get(i)); + getCombinationsHelper(nodes, i + 1, k - 1, current, result); + current.remove(current.size() - 1); + } + } + + private List> getCombinations(List nodes, int k) { + List> result = new ArrayList<>(); + getCombinationsHelper(nodes, 0, k, new ArrayList<>(), result); + return result; + } +} diff --git a/tests/1001-1500/1494. parallel-courses-ii/sol.kt b/tests/1001-1500/1494. parallel-courses-ii/sol.kt new file mode 100644 index 00000000..6e8219b3 --- /dev/null +++ b/tests/1001-1500/1494. parallel-courses-ii/sol.kt @@ -0,0 +1,68 @@ +class Solution { + private var n: Int = 0 + private var k: Int = 0 + private lateinit var graph: Array> + private val memo = HashMap() + + fun minNumberOfSemesters(n: Int, relations: Array, k: Int): Int { + this.n = n + this.k = k + graph = Array(n) { mutableListOf() } + val inDegrees = IntArray(n) + for (rel in relations) { + val prev = rel[0] - 1 + val next = rel[1] - 1 + inDegrees[next]++ + graph[prev].add(next) + } + memo.clear() + return recurse((1 shl n) - 1, inDegrees) + } + + private fun recurse(mask: Int, inDegrees: IntArray): Int { + if (mask == 0) return 0 + val key = "$mask-${inDegrees.joinToString()}" + memo[key]?.let { return it } + + val nodes = mutableListOf() + for (i in 0 until n) { + if ((mask and (1 shl i)) != 0 && inDegrees[i] == 0) { + nodes.add(i) + } + } + var ans = Int.MAX_VALUE + val combLimit = minOf(k, nodes.size) + val combinations = getCombinations(nodes, combLimit) + for (kNodes in combinations) { + var newMask = mask + val newInDeg = inDegrees.clone() + for (node in kNodes) { + newMask = newMask xor (1 shl node) + for (child in graph[node]) { + newInDeg[child]-- + } + } + ans = minOf(ans, 1 + recurse(newMask, newInDeg)) + } + memo[key] = ans + return ans + } + + private fun getCombinations(nodes: List, k: Int): List> { + val result = mutableListOf>() + combineHelper(nodes, 0, k, mutableListOf(), result) + return result + } + + private fun combineHelper(nodes: List, start: Int, k: Int, current: MutableList, result: MutableList>) { + if (k == 0) { + result.add(current.toList()) + return + } + for (i in start until nodes.size) { + current.add(nodes[i]) + combineHelper(nodes, i + 1, k - 1, current, result) + current.removeAt(current.size - 1) + } + } +} diff --git a/tests/1001-1500/1494. parallel-courses-ii/sol.py b/tests/1001-1500/1494. parallel-courses-ii/sol.py new file mode 100644 index 00000000..6d445c32 --- /dev/null +++ b/tests/1001-1500/1494. parallel-courses-ii/sol.py @@ -0,0 +1,51 @@ +from collections import defaultdict +from functools import lru_cache +from typing import List +from itertools import combinations # for picking k of n + + +class Solution: + @lru_cache(None) # caching for faster lookups + def recurse(self, mask, in_degrees): + # if all the bits are 0, we have taken all the courses + if not mask: + return 0 + + # all the nodes that *can* be taken now, following both the properties + nodes = [i for i in range(self.n) if mask & 1 << i and in_degrees[i] == 0] + + ans = float("inf") + # enumerating all the possible combinations + for k_nodes in combinations(nodes, min(self.k, len(nodes))): + new_mask, new_in_degrees = mask, list(in_degrees) + + # updating what would happen to new_mask and new_in_degrees + # if we considered the nodes in k_nodes + for node in k_nodes: + # since we know the bit is set, we un-set this bit, to mark it "considered" + new_mask ^= 1 << node + # updating each of the in-degrees, since the "parents" have been taken away + for child in self.graph[node]: + new_in_degrees[child] -= 1 + + # the heart of recursion + # note the +1! + ans = min(ans, 1 + self.recurse(new_mask, tuple(new_in_degrees))) + return ans + + def minNumberOfSemesters(self, n: int, relations: List[List[int]], k: int) -> int: + # saving n and k for later use + self.n = n + self.k = k + in_degrees = [0] * self.n + # graph layout remains the same, although the in_degrees change. + # This allows us to keep graph as self.graph + # instead of passing it over and over. + self.graph = defaultdict(list) + for prev_course, next_course in relations: + # remember, its 0-indexed now! + in_degrees[next_course - 1] += 1 + self.graph[prev_course - 1].append(next_course - 1) + + # start with all the bits set + return self.recurse((1 << self.n) - 1, tuple(in_degrees)) diff --git a/tests/1001-1500/1494. parallel-courses-ii/sol.py2 b/tests/1001-1500/1494. parallel-courses-ii/sol.py2 new file mode 100644 index 00000000..7c60c364 --- /dev/null +++ b/tests/1001-1500/1494. parallel-courses-ii/sol.py2 @@ -0,0 +1,41 @@ +class Solution(object): + def minNumberOfSemesters(self, n, relations, k): + """ + :type n: int + :type relations: List[List[int]] + :type k: int + :rtype: int + """ + from collections import defaultdict + from itertools import combinations + + self.n = n + self.k = k + in_degrees = [0] * n + self.graph = defaultdict(list) + for prev_course, next_course in relations: + in_degrees[next_course - 1] += 1 + self.graph[prev_course - 1].append(next_course - 1) + + memo = {} + def recurse(mask, in_deg_tuple): + if mask == 0: + return 0 + key = (mask, in_deg_tuple) + if key in memo: + return memo[key] + in_deg_list = list(in_deg_tuple) + nodes = [i for i in range(n) if mask & (1 << i) and in_deg_list[i] == 0] + ans = float('inf') + for k_nodes in combinations(nodes, min(k, len(nodes))): + new_mask = mask + new_in_deg = list(in_deg_list) + for node in k_nodes: + new_mask ^= 1 << node + for child in self.graph[node]: + new_in_deg[child] -= 1 + ans = min(ans, 1 + recurse(new_mask, tuple(new_in_deg))) + memo[key] = ans + return ans + + return recurse((1 << n) - 1, tuple(in_degrees)) diff --git a/tests/1001-1500/1494. parallel-courses-ii/sol.rb b/tests/1001-1500/1494. parallel-courses-ii/sol.rb new file mode 100644 index 00000000..894d2247 --- /dev/null +++ b/tests/1001-1500/1494. parallel-courses-ii/sol.rb @@ -0,0 +1,42 @@ +# @param {Integer} n +# @param {Integer[][]} relations +# @param {Integer} k +# @return {Integer} +def min_number_of_semesters(n, relations, k) + @n = n + @k = k + @graph = Hash.new { |h, key| h[key] = [] } + in_degrees = Array.new(n, 0) + relations.each do |prev_course, next_course| + in_degrees[next_course - 1] += 1 + @graph[prev_course - 1] << next_course - 1 + end + + @memo = {} + + recurse = lambda do |mask, in_deg_tuple| + return 0 if mask == 0 + key = [mask, in_deg_tuple] + return @memo[key] if @memo.key?(key) + + in_deg_list = in_deg_tuple.dup + nodes = (0...@n).select { |i| mask & (1 << i) != 0 && in_deg_list[i] == 0 } + ans = Float::INFINITY + + nodes.combination([@k, nodes.length].min).each do |k_nodes| + new_mask = mask + new_in_deg = in_deg_list.dup + k_nodes.each do |node| + new_mask ^= (1 << node) + @graph[node].each do |child| + new_in_deg[child] -= 1 + end + end + ans = [ans, 1 + recurse.call(new_mask, new_in_deg)].min + end + @memo[key] = ans + ans + end + + recurse.call((1 << n) - 1, in_degrees) +end diff --git a/tests/1001-1500/1494. parallel-courses-ii/sol.rs b/tests/1001-1500/1494. parallel-courses-ii/sol.rs new file mode 100644 index 00000000..7a673d5c --- /dev/null +++ b/tests/1001-1500/1494. parallel-courses-ii/sol.rs @@ -0,0 +1,78 @@ +use std::collections::HashMap; + +impl Solution { + pub fn min_number_of_semesters(n: i32, relations: Vec>, k: i32) -> i32 { + let n = n as usize; + let k = k as usize; + let mut graph: Vec> = vec![Vec::new(); n]; + let mut in_degrees = vec![0i32; n]; + for rel in &relations { + let prev = (rel[0] - 1) as usize; + let next = (rel[1] - 1) as usize; + in_degrees[next] += 1; + graph[prev].push(next); + } + + let mut memo: HashMap<(i32, Vec), i32> = HashMap::new(); + + fn recurse( + mask: i32, + in_degrees: Vec, + n: usize, + k: usize, + graph: &Vec>, + memo: &mut HashMap<(i32, Vec), i32>, + ) -> i32 { + if mask == 0 { + return 0; + } + if let Some(&val) = memo.get(&(mask, in_degrees.clone())) { + return val; + } + + let mut nodes: Vec = Vec::new(); + for i in 0..n { + if (mask & (1 << i)) != 0 && in_degrees[i] == 0 { + nodes.push(i); + } + } + + let mut ans = i32::MAX; + let comb_limit = std::cmp::min(k, nodes.len()); + let combos = combinations(&nodes, comb_limit); + for k_nodes in &combos { + let mut new_mask = mask; + let mut new_in_deg = in_degrees.clone(); + for &node in k_nodes { + new_mask ^= 1 << node; + for &child in &graph[node] { + new_in_deg[child] -= 1; + } + } + ans = std::cmp::min(ans, 1 + recurse(new_mask, new_in_deg, n, k, graph, memo)); + } + memo.insert((mask, in_degrees.clone()), ans); + ans + } + + recurse((1 << n) - 1, in_degrees, n, k, &graph, &mut memo) + } +} + +fn combinations(arr: &[usize], k: usize) -> Vec> { + let mut result = Vec::new(); + let mut current = Vec::new(); + fn backtrack(arr: &[usize], k: usize, start: usize, current: &mut Vec, result: &mut Vec>) { + if current.len() == k { + result.push(current.clone()); + return; + } + for i in start..arr.len() { + current.push(arr[i]); + backtrack(arr, k, i + 1, current, result); + current.pop(); + } + } + backtrack(arr, k, 0, &mut current, &mut result); + result +} diff --git a/tests/1001-1500/1494. parallel-courses-ii/sol.swift b/tests/1001-1500/1494. parallel-courses-ii/sol.swift new file mode 100644 index 00000000..a27e1284 --- /dev/null +++ b/tests/1001-1500/1494. parallel-courses-ii/sol.swift @@ -0,0 +1,69 @@ +class Solution { + var n: Int = 0 + var k: Int = 0 + var graph: [[Int]] = [] + var memo: [String: Int] = [:] + + func minNumberOfSemesters(_ n: Int, _ relations: [[Int]], _ k: Int) -> Int { + self.n = n + self.k = k + graph = Array(repeating: [], count: n) + var inDegrees = Array(repeating: 0, count: n) + for rel in relations { + let prev = rel[0] - 1 + let next = rel[1] - 1 + inDegrees[next] += 1 + graph[prev].append(next) + } + memo = [:] + return recurse((1 << n) - 1, inDegrees) + } + + func recurse(_ mask: Int, _ inDegrees: [Int]) -> Int { + if mask == 0 { return 0 } + let key = "\(mask)-\(inDegrees)" + if let val = memo[key] { return val } + + var nodes: [Int] = [] + for i in 0.. [[Int]] { + var result: [[Int]] = [] + func helper(_ start: Int, _ current: inout [Int]) { + if current.count == k { + result.append(current) + return + } + if start >= arr.count { return } + for i in start.. []); + const inDegrees: number[] = Array(n).fill(0); + for (const [prev, next] of relations) { + inDegrees[next - 1]++; + graph[prev - 1].push(next - 1); + } + + const memo = new Map(); + + const recurse = (mask: number, inDeg: number[]): number => { + if (mask === 0) return 0; + const key = `${mask}-${inDeg.toString()}`; + if (memo.has(key)) return memo.get(key)!; + + const nodes: number[] = []; + for (let i = 0; i < n; i++) { + if ((mask & (1 << i)) !== 0 && inDeg[i] === 0) { + nodes.push(i); + } + } + let ans = Infinity; + const combLimit = Math.min(k, nodes.length); + const combos = getCombinations(nodes, combLimit); + for (const kNodes of combos) { + let newMask = mask; + const newInDeg = [...inDeg]; + for (const node of kNodes) { + newMask ^= 1 << node; + for (const child of graph[node]) { + newInDeg[child]--; + } + } + ans = Math.min(ans, 1 + recurse(newMask, newInDeg)); + } + memo.set(key, ans); + return ans; + }; + + return recurse((1 << n) - 1, inDegrees); +} + +function getCombinations(arr: number[], k: number): number[][] { + const result: number[][] = []; + const helper = (start: number, current: number[]) => { + if (current.length === k) { + result.push([...current]); + return; + } + for (let i = start; i < arr.length; i++) { + current.push(arr[i]); + helper(i + 1, current); + current.pop(); + } + }; + helper(0, []); + return result; +} diff --git a/tests/1001-1500/1496. path-crossing/manifest.yaml b/tests/1001-1500/1496. path-crossing/manifest.yaml new file mode 100644 index 00000000..22b32f80 --- /dev/null +++ b/tests/1001-1500/1496. path-crossing/manifest.yaml @@ -0,0 +1,210 @@ +entry: + id: 1496 + title: "path-crossing" + params: + path: + type: string + call: + cpp: "Solution().isPathCrossing({path})" + rust: "Solution::is_path_crossing({path})" + python3: "Solution().isPathCrossing({path})" + python2: "Solution().isPathCrossing({path})" + ruby: "is_path_crossing({path})" + java: "new Solution().isPathCrossing({path})" + csharp: "new Solution().IsPathCrossing({path})" + kotlin: "Solution().isPathCrossing({path})" + go: "isPathCrossing({path})" + dart: "Solution().isPathCrossing({path})" + swift: "Solution().isPathCrossing({path})" + typescript: "isPathCrossing({path})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().isPathCrossing(path, {result})" + checker: | + class Checker: + def isPathCrossing(self, path, result): + x = y = 0 + seen = {(0, 0)} + moves = {"N": (0, 1), "S": (0, -1), "E": (1, 0), "W": (-1, 0)} + expected = False + for step in path: + dx, dy = moves[step] + x += dx + y += dy + if (x, y) in seen: + expected = True + break + seen.add((x, y)) + return isinstance(result, bool) and result == expected + +seed: 1496 + +tests: + - name: "example_nes" + in: + path: "NES" + out: false + - name: "example_nesww" + in: + path: "NESWW" + out: true + - name: "single_north" + in: + path: "N" + out: false + - name: "single_west" + in: + path: "W" + out: false + - name: "single_south" + in: + path: "S" + out: false + - name: "single_east" + in: + path: "E" + out: false + - name: "immediate_vertical_return" + in: + path: "NS" + out: true + - name: "immediate_horizontal_return" + in: + path: "EW" + out: true + - name: "vertical_line" + in: + path: "NNNNNN" + out: false + - name: "horizontal_line" + in: + path: "EEEEEE" + out: false + - name: "unit_square" + in: + path: "NESW" + out: true + - name: "reverse_unit_square" + in: + path: "ENWS" + out: true + - name: "large_square" + in: + path: "NNNEEESSSWWW" + - name: "open_corner" + in: + path: "NEEESSS" + out: false + - name: "rectangle_closes" + in: + path: "NEEESSWW" + out: false + - name: "out_and_back" + in: + path: "NNNEEESSS" + - name: "zigzag_open" + in: + path: "NENENEEE" + out: false + - name: "zigzag_revisit" + in: + path: "NENESW" + - name: "spiral_open" + in: + path: "ENNWWSSEEE" + - name: "spiral_closes" + in: + path: "ENNWWSSEE" + - name: "repeated_east_west" + in: + path: "EEEEWW" + out: true + - name: "delayed_origin_return" + in: + path: "NNEESSWW" + out: true + - name: "three_sided_path" + in: + path: "NNNEEESSSWWWN" + - name: "no_revisit_serpentine" + in: + path: "EEENWNENWNE" + - name: "serpentine_open" + in: + path: "EEENWNEEESW" + - name: "alternating_vertical" + in: + path: "NSSSSNNNN" + - name: "alternating_horizontal" + in: + path: "EWWWWEEEE" + - name: "crossing_diagonal_like" + in: + path: "NESE" + - name: "long_open_ray_turn" + in: + path: "NNNNNEEEEE" + - name: "long_closed_perimeter" + in: + path: "NNNNNEEEEEESSSSSWWWWWW" + - name: "nested_loop" + in: + path: "NEEESSWWNNEEESSWW" + - name: "late_single_revisit" + in: + path: "NNNEEESSSW" + - name: "non_origin_revisit" + in: + path: "NENWS" + out: true + - name: "long_detour_without_revisit" + in: + path: "NNNNEEEEESSSS" + out: false + - name: "partial_rectangle_open" + in: + path: "NNEESS" + out: false + - name: "generated_short" + seed: 101 + in: + path: + gen: "str" + len: 25 + alphabet: "NSEW" + - name: "generated_medium" + seed: 202 + in: + path: + gen: "str" + len: 250 + alphabet: "NSEW" + - name: "generated_long" + seed: 303 + in: + path: + gen: "str" + len: 5000 + alphabet: "NSEW" + - name: "generated_maximum" + seed: 404 + in: + path: + gen: "str" + len: 10000 + alphabet: "NSEW" + - name: "generated_direction_biased" + seed: 505 + in: + path: + gen: "str" + len: 1000 + alphabet: "NNNEEEESW" diff --git a/tests/1001-1500/1496. path-crossing/sol.cpp b/tests/1001-1500/1496. path-crossing/sol.cpp new file mode 100644 index 00000000..a57350ed --- /dev/null +++ b/tests/1001-1500/1496. path-crossing/sol.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + bool isPathCrossing(string path) { + set> s; + int x = 0, y = 0; + s.insert({0, 0}); + for (char c : path) { + if (c == 'N') y++; + else if (c == 'S') y--; + else if (c == 'E') x++; + else if (c == 'W') x--; + if (s.count({x, y})) return true; + s.insert({x, y}); + } + return false; + } +}; diff --git a/tests/1001-1500/1496. path-crossing/sol.cs b/tests/1001-1500/1496. path-crossing/sol.cs new file mode 100644 index 00000000..614c95d4 --- /dev/null +++ b/tests/1001-1500/1496. path-crossing/sol.cs @@ -0,0 +1,17 @@ +public class Solution { + public bool IsPathCrossing(string path) { + var set = new HashSet<(int, int)>(); + int x = 0, y = 0; + set.Add((0, 0)); + foreach (char c in path) { + if (c == 'N') y++; + else if (c == 'S') y--; + else if (c == 'E') x++; + else if (c == 'W') x--; + var point = (x, y); + if (set.Contains(point)) return true; + set.Add(point); + } + return false; + } +} diff --git a/tests/1001-1500/1496. path-crossing/sol.dart b/tests/1001-1500/1496. path-crossing/sol.dart new file mode 100644 index 00000000..8dad5e1a --- /dev/null +++ b/tests/1001-1500/1496. path-crossing/sol.dart @@ -0,0 +1,17 @@ +class Solution { + bool isPathCrossing(String path) { + var set = {}; + int x = 0, y = 0; + set.add("0,0"); + for (var c in path.split('')) { + if (c == 'N') y++; + else if (c == 'S') y--; + else if (c == 'E') x++; + else if (c == 'W') x--; + String point = "$x,$y"; + if (set.contains(point)) return true; + set.add(point); + } + return false; + } +} diff --git a/tests/1001-1500/1496. path-crossing/sol.go b/tests/1001-1500/1496. path-crossing/sol.go new file mode 100644 index 00000000..3531ea57 --- /dev/null +++ b/tests/1001-1500/1496. path-crossing/sol.go @@ -0,0 +1,19 @@ +func isPathCrossing(path string) bool { + set := make(map[string]bool) + x, y := 0, 0 + set["0,0"] = true + for _, c := range path { + switch c { + case 'N': y++ + case 'S': y-- + case 'E': x++ + case 'W': x-- + } + point := fmt.Sprintf("%d,%d", x, y) + if set[point] { + return true + } + set[point] = true + } + return false +} diff --git a/tests/1001-1500/1496. path-crossing/sol.java b/tests/1001-1500/1496. path-crossing/sol.java new file mode 100644 index 00000000..a07f08df --- /dev/null +++ b/tests/1001-1500/1496. path-crossing/sol.java @@ -0,0 +1,17 @@ +class Solution { + public boolean isPathCrossing(String path) { + Set set = new HashSet<>(); + int x = 0, y = 0; + set.add("0,0"); + for (char c : path.toCharArray()) { + if (c == 'N') y++; + else if (c == 'S') y--; + else if (c == 'E') x++; + else if (c == 'W') x--; + String point = x + "," + y; + if (set.contains(point)) return true; + set.add(point); + } + return false; + } +} diff --git a/tests/1001-1500/1496. path-crossing/sol.kt b/tests/1001-1500/1496. path-crossing/sol.kt new file mode 100644 index 00000000..af852870 --- /dev/null +++ b/tests/1001-1500/1496. path-crossing/sol.kt @@ -0,0 +1,20 @@ +class Solution { + fun isPathCrossing(path: String): Boolean { + val set = HashSet() + var x = 0 + var y = 0 + set.add("0,0") + for (c in path) { + when (c) { + 'N' -> y++ + 'S' -> y-- + 'E' -> x++ + 'W' -> x-- + } + val point = "$x,$y" + if (set.contains(point)) return true + set.add(point) + } + return false + } +} diff --git a/tests/1001-1500/1496. path-crossing/sol.py b/tests/1001-1500/1496. path-crossing/sol.py new file mode 100644 index 00000000..22505af8 --- /dev/null +++ b/tests/1001-1500/1496. path-crossing/sol.py @@ -0,0 +1,16 @@ +class Solution: + def isPathCrossing(self, path: str) -> bool: + pos = [(0, 0)] + dic = {"N": 1, "S": -1, "E": 1, "W": -1} + x = 0 + for i in path: + left, right = pos[x] + if i == "N" or i == "S": + left += dic[i] + else: + right += dic[i] + x += 1 + if (left, right) in pos: + return True + pos.append((left, right)) + return False diff --git a/tests/1001-1500/1496. path-crossing/sol.py2 b/tests/1001-1500/1496. path-crossing/sol.py2 new file mode 100644 index 00000000..986f5a02 --- /dev/null +++ b/tests/1001-1500/1496. path-crossing/sol.py2 @@ -0,0 +1,20 @@ +class Solution(object): + def isPathCrossing(self, path): + """ + :type path: str + :rtype: bool + """ + pos = [(0, 0)] + dic = {"N": 1, "S": -1, "E": 1, "W": -1} + x = 0 + for i in path: + left, right = pos[x] + if i == "N" or i == "S": + left += dic[i] + else: + right += dic[i] + x += 1 + if (left, right) in pos: + return True + pos.append((left, right)) + return False diff --git a/tests/1001-1500/1496. path-crossing/sol.rb b/tests/1001-1500/1496. path-crossing/sol.rb new file mode 100644 index 00000000..2c17091c --- /dev/null +++ b/tests/1001-1500/1496. path-crossing/sol.rb @@ -0,0 +1,21 @@ +# @param {String} path +# @return {Boolean} +def is_path_crossing(path) + pos = [[0, 0]] + dic = {"N" => 1, "S" => -1, "E" => 1, "W" => -1} + x = 0 + path.each_char do |i| + left, right = pos[x] + if i == "N" or i == "S" + left += dic[i] + else + right += dic[i] + end + x += 1 + if pos.include?([left, right]) + return true + end + pos.append([left, right]) + end + return false +end diff --git a/tests/1001-1500/1496. path-crossing/sol.rs b/tests/1001-1500/1496. path-crossing/sol.rs new file mode 100644 index 00000000..60c97764 --- /dev/null +++ b/tests/1001-1500/1496. path-crossing/sol.rs @@ -0,0 +1,21 @@ +impl Solution { + pub fn is_path_crossing(path: String) -> bool { + use std::collections::HashSet; + let mut set = HashSet::new(); + let (mut x, mut y) = (0, 0); + set.insert((0, 0)); + for c in path.chars() { + match c { + 'N' => y += 1, + 'S' => y -= 1, + 'E' => x += 1, + 'W' => x -= 1, + _ => (), + } + if !set.insert((x, y)) { + return true; + } + } + false + } +} diff --git a/tests/1001-1500/1496. path-crossing/sol.swift b/tests/1001-1500/1496. path-crossing/sol.swift new file mode 100644 index 00000000..e0c9a580 --- /dev/null +++ b/tests/1001-1500/1496. path-crossing/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func isPathCrossing(_ path: String) -> Bool { + var set = Set() + var x = 0, y = 0 + set.insert("0,0") + for c in path { + switch c { + case "N": y += 1 + case "S": y -= 1 + case "E": x += 1 + case "W": x -= 1 + default: break + } + let point = "\(x),\(y)" + if set.contains(point) { return true } + set.insert(point) + } + return false + } +} diff --git a/tests/1001-1500/1496. path-crossing/sol.ts b/tests/1001-1500/1496. path-crossing/sol.ts new file mode 100644 index 00000000..30e86027 --- /dev/null +++ b/tests/1001-1500/1496. path-crossing/sol.ts @@ -0,0 +1,16 @@ +function isPathCrossing(path: string): boolean { + const set = new Set(); + let x = 0, + y = 0; + set.add("0,0"); + for (const c of path) { + if (c === "N") y++; + else if (c === "S") y--; + else if (c === "E") x++; + else if (c === "W") x--; + const point = `${x},${y}`; + if (set.has(point)) return true; + set.add(point); + } + return false; +} diff --git a/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/manifest.yaml b/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/manifest.yaml new file mode 100644 index 00000000..bcf01a29 --- /dev/null +++ b/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/manifest.yaml @@ -0,0 +1,209 @@ +entry: + id: 1497 + title: check-if-array-pairs-are-divisible-by-k + params: + arr: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().canArrange({arr}, {k})" + rust: "Solution::can_arrange({arr}, {k})" + python3: "Solution().canArrange({arr}, {k})" + python2: "Solution().canArrange({arr}, {k})" + ruby: "can_arrange({arr}, {k})" + java: "new Solution().canArrange({arr}, {k})" + csharp: "new Solution().CanArrange({arr}, {k})" + kotlin: "Solution().canArrange({arr}, {k})" + go: "canArrange({arr}, {k})" + dart: "Solution().canArrange({arr}, {k})" + swift: "Solution().canArrange({arr}, {k})" + typescript: "canArrange({arr}, {k})" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().canArrange(arr, k, {result})" + checker: | + class Checker: + def canArrange(self, arr, k, result): + if type(result) is not bool or len(arr) % 2 != 0 or k < 1: + return False + counts = [0] * k + for value in arr: + counts[value % k] += 1 + if counts[0] % 2: + return result is False + for rem in range(1, (k + 1) // 2): + if counts[rem] != counts[k - rem]: + return result is False + if k % 2 == 0 and counts[k // 2] % 2: + return result is False + return result is True +seed: 1497 +tests: + - name: prompt-example-one + in: + arr: [1, 2, 3, 4, 5, 10, 6, 7, 8, 9] + k: 5 + - name: prompt-example-two + in: + arr: [1, 2, 3, 4, 5, 6] + k: 7 + - name: prompt-example-three + in: + arr: [1, 2, 3, 4, 5, 6] + k: 10 + - name: pair-sum-zero + in: + arr: [1, -1] + k: 5 + - name: pair-exact-multiple + in: + arr: [5, 10] + k: 5 + - name: single-pair-false + in: + arr: [1, 2] + k: 4 + - name: two-zero-remainders + in: + arr: [0, 5, 10, 15] + k: 5 + - name: self-complement-even + in: + arr: [2, 4] + k: 3 + - name: self-complement-odd + in: + arr: [1, 4, 7, 2] + k: 3 + - name: complementary-remainders + in: + arr: [1, 2, 4, 5] + k: 6 + - name: complementary-mismatch + in: + arr: [1, 2, 4, 4] + k: 6 + - name: negative-values-valid + in: + arr: [-1, -2, 1, 2] + k: 3 + - name: negative-values-invalid + in: + arr: [-1, -1, 2, 2] + k: 5 + - name: all-zeroes + in: + arr: [0, 0, 0, 0, 0, 0] + k: 7 + - name: all-same-multiple + in: + arr: [10, 20, 30, 40] + k: 10 + - name: all-same-nonmultiple-even + in: + arr: [1, 1, 1, 1] + k: 5 + - name: all-same-nonmultiple-odd + in: + arr: [1, 1, 1, 1, 1, 1] + k: 5 + - name: k-one + in: + arr: [-100, 0, 37, 999] + k: 1 + - name: k-two-even + in: + arr: [1, 3, 5, 7] + k: 2 + - name: k-two-mixed + in: + arr: [1, 2, 3, 4] + k: 2 + - name: k-four-balanced + in: + arr: [1, 3, 5, 7, 2, 6] + k: 4 + - name: k-four-mismatch + in: + arr: [1, 1, 3, 5] + k: 4 + - name: k-six-balanced + in: + arr: [1, 7, 2, 8, 3, 9] + k: 6 + - name: repeated-complementary + in: + arr: [1, 1, 1, 4, 4, 4] + k: 5 + - name: three-remainder-groups + in: + arr: [1, 6, 11, 2, 7, 12, 3, 8, 13, 4, 9, 14] + k: 5 + - name: interleaved-valid + in: + arr: [8, 1, 14, 7, 2, 13, 6, 9] + k: 15 + - name: interleaved-invalid + in: + arr: [8, 1, 14, 7, 2, 13, 6, 8] + k: 15 + - name: large-positive-pairs + in: + arr: [1000000000, -1000000000, 999999999, -999999999] + k: 7 + - name: large-positive-mismatch + in: + arr: [1000000000, 1000000000, -1000000000, 999999998] + k: 11 + - name: spaced-valid + in: + arr: [3, 10, 17, 24, 31, 38, 45, 52] + k: 7 + - name: spaced-invalid + in: + arr: [3, 10, 17, 24, 31, 38, 45, 53] + k: 7 + - name: prime-k-valid + in: + arr: [1, 2, 4, 5, 7, 8, 10, 11] + k: 13 + - name: prime-k-invalid + in: + arr: [1, 2, 4, 5, 7, 8, 10, 12] + k: 13 + - name: many-zero-remainders + in: + arr: [21, 42, 63, 84, 105, 126, 147, 168] + k: 21 + - name: negative-complement-groups + in: + arr: [-10, -9, -8, -7, 1, 2, 3, 4] + k: 11 + - name: twelve-elements-valid + in: + arr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] + k: 13 + - name: twelve-elements-invalid + in: + arr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13] + k: 13 + - name: max-magnitude-mixed + in: + arr: [-1000000000, -999999997, 999999994, 1000000000] + k: 13 + - name: maximum-k-zero-residue-pair + in: + arr: [1000000000, -1000000000] + k: 100000 + - name: maximum-k-near-complement-invalid + in: + arr: [999999999, 2] + k: 100000 diff --git a/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.cpp b/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.cpp new file mode 100644 index 00000000..8748bb1e --- /dev/null +++ b/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + bool canArrange(vector& arr, int k) { + vector a(arr.size()); + for (int i = 0; i < arr.size(); i++) { + a[i] = ((arr[i] % k) + k) % k; + } + sort(a.begin(), a.end()); + int j = 0; + while (j < a.size() && a[j] == 0) j++; + if (j % 2 != 0) return false; + for (int l = j, r = a.size() - 1; l < r; l++, r--) { + if ((a[l] + a[r]) % k != 0) return false; + } + return true; + } +}; diff --git a/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.cs b/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.cs new file mode 100644 index 00000000..fd646c75 --- /dev/null +++ b/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.cs @@ -0,0 +1,17 @@ +public class Solution { + public bool CanArrange(int[] arr, int k) { + int n = arr.Length; + int[] a = new int[n]; + for (int i = 0; i < n; i++) { + a[i] = ((arr[i] % k) + k) % k; + } + Array.Sort(a); + int j = 0; + while (j < n && a[j] == 0) j++; + if (j % 2 != 0) return false; + for (int l = j, r = n - 1; l < r; l++, r--) { + if ((a[l] + a[r]) % k != 0) return false; + } + return true; + } +} diff --git a/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.dart b/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.dart new file mode 100644 index 00000000..227c68cd --- /dev/null +++ b/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.dart @@ -0,0 +1,12 @@ +class Solution { + bool canArrange(List arr, int k) { + List a = arr.map((v) => ((v % k) + k) % k).toList()..sort(); + int j = a.where((v) => v == 0).length; + if (j % 2 != 0) return false; + List b = a.sublist(j); + for (int l = 0, r = b.length - 1; l < r; l++, r--) { + if ((b[l] + b[r]) % k != 0) return false; + } + return true; + } +} diff --git a/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.go b/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.go new file mode 100644 index 00000000..23bda597 --- /dev/null +++ b/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.go @@ -0,0 +1,21 @@ +func canArrange(arr []int, k int) bool { + a := make([]int, len(arr)) + for i, v := range arr { + a[i] = ((v % k) + k) % k + } + sort.Ints(a) + j := 0 + for j < len(a) && a[j] == 0 { + j++ + } + if j%2 != 0 { + return false + } + b := a[j:] + for l, r := 0, len(b)-1; l < r; l, r = l+1, r-1 { + if (b[l]+b[r])%k != 0 { + return false + } + } + return true +} diff --git a/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.java b/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.java new file mode 100644 index 00000000..4ecb1396 --- /dev/null +++ b/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.java @@ -0,0 +1,17 @@ +class Solution { + public boolean canArrange(int[] arr, int k) { + int n = arr.length; + int[] a = new int[n]; + for (int i = 0; i < n; i++) { + a[i] = ((arr[i] % k) + k) % k; + } + Arrays.sort(a); + int j = 0; + while (j < n && a[j] == 0) j++; + if (j % 2 != 0) return false; + for (int l = j, r = n - 1; l < r; l++, r--) { + if ((a[l] + a[r]) % k != 0) return false; + } + return true; + } +} diff --git a/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.kt b/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.kt new file mode 100644 index 00000000..ff228e6e --- /dev/null +++ b/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.kt @@ -0,0 +1,9 @@ +class Solution { + fun canArrange(arr: IntArray, k: Int): Boolean { + val a = arr.map { ((it % k) + k) % k }.sorted() + val j = a.count { it == 0 } + if (j % 2 != 0) return false + val b = a.drop(j) + return b.zip(b.reversed()).all { (p, q) -> (p + q) % k == 0 } + } +} diff --git a/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.py b/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.py new file mode 100644 index 00000000..aff62d43 --- /dev/null +++ b/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.py @@ -0,0 +1,10 @@ +from typing import List + + +class Solution: + def canArrange(self, a: List[int], k: int) -> bool: + return ( + (j := (a := sorted(v % k for v in a)).count(0)) % 2 + == 0 + == sum((p + q) % k for p, q in zip(a[j:], a[::-1])) + ) diff --git a/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.py2 b/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.py2 new file mode 100644 index 00000000..44451f17 --- /dev/null +++ b/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.py2 @@ -0,0 +1,10 @@ +class Solution(object): + def canArrange(self, arr, k): + """ + :type arr: List[int] + :type k: int + :rtype: bool + """ + a = sorted(v % k for v in arr) + j = a.count(0) + return j % 2 == 0 and sum((p + q) % k for p, q in zip(a[j:], a[::-1])) == 0 diff --git a/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.rb b/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.rb new file mode 100644 index 00000000..65cabe1f --- /dev/null +++ b/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.rb @@ -0,0 +1,10 @@ +# @param {Integer[]} arr +# @param {Integer} k +# @return {Boolean} +def can_arrange(arr, k) + a = arr.map { |v| v % k }.sort + j = a.count(0) + return false unless j.even? + b = a[j..] + b.zip(b.reverse).all? { |p, q| (p + q) % k == 0 } +end diff --git a/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.rs b/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.rs new file mode 100644 index 00000000..ac2c59f3 --- /dev/null +++ b/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.rs @@ -0,0 +1,17 @@ +impl Solution { + pub fn can_arrange(arr: Vec, k: i32) -> bool { + let mut a: Vec = arr.iter().map(|&v| ((v % k) + k) % k).collect(); + a.sort(); + let j = a.iter().take_while(|&&x| x == 0).count(); + if j % 2 != 0 { + return false; + } + let b = &a[j..]; + for l in 0..b.len() / 2 { + if (b[l] + b[b.len() - 1 - l]) % k != 0 { + return false; + } + } + true + } +} diff --git a/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.swift b/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.swift new file mode 100644 index 00000000..6f7a89a0 --- /dev/null +++ b/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.swift @@ -0,0 +1,14 @@ +class Solution { + func canArrange(_ arr: [Int], _ k: Int) -> Bool { + var a = arr.map { (($0 % k) + k) % k }.sorted() + let j = a.prefix(while: { $0 == 0 }).count + if j % 2 != 0 { return false } + let b = Array(a[j...]) + for l in 0..<(b.count / 2) { + if (b[l] + b[b.count - 1 - l]) % k != 0 { + return false + } + } + return true + } +} diff --git a/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.ts b/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.ts new file mode 100644 index 00000000..76914c73 --- /dev/null +++ b/tests/1001-1500/1497. check-if-array-pairs-are-divisible-by-k/sol.ts @@ -0,0 +1,11 @@ +function canArrange(arr: number[], k: number): boolean { + const a = arr.map((v) => ((v % k) + k) % k).sort((x, y) => x - y); + let j = 0; + while (j < a.length && a[j] === 0) j++; + if (j % 2 !== 0) return false; + const b = a.slice(j); + for (let l = 0, r = b.length - 1; l < r; l++, r--) { + if ((b[l] + b[r]) % k !== 0) return false; + } + return true; +} diff --git a/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/manifest.yaml b/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/manifest.yaml new file mode 100644 index 00000000..2c2095a1 --- /dev/null +++ b/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/manifest.yaml @@ -0,0 +1,367 @@ +entry: + id: 1498 + title: "number-of-subsequences-that-satisfy-the-given-sum-condition" + params: + nums: + type: array + items: + type: int + target: + type: int + call: + cpp: "Solution().numSubseq({nums}, {target})" + rust: "Solution::num_subseq({nums}, {target})" + python3: "Solution().numSubseq({nums}, {target})" + python2: "Solution().numSubseq({nums}, {target})" + ruby: "num_subseq({nums}, {target})" + java: "new Solution().numSubseq({nums}, {target})" + csharp: "new Solution().NumSubseq({nums}, {target})" + kotlin: "Solution().numSubseq({nums}, {target})" + go: "numSubseq({nums}, {target})" + dart: "Solution().numSubseq({nums}, {target})" + swift: "Solution().numSubseq({nums}, {target})" + typescript: "numSubseq({nums}, {target})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().numSubseq(nums, target, {result})" + checker: | + class Checker: + def numSubseq(self, nums, target, result): + mod = 10 ** 9 + 7 + if len(nums) <= 20: + expected = 0 + for mask in range(1, 1 << len(nums)): + chosen = [nums[index] for index in range(len(nums)) if mask & (1 << index)] + if min(chosen) + max(chosen) <= target: + expected += 1 + expected %= mod + else: + values = sorted(nums) + powers = [1] * len(values) + for index in range(1, len(values)): + powers[index] = (powers[index - 1] * 2) % mod + expected = 0 + for right, maximum in enumerate(values): + limit = target - maximum + low, high = 0, right + while low < high: + middle = (low + high) // 2 + if values[middle] <= limit: + low = middle + 1 + else: + high = middle + low_count = low + valid_with_smaller_min = powers[right] - powers[right - low_count] + if 2 * maximum <= target: + valid_with_smaller_min += 1 + expected = (expected + valid_with_smaller_min) % mod + return result == expected + +seed: 1498 + +tests: + - name: "example-one" + in: + nums: [3, 5, 6, 7] + target: 9 + out: 4 + - name: "example-two" + in: + nums: [3, 3, 6, 8] + target: 10 + out: 6 + - name: "example-three" + in: + nums: [2, 3, 3, 4, 6, 7] + target: 12 + out: 61 + - name: "single-valid" + in: + nums: [5] + target: 10 + out: 1 + - name: "single-invalid" + in: + nums: [5] + target: 9 + out: 0 + - name: "two-both-valid" + in: + nums: [1, 2] + target: 5 + out: 3 + - name: "two-none-valid" + in: + nums: [5, 6] + target: 9 + out: 0 + - name: "exact-pair-boundary" + in: + nums: [4, 5] + target: 9 + out: 2 + - name: "duplicate-ones" + in: + nums: [1, 1, 1, 1] + target: 2 + out: 15 + - name: "duplicate-fives" + in: + nums: [5, 5, 5, 5, 5] + target: 10 + out: 31 + - name: "all-valid-small" + in: + nums: [1, 2, 3, 4, 5] + target: 100 + out: 31 + - name: "all-invalid-small" + in: + nums: [10, 20, 30, 40] + target: 15 + out: 0 + - name: "unsorted-input" + in: + nums: [7, 3, 6, 5] + target: 9 + out: 4 + - name: "mixed-duplicates" + in: + nums: [2, 2, 4, 4, 6, 6] + target: 8 + out: 51 + - name: "one-small-many-large" + in: + nums: [1, 100, 100, 100] + target: 101 + out: 8 + - name: "two-small-many-large" + in: + nums: [1, 2, 100, 100] + target: 102 + out: 12 + - name: "threshold-just-below" + in: + nums: [2, 3, 4, 5] + target: 6 + out: 5 + - name: "threshold-just-above" + in: + nums: [2, 3, 4, 5] + target: 7 + out: 10 + - name: "powers-of-two-values" + in: + nums: [1, 2, 4, 8, 16] + target: 17 + out: 23 + - name: "ascending-seven" + in: + nums: [1, 2, 3, 4, 5, 6, 7] + target: 10 + out: 117 + - name: "descending-seven" + in: + nums: [7, 6, 5, 4, 3, 2, 1] + target: 10 + out: 117 + - name: "large-value-single" + in: + nums: [1000000] + target: 2000000 + out: 1 + - name: "large-value-pair" + in: + nums: [999999, 1000000] + target: 1999999 + out: 2 + - name: "large-values-invalid" + in: + nums: [999999, 1000000] + target: 199998 + out: 0 + - name: "ten-equal" + in: + nums: [10, 10, 10, 10, 10, 10, 10, 10, 10, 10] + target: 20 + out: 1023 + - name: "ten-mixed" + in: + nums: [1, 4, 7, 10, 13, 16, 19, 22, 25, 28] + target: 30 + out: 682 + - name: "ten-alternating" + in: + nums: [1, 100, 2, 99, 3, 98, 4, 97, 5, 96] + target: 100 + out: 341 + - name: "fifteen-repeated-blocks" + in: + nums: [2, 2, 2, 5, 5, 5, 8, 8, 8, 11, 11, 11, 14, 14, 14] + target: 16 + out: 29127 + - name: "twenty-all-valid" + in: + nums: + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] + target: 1000 + out: 1048575 + - name: "twenty-all-invalid" + in: + nums: + [ + 100, + 101, + 102, + 103, + 104, + 105, + 106, + 107, + 108, + 109, + 110, + 111, + 112, + 113, + 114, + 115, + 116, + 117, + 118, + 119, + ] + target: 100 + out: 0 + - name: "twenty-five-balanced" + in: + nums: + [ + 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, + ] + target: 50 + out: 22369621 + - name: "thirty-mixed" + in: + nums: + [ + 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, + ] + target: 100 + out: 357913941 + - name: "large-generated-low" + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 1000000 + distinct: false + sorted: false + elemType: "int" + target: 1000001 + - name: "large-generated-high" + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 1000000 + distinct: false + sorted: false + elemType: "int" + target: 2000000 + - name: "exact-min-max-boundary" + in: + nums: [1, 1, 2, 2, 3, 3, 4, 4] + target: 5 + - name: "target-at-minimum" + in: + nums: [1] + target: 1 + out: 0 + - name: "maximum-value-cutoff" + in: + nums: [1, 999999, 1000000] + target: 1000000 + out: 2 + - name: "duplicate-boundary-mix" + in: + nums: [1, 2, 2, 3] + target: 4 + out: 11 + - name: "near-maximum-duplicates" + in: + nums: [500000, 500000, 500001, 500001] + target: 1000000 + out: 3 + - name: "zero-valid-at-large-values" + in: + nums: [999999, 1000000, 1000000] + target: 1000000 + out: 0 diff --git a/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.cpp b/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.cpp new file mode 100644 index 00000000..d425f26c --- /dev/null +++ b/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int numSubseq(vector& nums, int target) { + const int mod = 1000000007; + sort(nums.begin(), nums.end()); + int n = nums.size(); + + vector power(n, 1); + for (int i = 1; i < n; i++) { + power[i] = (power[i - 1] * 2) % mod; + } + + int left = 0, right = n - 1; + int result = 0; + + while (left <= right) { + if (nums[left] + nums[right] <= target) { + result = (result + power[right - left]) % mod; + left++; + } else { + right--; + } + } + + return result; + } +}; diff --git a/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.cs b/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.cs new file mode 100644 index 00000000..b81bf661 --- /dev/null +++ b/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.cs @@ -0,0 +1,27 @@ +public class Solution { + public int NumSubseq(int[] nums, int target) { + const int mod = 1000000007; + Array.Sort(nums); + int n = nums.Length; + + int[] power = new int[n]; + power[0] = 1; + for (int i = 1; i < n; i++) { + power[i] = (power[i - 1] * 2) % mod; + } + + int left = 0, right = n - 1; + int result = 0; + + while (left <= right) { + if (nums[left] + nums[right] <= target) { + result = (result + power[right - left]) % mod; + left++; + } else { + right--; + } + } + + return result; + } +} diff --git a/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.dart b/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.dart new file mode 100644 index 00000000..833222a3 --- /dev/null +++ b/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.dart @@ -0,0 +1,26 @@ +class Solution { + int numSubseq(List nums, int target) { + const int mod = 1000000007; + nums.sort(); + int n = nums.length; + + List power = List.filled(n, 1); + for (int i = 1; i < n; i++) { + power[i] = (power[i - 1] * 2) % mod; + } + + int left = 0, right = n - 1; + int result = 0; + + while (left <= right) { + if (nums[left] + nums[right] <= target) { + result = (result + power[right - left]) % mod; + left++; + } else { + right--; + } + } + + return result; + } +} diff --git a/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.go b/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.go new file mode 100644 index 00000000..82488a01 --- /dev/null +++ b/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.go @@ -0,0 +1,25 @@ +func numSubseq(nums []int, target int) int { + mod := 1000000007 + sort.Ints(nums) + n := len(nums) + + power := make([]int, n) + power[0] = 1 + for i := 1; i < n; i++ { + power[i] = (power[i-1] * 2) % mod + } + + left, right := 0, n-1 + result := 0 + + for left <= right { + if nums[left]+nums[right] <= target { + result = (result + power[right-left]) % mod + left++ + } else { + right-- + } + } + + return result +} diff --git a/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.java b/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.java new file mode 100644 index 00000000..2784d6ca --- /dev/null +++ b/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.java @@ -0,0 +1,27 @@ +class Solution { + public int numSubseq(int[] nums, int target) { + int mod = 1000000007; + Arrays.sort(nums); + int n = nums.length; + + int[] power = new int[n]; + power[0] = 1; + for (int i = 1; i < n; i++) { + power[i] = (power[i - 1] * 2) % mod; + } + + int left = 0, right = n - 1; + int result = 0; + + while (left <= right) { + if (nums[left] + nums[right] <= target) { + result = (result + power[right - left]) % mod; + left++; + } else { + right--; + } + } + + return result; + } +} diff --git a/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.kt b/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.kt new file mode 100644 index 00000000..41a3c523 --- /dev/null +++ b/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.kt @@ -0,0 +1,28 @@ +class Solution { + fun numSubseq(nums: IntArray, target: Int): Int { + val mod = 1000000007 + nums.sort() + val n = nums.size + + val power = IntArray(n) + power[0] = 1 + for (i in 1 until n) { + power[i] = (power[i - 1] * 2) % mod + } + + var left = 0 + var right = n - 1 + var result = 0 + + while (left <= right) { + if (nums[left] + nums[right] <= target) { + result = (result + power[right - left]) % mod + left++ + } else { + right-- + } + } + + return result + } +} diff --git a/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.py b/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.py new file mode 100644 index 00000000..10003fa3 --- /dev/null +++ b/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.py @@ -0,0 +1,21 @@ +class Solution: + def numSubseq(self, nums, target): + mod = 10**9 + 7 + values = sorted(nums) + n = len(values) + + power = [1] * n + for i in range(1, n): + power[i] = (power[i - 1] * 2) % mod + + left, right = 0, n - 1 + result = 0 + + while left <= right: + if values[left] + values[right] <= target: + result = (result + power[right - left]) % mod + left += 1 + else: + right -= 1 + + return result diff --git a/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.py2 b/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.py2 new file mode 100644 index 00000000..58e81632 --- /dev/null +++ b/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.py2 @@ -0,0 +1,26 @@ +class Solution(object): + def numSubseq(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: int + """ + mod = 10**9 + 7 + values = sorted(nums) + n = len(values) + + power = [1] * n + for i in range(1, n): + power[i] = (power[i - 1] * 2) % mod + + left, right = 0, n - 1 + result = 0 + + while left <= right: + if values[left] + values[right] <= target: + result = (result + power[right - left]) % mod + left += 1 + else: + right -= 1 + + return result diff --git a/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.rb b/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.rb new file mode 100644 index 00000000..252790a1 --- /dev/null +++ b/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.rb @@ -0,0 +1,25 @@ +# @param {Integer[]} nums +# @param {Integer} target +# @return {Integer} +def num_subseq(nums, target) + mod = 10**9 + 7 + values = nums.sort + n = values.length + + power = [1] * n + (1...n).each { |i| power[i] = (power[i - 1] * 2) % mod } + + left, right = 0, n - 1 + result = 0 + + while left <= right + if values[left] + values[right] <= target + result = (result + power[right - left]) % mod + left += 1 + else + right -= 1 + end + end + + result +end diff --git a/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.rs b/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.rs new file mode 100644 index 00000000..01f17b87 --- /dev/null +++ b/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.rs @@ -0,0 +1,28 @@ +impl Solution { + pub fn num_subseq(nums: Vec, target: i32) -> i32 { + let modulo: i32 = 1_000_000_007; + let mut values = nums; + values.sort_unstable(); + let n = values.len(); + + let mut power = vec![1; n]; + for i in 1..n { + power[i] = (power[i - 1] * 2) % modulo; + } + + let mut left = 0; + let mut right = n as i32 - 1; + let mut result = 0; + + while left <= right { + if values[left as usize] + values[right as usize] <= target { + result = (result + power[(right - left) as usize]) % modulo; + left += 1; + } else { + right -= 1; + } + } + + result + } +} diff --git a/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.swift b/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.swift new file mode 100644 index 00000000..7aa49435 --- /dev/null +++ b/tests/1001-1500/1498. number-of-subsequences-that-satisfy-the-given-sum-condition/sol.swift @@ -0,0 +1,26 @@ +class Solution { + func numSubseq(_ nums: [Int], _ target: Int) -> Int { + let mod = 1000000007 + var values = nums.sorted() + let n = values.count + + var power = [Int](repeating: 1, count: n) + for i in 1.. a - b); + const n = nums.length; + + const power: number[] = new Array(n); + power[0] = 1; + for (let i = 1; i < n; i++) { + power[i] = (power[i - 1] * 2) % mod; + } + + let left = 0, + right = n - 1; + let result = 0; + + while (left <= right) { + if (nums[left] + nums[right] <= target) { + result = (result + power[right - left]) % mod; + left++; + } else { + right--; + } + } + + return result; +} diff --git a/tests/1001-1500/1499. max-value-of-equation/manifest.yaml b/tests/1001-1500/1499. max-value-of-equation/manifest.yaml new file mode 100644 index 00000000..e1a0a399 --- /dev/null +++ b/tests/1001-1500/1499. max-value-of-equation/manifest.yaml @@ -0,0 +1,549 @@ +entry: + id: 1499 + title: "max-value-of-equation" + params: + points: + type: array + items: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().findMaxValueOfEquation({points}, {k})" + rust: "Solution::find_max_value_of_equation({points}, {k})" + python3: "Solution().findMaxValueOfEquation({points}, {k})" + python2: "Solution().findMaxValueOfEquation({points}, {k})" + ruby: "find_max_value_of_equation({points}, {k})" + java: "new Solution().findMaxValueOfEquation({points}, {k})" + csharp: "new Solution().FindMaxValueOfEquation({points}, {k})" + kotlin: "Solution().findMaxValueOfEquation({points}, {k})" + go: "findMaxValueOfEquation({points}, {k})" + dart: "Solution().findMaxValueOfEquation({points}, {k})" + swift: "Solution().findMaxValueOfEquation({points}, {k})" + typescript: "findMaxValueOfEquation({points}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().findMaxValueOfEquation(points, k, {result})" + checker: | + class Checker: + def findMaxValueOfEquation(self, points, k, result): + expected = None + for i in range(len(points)): + for j in range(i + 1, len(points)): + if points[j][0] - points[i][0] <= k: + value = points[i][1] + points[j][1] + points[j][0] - points[i][0] + expected = value if expected is None else max(expected, value) + return isinstance(result, int) and not isinstance(result, bool) and result == expected + +seed: 1499 + +tests: + - name: "example_one" + in: + points: + elemType: "int" + value: + - [1, 3] + - [2, 0] + - [5, 10] + - [6, -10] + k: 1 + out: 4 + - name: "example_two" + in: + points: + elemType: "int" + value: + - [0, 0] + - [3, 0] + - [9, 2] + k: 3 + out: 3 + - name: "two_points_equal_x_gap" + in: + points: + elemType: "int" + value: + - [0, 5] + - [2, 7] + k: 2 + out: 14 + - name: "two_points_exact_boundary" + in: + points: + elemType: "int" + value: + - [-10, 4] + - [0, 6] + k: 10 + out: 20 + - name: "two_points_negative_y" + in: + points: + elemType: "int" + value: + - [2, -8] + - [5, -3] + k: 3 + out: -8 + - name: "best_first_pair_boundary" + in: + points: + elemType: "int" + value: + - [0, 3] + - [1, 0] + - [5, -100] + k: 1 + - name: "best_later_pair" + in: + points: + elemType: "int" + value: + - [0, -50] + - [1, -40] + - [2, 100] + - [3, 100] + k: 3 + - name: "k_zero_adjacent_only" + in: + points: + elemType: "int" + value: + - [0, 1] + - [1, 50] + - [2, -1] + k: 1 + - name: "large_k_all_pairs" + in: + points: + elemType: "int" + value: + - [-5, 1] + - [0, 2] + - [8, 3] + - [20, 4] + k: 100 + - name: "negative_x_values" + in: + points: + elemType: "int" + value: + - [-20, 5] + - [-15, 7] + - [-10, -2] + - [-1, 8] + k: 10 + - name: "descending_y" + in: + points: + elemType: "int" + value: + - [0, 100] + - [2, 50] + - [4, 0] + - [6, -50] + k: 6 + - name: "ascending_y" + in: + points: + elemType: "int" + value: + - [0, -100] + - [1, -10] + - [2, 0] + - [3, 10] + - [4, 100] + k: 4 + - name: "sliding_window_expiration" + in: + points: + elemType: "int" + value: + - [0, 100] + - [2, -100] + - [4, -100] + - [6, 100] + k: 2 + - name: "equal_y_values" + in: + points: + elemType: "int" + value: + - [1, 4] + - [3, 4] + - [6, 4] + - [10, 4] + k: 5 + - name: "repeated_x_gaps_one" + in: + points: + elemType: "int" + value: + - [0, 0] + - [1, 1] + - [2, 2] + - [3, 3] + - [4, 4] + k: 1 + - name: "wide_gaps_small_k" + in: + points: + elemType: "int" + value: + - [0, 1] + - [10, 20] + - [20, 30] + - [30, 40] + k: 10 + - name: "wide_gaps_large_k" + in: + points: + elemType: "int" + value: + - [0, 1] + - [10, 20] + - [20, 30] + - [30, 40] + k: 30 + - name: "six_point_mixed" + in: + points: + elemType: "int" + value: + - [-8, 12] + - [-3, -4] + - [0, 15] + - [4, 1] + - [9, 22] + - [15, -10] + k: 9 + - name: "six_point_tight_window" + in: + points: + elemType: "int" + value: + - [1, 1] + - [2, 20] + - [4, 3] + - [7, 40] + - [8, -5] + - [12, 30] + k: 1 + - name: "seven_point_negative_values" + in: + points: + elemType: "int" + value: + - [-30, -1] + - [-25, -2] + - [-19, -3] + - [-12, -4] + - [-4, -5] + - [5, -6] + - [15, -7] + k: 8 + - name: "eight_point_rising_peaks" + in: + points: + elemType: "int" + value: + - [0, 3] + - [2, -8] + - [5, 12] + - [7, 0] + - [11, 20] + - [14, -3] + - [18, 30] + - [21, 1] + k: 6 + - name: "eight_point_all_in_window" + in: + points: + elemType: "int" + value: + - [100, -10] + - [101, 5] + - [102, -2] + - [103, 7] + - [104, 1] + - [105, 9] + - [106, -4] + - [107, 8] + k: 100 + - name: "large_coordinate_positive" + in: + points: + elemType: "int" + value: + - [99999900, 100000000] + - [99999950, -100000000] + - [100000000, 99999999] + k: 100 + - name: "large_coordinate_negative" + in: + points: + elemType: "int" + value: + - [-100000000, 99999999] + - [-99999900, 100000000] + - [-99800000, -100000000] + k: 100 + - name: "ten_point_alternating" + in: + points: + elemType: "int" + value: + - [0, 50] + - [3, -50] + - [6, 49] + - [9, -49] + - [12, 48] + - [15, -48] + - [18, 47] + - [21, -47] + - [24, 46] + - [27, -46] + k: 6 + - name: "ten_point_irregular_gaps" + in: + points: + elemType: "int" + value: + - [-11, 8] + - [-7, 13] + - [-2, -2] + - [1, 17] + - [9, 0] + - [10, 22] + - [18, -4] + - [25, 19] + - [31, 3] + - [40, 30] + k: 10 + - name: "twelve_point_chain" + in: + points: + elemType: "int" + value: + - [0, 0] + - [1, 3] + - [2, 6] + - [3, 9] + - [4, 12] + - [5, 15] + - [6, 18] + - [7, 21] + - [8, 24] + - [9, 27] + - [10, 30] + - [11, 33] + k: 3 + - name: "twelve_point_sparse" + in: + points: + elemType: "int" + value: + - [0, 100] + - [10, -100] + - [20, 100] + - [30, -100] + - [40, 100] + - [50, -100] + - [60, 100] + - [70, -100] + - [80, 100] + - [90, -100] + - [100, 100] + - [110, -100] + k: 10 + - name: "thirteen_point_window_three" + in: + points: + elemType: "int" + value: + - [2, 5] + - [4, 1] + - [6, 9] + - [8, -3] + - [10, 11] + - [12, 0] + - [14, 7] + - [16, -8] + - [18, 13] + - [20, 2] + - [22, 15] + - [24, -1] + - [26, 17] + k: 3 + - name: "fifteen_point_large_k" + in: + points: + elemType: "int" + value: + - [-14, 1] + - [-12, 4] + - [-9, 8] + - [-5, 2] + - [0, 10] + - [2, -7] + - [5, 11] + - [9, 3] + - [14, 20] + - [20, -5] + - [27, 18] + - [35, 6] + - [44, 25] + - [54, -9] + - [65, 30] + k: 50 + - name: "twenty_point_boundary_k" + in: + points: + 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] + - [16, 17] + - [17, -18] + - [18, 19] + - [19, -20] + k: 1 + - name: "negative_k_not_allowed_boundary_zero" + in: + points: + elemType: "int" + value: + - [-2, 6] + - [-1, 7] + - [0, 8] + k: 1 + - name: "maximum_y_pair" + in: + points: + elemType: "int" + value: + - [-100000000, 100000000] + - [-99999999, 100000000] + k: 1 + - name: "maximum_x_gap" + in: + points: + elemType: "int" + value: + - [-100000000, -1] + - [100000000, -2] + k: 200000000 + - name: "dense_twentyfive" + in: + points: + elemType: "int" + value: + - [0, 4] + - [2, -3] + - [4, 8] + - [6, 1] + - [8, 9] + - [10, -2] + - [12, 7] + - [14, 0] + - [16, 11] + - [18, -5] + - [20, 12] + - [22, 3] + - [24, 13] + - [26, -4] + - [28, 14] + - [30, 2] + - [32, 15] + - [34, -1] + - [36, 16] + - [38, 5] + - [40, 17] + - [42, 6] + - [44, 18] + - [46, 7] + - [48, 19] + k: 8 + - name: "eviction_reveals_next_best" + in: + points: + elemType: "int" + value: + - [0, 100] + - [1, 99] + - [2, -100] + - [3, -99] + - [4, 100] + k: 1 + - name: "equal_optimal_values" + in: + points: + elemType: "int" + value: + - [-4, 8] + - [-2, 6] + - [0, 4] + - [2, 2] + - [4, 0] + k: 4 + - name: "minimum_coordinate_span" + in: + points: + elemType: "int" + value: + - [-100000000, -100000000] + - [-99999999, -99999999] + - [-99999998, -100000000] + k: 1 + - name: "maximum_k_with_mixed_extremes" + in: + points: + elemType: "int" + value: + - [-100000000, 100000000] + - [-50000000, -100000000] + - [0, 99999999] + - [50000000, -99999999] + - [100000000, 100000000] + k: 200000000 + - name: "dense_window_peak_moves" + in: + points: + elemType: "int" + value: + - [10, -20] + - [11, 30] + - [12, -10] + - [13, 25] + - [14, -5] + - [15, 40] + - [16, 0] + - [17, 35] + - [18, 5] + - [19, 50] + k: 3 diff --git a/tests/1001-1500/1499. max-value-of-equation/sol.cpp b/tests/1001-1500/1499. max-value-of-equation/sol.cpp new file mode 100644 index 00000000..13c5df82 --- /dev/null +++ b/tests/1001-1500/1499. max-value-of-equation/sol.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int findMaxValueOfEquation(vector>& points, int k) { + deque> window; + int answer = INT_MIN; + for (auto& point : points) { + int x = point[0]; + int y = point[1]; + while (!window.empty() && x - window.front().second > k) { + window.pop_front(); + } + if (!window.empty()) { + answer = max(answer, x + y + window.front().first); + } + int value = y - x; + while (!window.empty() && window.back().first <= value) { + window.pop_back(); + } + window.push_back({value, x}); + } + return answer; + } +}; diff --git a/tests/1001-1500/1499. max-value-of-equation/sol.cs b/tests/1001-1500/1499. max-value-of-equation/sol.cs new file mode 100644 index 00000000..f4d21438 --- /dev/null +++ b/tests/1001-1500/1499. max-value-of-equation/sol.cs @@ -0,0 +1,22 @@ +public class Solution { + public int FindMaxValueOfEquation(int[][] points, int k) { + var window = new System.Collections.Generic.LinkedList<(int value, int x)>(); + int answer = int.MinValue; + foreach (var point in points) { + int x = point[0]; + int y = point[1]; + while (window.Count > 0 && x - window.First.Value.x > k) { + window.RemoveFirst(); + } + if (window.Count > 0) { + answer = Math.Max(answer, x + y + window.First.Value.value); + } + int value = y - x; + while (window.Count > 0 && window.Last.Value.value <= value) { + window.RemoveLast(); + } + window.AddLast((value, x)); + } + return answer; + } +} diff --git a/tests/1001-1500/1499. max-value-of-equation/sol.dart b/tests/1001-1500/1499. max-value-of-equation/sol.dart new file mode 100644 index 00000000..f84cfc73 --- /dev/null +++ b/tests/1001-1500/1499. max-value-of-equation/sol.dart @@ -0,0 +1,25 @@ +class Solution { + int findMaxValueOfEquation(List> points, int k) { + var window = >[]; + var answer = -1000000000000000000; + for (var point in points) { + var x = point[0]; + var y = point[1]; + while (window.isNotEmpty && x - window.first[1] > k) { + window.removeAt(0); + } + if (window.isNotEmpty) { + var current = x + y + window.first[0]; + if (current > answer) { + answer = current; + } + } + var value = y - x; + while (window.isNotEmpty && window.last[0] <= value) { + window.removeLast(); + } + window.add([value, x]); + } + return answer; + } +} diff --git a/tests/1001-1500/1499. max-value-of-equation/sol.go b/tests/1001-1500/1499. max-value-of-equation/sol.go new file mode 100644 index 00000000..944dc237 --- /dev/null +++ b/tests/1001-1500/1499. max-value-of-equation/sol.go @@ -0,0 +1,25 @@ +func findMaxValueOfEquation(points [][]int, k int) int { + type pair struct { + value int + x int + } + window := make([]pair, 0) + answer := -1 << 60 + for _, point := range points { + x, y := point[0], point[1] + for len(window) > 0 && x - window[0].x > k { + window = window[1:] + } + if len(window) > 0 { + if x + y + window[0].value > answer { + answer = x + y + window[0].value + } + } + value := y - x + for len(window) > 0 && window[len(window)-1].value <= value { + window = window[:len(window)-1] + } + window = append(window, pair{value, x}) + } + return answer +} diff --git a/tests/1001-1500/1499. max-value-of-equation/sol.java b/tests/1001-1500/1499. max-value-of-equation/sol.java new file mode 100644 index 00000000..cbae601b --- /dev/null +++ b/tests/1001-1500/1499. max-value-of-equation/sol.java @@ -0,0 +1,22 @@ +class Solution { + public int findMaxValueOfEquation(int[][] points, int k) { + java.util.Deque window = new java.util.ArrayDeque<>(); + int answer = Integer.MIN_VALUE; + for (int[] point : points) { + int x = point[0]; + int y = point[1]; + while (!window.isEmpty() && x - window.peekFirst()[1] > k) { + window.pollFirst(); + } + if (!window.isEmpty()) { + answer = Math.max(answer, x + y + window.peekFirst()[0]); + } + int value = y - x; + while (!window.isEmpty() && window.peekLast()[0] <= value) { + window.pollLast(); + } + window.offerLast(new int[]{value, x}); + } + return answer; + } +} diff --git a/tests/1001-1500/1499. max-value-of-equation/sol.kt b/tests/1001-1500/1499. max-value-of-equation/sol.kt new file mode 100644 index 00000000..5ec47e1c --- /dev/null +++ b/tests/1001-1500/1499. max-value-of-equation/sol.kt @@ -0,0 +1,22 @@ +class Solution { + fun findMaxValueOfEquation(points: Array, k: Int): Int { + val window = ArrayDeque() + var answer = Int.MIN_VALUE + for (point in points) { + val x = point[0] + val y = point[1] + while (window.isNotEmpty() && x - window.first()[1] > k) { + window.removeFirst() + } + if (window.isNotEmpty()) { + answer = maxOf(answer, x + y + window.first()[0]) + } + val value = y - x + while (window.isNotEmpty() && window.last()[0] <= value) { + window.removeLast() + } + window.addLast(intArrayOf(value, x)) + } + return answer + } +} diff --git a/tests/1001-1500/1499. max-value-of-equation/sol.py b/tests/1001-1500/1499. max-value-of-equation/sol.py new file mode 100644 index 00000000..1eb991c2 --- /dev/null +++ b/tests/1001-1500/1499. max-value-of-equation/sol.py @@ -0,0 +1,19 @@ +from typing import List + + +class Solution: + def findMaxValueOfEquation(self, points: List[List[int]], k: int) -> int: + from collections import deque + + window = deque() + answer = -(10**30) + for x, y in points: + while window and x - window[0][1] > k: + window.popleft() + if window: + answer = max(answer, x + y + window[0][0]) + value = y - x + while window and window[-1][0] <= value: + window.pop() + window.append((value, x)) + return answer diff --git a/tests/1001-1500/1499. max-value-of-equation/sol.py2 b/tests/1001-1500/1499. max-value-of-equation/sol.py2 new file mode 100644 index 00000000..dd92ffce --- /dev/null +++ b/tests/1001-1500/1499. max-value-of-equation/sol.py2 @@ -0,0 +1,20 @@ +class Solution(object): + def findMaxValueOfEquation(self, points, k): + """ + :type points: List[List[int]] + :type k: int + :rtype: int + """ + from collections import deque + window = deque() + answer = -10**30 + for x, y in points: + while window and x - window[0][1] > k: + window.popleft() + if window: + answer = max(answer, x + y + window[0][0]) + value = y - x + while window and window[-1][0] <= value: + window.pop() + window.append((value, x)) + return answer diff --git a/tests/1001-1500/1499. max-value-of-equation/sol.rb b/tests/1001-1500/1499. max-value-of-equation/sol.rb new file mode 100644 index 00000000..daaacad2 --- /dev/null +++ b/tests/1001-1500/1499. max-value-of-equation/sol.rb @@ -0,0 +1,21 @@ +# @param {Integer[][]} points +# @param {Integer} k +# @return {Integer} +def find_max_value_of_equation(points, k) + window = [] + answer = -10**30 + points.each do |x, y| + while !window.empty? && x - window[0][1] > k + window.shift + end + if !window.empty? + answer = [answer, x + y + window[0][0]].max + end + value = y - x + while !window.empty? && window[-1][0] <= value + window.pop + end + window << [value, x] + end + answer +end diff --git a/tests/1001-1500/1499. max-value-of-equation/sol.rs b/tests/1001-1500/1499. max-value-of-equation/sol.rs new file mode 100644 index 00000000..547f5111 --- /dev/null +++ b/tests/1001-1500/1499. max-value-of-equation/sol.rs @@ -0,0 +1,29 @@ +impl Solution { + pub fn find_max_value_of_equation(points: Vec>, k: i32) -> i32 { + use std::collections::VecDeque; + let mut window: VecDeque<(i32, i32)> = VecDeque::new(); + let mut answer = i32::MIN; + for point in &points { + let x = point[0]; + let y = point[1]; + while let Some(&(_, front_x)) = window.front() { + if x - front_x <= k { + break; + } + window.pop_front(); + } + if let Some(&(front_val, _)) = window.front() { + answer = answer.max(x + y + front_val); + } + let value = y - x; + while let Some(&(back_val, _)) = window.back() { + if back_val > value { + break; + } + window.pop_back(); + } + window.push_back((value, x)); + } + answer + } +} diff --git a/tests/1001-1500/1499. max-value-of-equation/sol.swift b/tests/1001-1500/1499. max-value-of-equation/sol.swift new file mode 100644 index 00000000..2d88351b --- /dev/null +++ b/tests/1001-1500/1499. max-value-of-equation/sol.swift @@ -0,0 +1,22 @@ +class Solution { + func findMaxValueOfEquation(_ points: [[Int]], _ k: Int) -> Int { + var window = [(Int, Int)]() + var answer = Int.min + for point in points { + let x = point[0] + let y = point[1] + while !window.isEmpty && x - window[0].1 > k { + window.removeFirst() + } + if !window.isEmpty { + answer = max(answer, x + y + window[0].0) + } + let value = y - x + while !window.isEmpty && window.last!.0 <= value { + window.removeLast() + } + window.append((value, x)) + } + return answer + } +} diff --git a/tests/1001-1500/1499. max-value-of-equation/sol.ts b/tests/1001-1500/1499. max-value-of-equation/sol.ts new file mode 100644 index 00000000..e490d734 --- /dev/null +++ b/tests/1001-1500/1499. max-value-of-equation/sol.ts @@ -0,0 +1,18 @@ +function findMaxValueOfEquation(points: number[][], k: number): number { + const window: [number, number][] = []; + let answer = -Infinity; + for (const [x, y] of points) { + while (window.length && x - window[0][1] > k) { + window.shift(); + } + if (window.length) { + answer = Math.max(answer, x + y + window[0][0]); + } + const value = y - x; + while (window.length && window[window.length - 1][0] <= value) { + window.pop(); + } + window.push([value, x]); + } + return answer; +} diff --git a/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/manifest.yaml b/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/manifest.yaml new file mode 100644 index 00000000..3b559304 --- /dev/null +++ b/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/manifest.yaml @@ -0,0 +1,210 @@ +entry: + id: 1502 + title: "can-make-arithmetic-progression-from-sequence" + params: + arr: + type: array + items: + type: int + call: + cpp: "Solution().canMakeArithmeticProgression({arr})" + rust: "Solution::can_make_arithmetic_progression({arr})" + python3: "Solution().canMakeArithmeticProgression({arr})" + python2: "Solution().canMakeArithmeticProgression({arr})" + ruby: "can_make_arithmetic_progression({arr})" + java: "new Solution().canMakeArithmeticProgression({arr})" + csharp: "new Solution().CanMakeArithmeticProgression({arr})" + kotlin: "Solution().canMakeArithmeticProgression({arr})" + go: "canMakeArithmeticProgression({arr})" + dart: "Solution().canMakeArithmeticProgression({arr})" + swift: "Solution().canMakeArithmeticProgression({arr})" + typescript: "canMakeArithmeticProgression({arr})" +judge: + type: exact +limits: + time_ms: 300 + memory_mb: 300 +oracle: + python3: + call: "Checker().canMakeArithmeticProgression(arr, {result})" + checker: | + class Checker: + def canMakeArithmeticProgression(self, arr, result): + values = sorted(arr) + step = values[1] - values[0] + expected = all(values[i] - values[i - 1] == step for i in range(2, len(values))) + return result == expected +seed: 1502 +tests: + - name: ex1 + in: + arr: [3, 5, 1] + out: true + - name: ex2 + in: + arr: [1, 2, 4] + out: false + - name: equal_three + in: + arr: [7, 7, 7] + out: true + - name: equal_many + in: + arr: [0, 0, 0, 0, 0, 0] + out: true + - name: descending_step + in: + arr: [10, 4, 7, 1] + out: true + - name: negative_step + in: + arr: [-2, -8, -5, -11] + out: true + - name: negative_values + in: + arr: [-9, -3, -15, -6, -12] + out: true + - name: crosses_zero + in: + arr: [6, -2, 2, -6, -10] + out: true + - name: unit_step + in: + arr: [5, 2, 4, 3, 1] + out: true + - name: large_step + in: + arr: [1000000, -1000000, 0] + out: true + - name: duplicate_break + in: + arr: [1, 3, 3, 5] + out: false + - name: one_gap + in: + arr: [0, 2, 4, 9] + out: false + - name: uneven_gaps + in: + arr: [2, 8, 14, 21] + out: false + - name: shuffled_five + in: + arr: [14, 2, 8, 20, 26] + out: true + - name: step_two + in: + arr: [12, 4, 10, 2, 8, 6] + out: true + - name: step_three + in: + arr: [18, 3, 12, 9, 0, 15, 6] + out: true + - name: step_negative_four + in: + arr: [-4, -16, -8, -12, 0] + out: true + - name: short_false + in: + arr: [2, 5, 9] + out: false + - name: short_true + in: + arr: [8, 2, 5] + out: true + - name: min_boundaries + in: + arr: [-1000000, 0, 1000000] + out: true + - name: min_bound_false + in: + arr: [-1000000, -999999, 1000000] + out: false + - name: max_boundaries + in: + arr: [1000000, 999998, 999999] + out: true + - name: four_duplicates + in: + arr: [4, 4, 4, 4] + out: true + - name: repeated_middle + in: + arr: [0, 5, 10, 10, 15] + out: false + - name: repeated_endpoint + in: + arr: [0, 0, 5, 10, 15] + out: false + - name: prime_spaced + in: + arr: [29, 17, 23, 11, 5] + out: true + - name: powers_false + in: + arr: [1, 2, 4, 8, 16] + out: false + - name: squares_false + in: + arr: [1, 4, 9, 16, 25] + out: false + - name: wide_negative + in: + arr: [-100, -50, 0, 50, 100] + out: true + - name: wide_negative_shuffled + in: + arr: [100, 0, -100, 50, -50] + out: true + - name: six_false + in: + arr: [3, 8, 13, 18, 24, 28] + out: false + - name: seven_true + in: + arr: [42, 6, 30, 18, 12, 36, 24] + out: true + - name: eight_true + in: + arr: [9, -12, 2, -5, 16, -19, 23, -26] + out: true + - name: eight_false + in: + arr: [9, -12, 2, -5, 16, -19, 24, -26] + out: false + - name: large_values_false + in: + arr: [-1000000, -500000, 0, 500000, 999999] + out: false + - name: generated_random_a + in: + arr: + gen: array + len: 1000 + of: + gen: int + min: -1000000 + max: 1000000 + elemType: int + - name: generated_random_b + in: + arr: + gen: array + len: 997 + of: + gen: int + min: -1000000 + max: 1000000 + elemType: int + - name: max_three_unit_step + in: + arr: [1000000, 999998, 999999] + out: true + - name: duplicate_far_apart_false + in: + arr: [-1000000, -500000, 0, 0, 500000, 1000000] + out: false + - name: near_boundary_gap_false + in: + arr: [-1000000, -999998, -999996, -999995] + out: false diff --git a/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.cpp b/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.cpp new file mode 100644 index 00000000..b2d29002 --- /dev/null +++ b/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + bool canMakeArithmeticProgression(vector& arr) { + sort(arr.begin(), arr.end()); + int diff = arr[1] - arr[0]; + for (int i = 0; i < arr.size() - 1; i++) { + if (arr[i+1] - arr[i] != diff) { + return false; + } + } + return true; + } +}; diff --git a/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.cs b/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.cs new file mode 100644 index 00000000..0bc21a10 --- /dev/null +++ b/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.cs @@ -0,0 +1,12 @@ +public class Solution { + public bool CanMakeArithmeticProgression(int[] arr) { + Array.Sort(arr); + int diff = arr[1] - arr[0]; + for (int i = 0; i < arr.Length - 1; i++) { + if (arr[i+1] - arr[i] != diff) { + return false; + } + } + return true; + } +} diff --git a/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.dart b/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.dart new file mode 100644 index 00000000..77a0021a --- /dev/null +++ b/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.dart @@ -0,0 +1,12 @@ +class Solution { + bool canMakeArithmeticProgression(List arr) { + arr.sort(); + int diff = arr[1] - arr[0]; + for (int i = 0; i < arr.length - 1; i++) { + if (arr[i+1] - arr[i] != diff) { + return false; + } + } + return true; + } +} diff --git a/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.go b/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.go new file mode 100644 index 00000000..912922d6 --- /dev/null +++ b/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.go @@ -0,0 +1,10 @@ +func canMakeArithmeticProgression(arr []int) bool { + sort.Ints(arr) + diff := arr[1] - arr[0] + for i := 0; i < len(arr)-1; i++ { + if arr[i+1]-arr[i] != diff { + return false + } + } + return true +} diff --git a/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.java b/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.java new file mode 100644 index 00000000..6337f152 --- /dev/null +++ b/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.java @@ -0,0 +1,12 @@ +class Solution { + public boolean canMakeArithmeticProgression(int[] arr) { + Arrays.sort(arr); + int diff = arr[1] - arr[0]; + for (int i = 0; i < arr.length - 1; i++) { + if (arr[i+1] - arr[i] != diff) { + return false; + } + } + return true; + } +} diff --git a/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.kt b/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.kt new file mode 100644 index 00000000..69e7b2dd --- /dev/null +++ b/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.kt @@ -0,0 +1,12 @@ +class Solution { + fun canMakeArithmeticProgression(arr: IntArray): Boolean { + arr.sort() + val diff = arr[1] - arr[0] + for (i in 0 until arr.size - 1) { + if (arr[i+1] - arr[i] != diff) { + return false + } + } + return true + } +} diff --git a/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.py b/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.py new file mode 100644 index 00000000..88d088c1 --- /dev/null +++ b/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.py @@ -0,0 +1,13 @@ +class Solution(object): + def canMakeArithmeticProgression(self, arr): + """ + :type arr: List[int] + :rtype: bool + """ + arr.sort() + li = arr[1] - arr[0] + for i in range(len(arr) - 1): + m = arr[i + 1] - arr[i] + if li != m: + return False + return True diff --git a/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.py2 b/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.py2 new file mode 100644 index 00000000..6e90d2b3 --- /dev/null +++ b/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.py2 @@ -0,0 +1,13 @@ +class Solution(object): + def canMakeArithmeticProgression(self, arr): + """ + :type arr: List[int] + :rtype: bool + """ + arr.sort() + li=arr[1]-arr[0] + for i in range(len(arr)-1): + m=arr[i+1]-arr[i] + if li != m: + return False + return True diff --git a/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.rb b/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.rb new file mode 100644 index 00000000..a788abab --- /dev/null +++ b/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.rb @@ -0,0 +1,10 @@ +# @param {Integer[]} arr +# @return {Boolean} +def can_make_arithmetic_progression(arr) + arr.sort! + diff = arr[1] - arr[0] + (0...arr.length - 1).each do |i| + return false if arr[i+1] - arr[i] != diff + end + true +end diff --git a/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.rs b/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.rs new file mode 100644 index 00000000..976ff652 --- /dev/null +++ b/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.rs @@ -0,0 +1,13 @@ +impl Solution { + pub fn can_make_arithmetic_progression(arr: Vec) -> bool { + let mut arr = arr; + arr.sort(); + let diff = arr[1] - arr[0]; + for i in 0..arr.len() - 1 { + if arr[i+1] - arr[i] != diff { + return false; + } + } + true + } +} diff --git a/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.swift b/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.swift new file mode 100644 index 00000000..3516fcb3 --- /dev/null +++ b/tests/1501-2000/1502. can-make-arithmetic-progression-from-sequence/sol.swift @@ -0,0 +1,12 @@ +class Solution { + func canMakeArithmeticProgression(_ arr: [Int]) -> Bool { + let sorted = arr.sorted() + let diff = sorted[1] - sorted[0] + for i in 0.. a - b); + const diff = arr[1] - arr[0]; + for (let i = 0; i < arr.length - 1; i++) { + if (arr[i + 1] - arr[i] !== diff) { + return false; + } + } + return true; +} diff --git a/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/manifest.yaml b/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/manifest.yaml new file mode 100644 index 00000000..7a4c3683 --- /dev/null +++ b/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/manifest.yaml @@ -0,0 +1,395 @@ +entry: + id: 1503 + title: "last-moment-before-all-ants-fall-out-of-a-plank" + params: + n: + type: int + left: + type: array + items: + type: int + right: + type: array + items: + type: int + call: + cpp: "Solution().getLastMoment({n}, {left}, {right})" + rust: "Solution::get_last_moment({n}, {left}, {right})" + python3: "Solution().getLastMoment({n}, {left}, {right})" + python2: "Solution().getLastMoment({n}, {left}, {right})" + ruby: "get_last_moment({n}, {left}, {right})" + java: "new Solution().getLastMoment({n}, {left}, {right})" + csharp: "new Solution().GetLastMoment({n}, {left}, {right})" + kotlin: "Solution().getLastMoment({n}, {left}, {right})" + go: "getLastMoment({n}, {left}, {right})" + dart: "Solution().getLastMoment({n}, {left}, {right})" + swift: "Solution().getLastMoment({n}, {left}, {right})" + typescript: "getLastMoment({n}, {left}, {right})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().getLastMoment(n, left, right, {result})" + checker: | + class Checker: + def getLastMoment(self, n, left, right, result): + expected = max([0] + list(left) + [n - x for x in right]) + return result == expected + +seed: 1503 + +tests: + - name: "example_mixed" + in: + n: 4 + left: [4, 3] + right: [0, 1] + out: 4 + - name: "example_all_right" + in: + n: 7 + left: [] + right: [0, 1, 2, 3, 4, 5, 6, 7] + out: 7 + - name: "example_all_left" + in: + n: 7 + left: [0, 1, 2, 3, 4, 5, 6, 7] + right: [] + out: 7 + - name: "single_left_at_zero" + in: + n: 1 + left: [0] + right: [] + out: 0 + - name: "single_right_at_zero" + in: + n: 1 + left: [] + right: [0] + out: 1 + - name: "single_left_at_end" + in: + n: 1 + left: [1] + right: [] + out: 1 + - name: "single_right_at_end" + in: + n: 1 + left: [] + right: [1] + out: 0 + - name: "both_endpoints" + in: + n: 9 + left: [9] + right: [0] + out: 9 + - name: "left_near_end" + in: + n: 10 + left: [9] + right: [] + out: 9 + - name: "right_near_end" + in: + n: 10 + left: [] + right: [1] + out: 9 + - name: "left_near_zero" + in: + n: 10 + left: [1] + right: [] + out: 1 + - name: "right_near_zero" + in: + n: 10 + left: [] + right: [9] + out: 1 + - name: "mixed_left_dominates" + in: + n: 12 + left: [2, 7, 11] + right: [1, 5, 10] + out: 11 + - name: "mixed_right_dominates" + in: + n: 12 + left: [1, 4, 8] + right: [0, 2, 3] + out: 12 + - name: "balanced_middle" + in: + n: 20 + left: [5, 10] + right: [8, 15] + out: 12 + - name: "interleaved_positions" + in: + n: 20 + left: [2, 11, 18] + right: [1, 9, 19] + out: 19 + - name: "all_positions_left_except_one" + in: + n: 5 + left: [0, 1, 2, 3, 4] + right: [5] + out: 4 + - name: "all_positions_right_except_one" + in: + n: 5 + left: [0] + right: [1, 2, 3, 4, 5] + out: 4 + - name: "alternating_directions" + in: + n: 10 + left: [0, 2, 4, 6, 8] + right: [1, 3, 5, 7, 9, 10] + out: 9 + - name: "left_duplicate_values_valid" + in: + n: 100 + left: [3, 4, 5, 50] + right: [1] + out: 99 + - name: "right_duplicate_values_valid" + in: + n: 100 + left: [3] + right: [4, 5, 6, 97] + out: 96 + - name: "generated_large_balanced_partition" + seed: 150301 + in: + n: 10000 + left: + gen: "array" + len: 5000 + of: + gen: "int" + min: 0 + max: 4999 + distinct: true + sorted: false + elemType: "int" + right: + gen: "array" + len: 5001 + of: + gen: "int" + min: 5000 + max: 10000 + distinct: true + sorted: false + elemType: "int" + - name: "generated_large_left_upper_half" + seed: 150302 + in: + n: 10000 + left: + gen: "array" + len: 5000 + of: + gen: "int" + min: 5000 + max: 9999 + distinct: true + sorted: false + elemType: "int" + right: + gen: "array" + len: 5000 + of: + gen: "int" + min: 0 + max: 4999 + distinct: true + sorted: false + elemType: "int" + - name: "generated_large_left_endpoint" + seed: 150303 + in: + n: 10000 + left: + gen: "array" + len: 10000 + of: + gen: "int" + min: 0 + max: 9999 + distinct: true + sorted: false + elemType: "int" + right: + gen: "array" + len: 1 + of: + gen: "int" + min: 10000 + max: 10000 + distinct: true + sorted: false + elemType: "int" + - name: "generated_large_right_endpoint" + seed: 150304 + in: + n: 10000 + left: + gen: "array" + len: 1 + of: + gen: "int" + min: 10000 + max: 10000 + distinct: true + sorted: false + elemType: "int" + right: + gen: "array" + len: 10000 + of: + gen: "int" + min: 0 + max: 9999 + distinct: true + sorted: false + elemType: "int" + - name: "generated_large_left_quarter_right_three_quarters" + seed: 150305 + in: + n: 10000 + left: + gen: "array" + len: 2500 + of: + gen: "int" + min: 0 + max: 4999 + distinct: true + sorted: false + elemType: "int" + right: + gen: "array" + len: 7500 + of: + gen: "int" + min: 5000 + max: 10000 + distinct: true + sorted: false + elemType: "int" + - name: "generated_large_sparse_disjoint_ranges" + seed: 150306 + in: + n: 10000 + left: + gen: "array" + len: 3333 + of: + gen: "int" + min: 0 + max: 3332 + distinct: true + sorted: false + elemType: "int" + right: + gen: "array" + len: 6667 + of: + gen: "int" + min: 3333 + max: 10000 + distinct: true + sorted: false + elemType: "int" + - name: "single_middle_left" + in: + n: 1000 + left: [500] + right: [] + out: 500 + - name: "single_middle_right" + in: + n: 1000 + left: [] + right: [500] + out: 500 + - name: "same_time_opposite" + in: + n: 100 + left: [25, 75] + right: [0, 50] + out: 100 + - name: "right_at_center_and_left_far" + in: + n: 101 + left: [100] + right: [50] + out: 100 + - name: "left_at_center_and_right_far" + in: + n: 101 + left: [50] + right: [1] + out: 100 + - name: "minimum_plank_full" + in: + n: 2 + left: [0, 1] + right: [2] + out: 1 + - name: "minimum_plank_mixed" + in: + n: 2 + left: [2] + right: [0, 1] + out: 2 + - name: "left_only_multiple" + in: + n: 13 + left: [0, 4, 8, 12] + right: [] + out: 12 + - name: "right_only_multiple" + in: + n: 13 + left: [] + right: [0, 4, 8, 12] + out: 13 + - name: "late_left_vs_early_right" + in: + n: 30 + left: [29] + right: [0, 1, 2, 3] + out: 30 + - name: "early_left_vs_late_right" + in: + n: 30 + left: [0, 1, 2, 3] + right: [29] + out: 3 + - name: "dense_mixed_no_endpoints" + in: + n: 16 + left: [1, 3, 5, 7, 9, 11, 13, 15] + right: [2, 4, 6, 8, 10, 12, 14] + out: 15 + - name: "minimum_plank_right_cluster" + in: + n: 2 + left: [0] + right: [1, 2] + out: 1 diff --git a/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.cpp b/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.cpp new file mode 100644 index 00000000..99760898 --- /dev/null +++ b/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + int getLastMoment(int n, vector& left, vector& right) { + int maxVal = 0; + for (int value : left) { + maxVal = max(value, maxVal); + } + for (int value : right) { + maxVal = max(n - value, maxVal); + } + return maxVal; + } +}; diff --git a/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.cs b/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.cs new file mode 100644 index 00000000..724d1670 --- /dev/null +++ b/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.cs @@ -0,0 +1,12 @@ +public class Solution { + public int GetLastMoment(int n, int[] left, int[] right) { + int maxVal = 0; + foreach (int value in left) { + maxVal = Math.Max(value, maxVal); + } + foreach (int value in right) { + maxVal = Math.Max(n - value, maxVal); + } + return maxVal; + } +} diff --git a/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.dart b/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.dart new file mode 100644 index 00000000..c4370c98 --- /dev/null +++ b/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.dart @@ -0,0 +1,16 @@ +class Solution { + int getLastMoment(int n, List left, List right) { + int maxVal = 0; + for (int value in left) { + if (value > maxVal) { + maxVal = value; + } + } + for (int value in right) { + if (n - value > maxVal) { + maxVal = n - value; + } + } + return maxVal; + } +} diff --git a/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.go b/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.go new file mode 100644 index 00000000..3cd730db --- /dev/null +++ b/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.go @@ -0,0 +1,14 @@ +func getLastMoment(n int, left []int, right []int) int { + maxVal := 0 + for _, value := range left { + if value > maxVal { + maxVal = value + } + } + for _, value := range right { + if n-value > maxVal { + maxVal = n - value + } + } + return maxVal +} diff --git a/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.java b/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.java new file mode 100644 index 00000000..1545b220 --- /dev/null +++ b/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.java @@ -0,0 +1,12 @@ +class Solution { + public int getLastMoment(int n, int[] left, int[] right) { + int maxVal = 0; + for (int value : left) { + maxVal = Math.max(value, maxVal); + } + for (int value : right) { + maxVal = Math.max(n - value, maxVal); + } + return maxVal; + } +} diff --git a/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.kt b/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.kt new file mode 100644 index 00000000..797d9507 --- /dev/null +++ b/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.kt @@ -0,0 +1,12 @@ +class Solution { + fun getLastMoment(n: Int, left: IntArray, right: IntArray): Int { + var maxVal = 0 + for (value in left) { + maxVal = maxOf(value, maxVal) + } + for (value in right) { + maxVal = maxOf(n - value, maxVal) + } + return maxVal + } +} diff --git a/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.py b/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.py new file mode 100644 index 00000000..d50a10a6 --- /dev/null +++ b/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.py @@ -0,0 +1,11 @@ +class Solution: + def getLastMoment(self, n: int, left: List[int], right: List[int]) -> int: + max_val = 0 + + for value in left: + max_val = max(value, max_val) + + for value in right: + max_val = max(n - value, max_val) + + return max_val diff --git a/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.py2 b/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.py2 new file mode 100644 index 00000000..3d2567ce --- /dev/null +++ b/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.py2 @@ -0,0 +1,14 @@ +class Solution(object): + def getLastMoment(self, n, left, right): + """ + :type n: int + :type left: List[int] + :type right: List[int] + :rtype: int + """ + max_val = 0 + for value in left: + max_val = max(value, max_val) + for value in right: + max_val = max(n - value, max_val) + return max_val diff --git a/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.rb b/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.rb new file mode 100644 index 00000000..54483c03 --- /dev/null +++ b/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.rb @@ -0,0 +1,14 @@ +# @param {Integer} n +# @param {Integer[]} left +# @param {Integer[]} right +# @return {Integer} +def get_last_moment(n, left, right) + max_val = 0 + left.each do |value| + max_val = [value, max_val].max + end + right.each do |value| + max_val = [n - value, max_val].max + end + max_val +end diff --git a/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.rs b/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.rs new file mode 100644 index 00000000..6e439fec --- /dev/null +++ b/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.rs @@ -0,0 +1,12 @@ +impl Solution { + pub fn get_last_moment(n: i32, left: Vec, right: Vec) -> i32 { + let mut max_val = 0; + for value in left { + max_val = max_val.max(value); + } + for value in right { + max_val = max_val.max(n - value); + } + max_val + } +} diff --git a/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.swift b/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.swift new file mode 100644 index 00000000..2e496cce --- /dev/null +++ b/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.swift @@ -0,0 +1,12 @@ +class Solution { + func getLastMoment(_ n: Int, _ left: [Int], _ right: [Int]) -> Int { + var maxVal = 0 + for value in left { + maxVal = max(value, maxVal) + } + for value in right { + maxVal = max(n - value, maxVal) + } + return maxVal + } +} diff --git a/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.ts b/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.ts new file mode 100644 index 00000000..b7144fac --- /dev/null +++ b/tests/1501-2000/1503. last-moment-before-all-ants-fall-out-of-a-plank/sol.ts @@ -0,0 +1,10 @@ +function getLastMoment(n: number, left: number[], right: number[]): number { + let maxVal = 0; + for (const value of left) { + maxVal = Math.max(value, maxVal); + } + for (const value of right) { + maxVal = Math.max(n - value, maxVal); + } + return maxVal; +} diff --git a/tests/1501-2000/1504. count-submatrices-with-all-ones/manifest.yaml b/tests/1501-2000/1504. count-submatrices-with-all-ones/manifest.yaml new file mode 100644 index 00000000..c7a0d650 --- /dev/null +++ b/tests/1501-2000/1504. count-submatrices-with-all-ones/manifest.yaml @@ -0,0 +1,423 @@ +entry: + id: 1504 + title: "count-submatrices-with-all-ones" + params: + mat: + type: array + items: + type: array + items: + type: int + call: + python3: "Solution().numSubmat({mat})" + python2: "Solution().numSubmat({mat})" + java: "new Solution().numSubmat({mat})" + kotlin: "Solution().numSubmat({mat})" + go: "numSubmat({mat})" + rust: "Solution::num_submat({mat})" + cpp: "Solution().numSubmat({mat})" + csharp: "new Solution().NumSubmat({mat})" + ruby: "num_submat({mat})" + dart: "Solution().numSubmat({mat})" + swift: "Solution().numSubmat({mat})" + typescript: "numSubmat({mat})" +judge: + type: "exact" +limits: + time_ms: 500 + memory_mb: 300 +oracle: + python3: + call: "Checker().numSubmat(mat, {result})" + checker: | + class Checker: + def numSubmat(self, mat, result): + if not isinstance(result, int): + return False + total = 0 + for top in range(len(mat)): + for bottom in range(top, len(mat)): + run = 0 + for j in range(len(mat[0])): + if all(mat[i][j] for i in range(top, bottom + 1)): + run += 1 + total += run + else: + run = 0 + return result == total +seed: 1504 +tests: + - name: "example_one" + in: + mat: + elemType: "int" + value: + - [1, 0, 1] + - [1, 1, 0] + - [1, 1, 0] + out: 13 + - name: "example_two" + in: + mat: + elemType: "int" + value: + - [0, 1, 1, 0] + - [0, 1, 1, 1] + - [1, 1, 1, 0] + out: 24 + - name: "single_zero" + in: + mat: + elemType: "int" + value: + - [0] + out: 0 + - name: "single_one" + in: + mat: + elemType: "int" + value: + - [1] + out: 1 + - name: "zero_row" + in: + mat: + elemType: "int" + value: + - [0, 0, 0] + out: 0 + - name: "one_row_all" + in: + mat: + elemType: "int" + value: + - [1, 1, 1] + out: 6 + - name: "one_column_all" + in: + mat: + elemType: "int" + value: + - [1] + - [1] + - [1] + out: 6 + - name: "alternating_row" + in: + mat: + elemType: "int" + value: + - [1, 0, 1, 0] + out: 2 + - name: "alternating_column" + in: + mat: + elemType: "int" + value: + - [1] + - [0] + - [1] + out: 2 + - name: "two_by_two_all" + in: + mat: + elemType: "int" + value: + - [1, 1] + - [1, 1] + out: 9 + - name: "two_by_two_diagonal" + in: + mat: + elemType: "int" + value: + - [1, 0] + - [0, 1] + out: 2 + - name: "two_by_two_corner" + in: + mat: + elemType: "int" + value: + - [0, 1] + - [1, 1] + out: 5 + - name: "two_rows_all" + in: + mat: + elemType: "int" + value: + - [1, 1, 1] + - [1, 1, 1] + out: 18 + - name: "three_rows_all_two_cols" + in: + mat: + elemType: "int" + value: + - [1, 1] + - [1, 1] + - [1, 1] + out: 18 + - name: "cross_sparse" + in: + mat: + elemType: "int" + value: + - [1, 0, 1] + - [0, 1, 0] + out: 3 + - name: "staggered_three" + in: + mat: + elemType: "int" + value: + - [1, 1, 0] + - [1, 0, 1] + - [0, 1, 1] + out: 10 + - name: "vertical_cross" + in: + mat: + elemType: "int" + value: + - [0, 1, 0] + - [1, 1, 1] + - [0, 1, 0] + out: 11 + - name: "edge_columns" + in: + mat: + elemType: "int" + value: + - [1, 0, 0, 1] + - [1, 1, 0, 1] + out: 8 + - name: "staircase" + in: + mat: + elemType: "int" + value: + - [1, 1, 0, 0] + - [1, 1, 1, 0] + - [0, 1, 1, 1] + out: 22 + - name: "rising_heights" + in: + mat: + elemType: "int" + value: + - [1, 0, 1] + - [1, 0, 1] + - [1, 1, 1] + out: 16 + - name: "wide_middle" + in: + mat: + elemType: "int" + value: + - [1, 1, 1, 1] + - [0, 1, 1, 0] + out: 16 + - name: "mixed_four" + in: + mat: + elemType: "int" + value: + - [1, 0, 1, 1] + - [1, 1, 1, 0] + - [1, 1, 0, 1] + out: 20 + - name: "dense_bottom" + in: + mat: + elemType: "int" + value: + - [0, 0, 1] + - [1, 1, 1] + - [1, 1, 1] + out: 21 + - name: "hole_center" + in: + mat: + elemType: "int" + value: + - [1, 1, 1] + - [1, 0, 1] + - [1, 1, 1] + out: 20 + - name: "wide_single_run" + in: + mat: + elemType: "int" + value: + - [1, 1, 0, 1, 1] + out: 6 + - name: "single_column_gap" + in: + mat: + elemType: "int" + value: + - [1] + - [1] + - [0] + - [1] + out: 4 + - name: "two_row_dense" + in: + mat: + elemType: "int" + value: + - [1, 0, 1, 0, 1] + - [1, 1, 1, 1, 1] + out: 21 + - name: "four_by_four_mixed" + in: + mat: + elemType: "int" + value: + - [1, 1, 1, 0] + - [0, 1, 1, 1] + - [1, 1, 1, 1] + - [1, 0, 1, 1] + out: 46 + - name: "three_by_five_mixed" + in: + mat: + elemType: "int" + value: + - [0, 1, 1, 1, 0] + - [1, 1, 0, 1, 1] + - [1, 1, 1, 1, 1] + out: 37 + - name: "one_row_five" + in: + mat: + elemType: "int" + value: + - [1, 1, 1, 1, 1] + out: 15 + - name: "one_column_five" + in: + mat: + elemType: "int" + value: + - [1] + - [1] + - [1] + - [1] + - [1] + out: 15 + - name: "three_by_three_all" + in: + mat: + elemType: "int" + value: + - [1, 1, 1] + - [1, 1, 1] + - [1, 1, 1] + out: 36 + - name: "four_row_checker" + in: + mat: + elemType: "int" + value: + - [0, 1] + - [1, 1] + - [1, 0] + - [1, 1] + out: 12 + - name: "lower_triangle" + in: + mat: + elemType: "int" + value: + - [1, 0, 0] + - [1, 1, 0] + - [1, 1, 1] + - [0, 1, 1] + out: 22 + - name: "upper_right_dense" + in: + mat: + elemType: "int" + value: + - [1, 1, 0, 1] + - [1, 1, 1, 1] + - [0, 1, 1, 1] + out: 32 + - name: "generated_max_width" + seed: 150401 + in: + mat: + gen: "array" + len: 1 + elemType: "int" + of: + gen: "array" + len: 150 + elemType: "int" + of: + gen: "int" + min: 0 + max: 1 + - name: "generated_max_height" + seed: 150402 + in: + mat: + gen: "array" + len: 150 + elemType: "int" + of: + gen: "array" + len: 1 + elemType: "int" + of: + gen: "int" + min: 0 + max: 1 + - name: "generated_max_square_a" + seed: 150403 + in: + mat: + gen: "array" + len: 150 + elemType: "int" + of: + gen: "array" + len: 150 + elemType: "int" + of: + gen: "int" + min: 0 + max: 1 + - name: "generated_max_square_b" + seed: 150404 + in: + mat: + gen: "array" + len: 150 + elemType: "int" + of: + gen: "array" + len: 150 + elemType: "int" + of: + gen: "int" + min: 0 + max: 1 + - name: "generated_near_max_rectangle" + seed: 150405 + in: + mat: + gen: "array" + len: 149 + elemType: "int" + of: + gen: "array" + len: 150 + elemType: "int" + of: + gen: "int" + min: 0 + max: 1 diff --git a/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.cpp b/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.cpp new file mode 100644 index 00000000..ce16b717 --- /dev/null +++ b/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + int numSubmat(vector>& mat) { + int r = mat.size(); + int c = mat[0].size(); + vector h(c, 0); + int ans = 0; + + for (int i = 0; i < r; i++) { + for (int j = 0; j < c; j++) { + h[j] = mat[i][j] ? h[j] + 1 : 0; + } + + vector sumv(c, 0); + vector st; + + for (int j = 0; j < c; j++) { + while (!st.empty() && h[st.back()] >= h[j]) { + st.pop_back(); + } + + if (!st.empty()) { + int p = st.back(); + sumv[j] = sumv[p] + h[j] * (j - p); + } else { + sumv[j] = h[j] * (j + 1); + } + + st.push_back(j); + ans += sumv[j]; + } + } + + return ans; + } +}; diff --git a/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.cs b/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.cs new file mode 100644 index 00000000..1ba8fc56 --- /dev/null +++ b/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.cs @@ -0,0 +1,35 @@ +public class Solution { + public int NumSubmat(int[][] mat) { + int r = mat.Length; + int c = mat[0].Length; + int[] h = new int[c]; + int ans = 0; + + for (int i = 0; i < r; i++) { + for (int j = 0; j < c; j++) { + h[j] = mat[i][j] == 1 ? h[j] + 1 : 0; + } + + int[] sumv = new int[c]; + var st = new List(); + + for (int j = 0; j < c; j++) { + while (st.Count > 0 && h[st[st.Count - 1]] >= h[j]) { + st.RemoveAt(st.Count - 1); + } + + if (st.Count > 0) { + int p = st[st.Count - 1]; + sumv[j] = sumv[p] + h[j] * (j - p); + } else { + sumv[j] = h[j] * (j + 1); + } + + st.Add(j); + ans += sumv[j]; + } + } + + return ans; + } +} diff --git a/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.dart b/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.dart new file mode 100644 index 00000000..7abf9a96 --- /dev/null +++ b/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.dart @@ -0,0 +1,35 @@ +class Solution { + int numSubmat(List> mat) { + int r = mat.length; + int c = mat[0].length; + List h = List.filled(c, 0); + int ans = 0; + + for (int i = 0; i < r; i++) { + for (int j = 0; j < c; j++) { + h[j] = mat[i][j] == 1 ? h[j] + 1 : 0; + } + + List sumv = List.filled(c, 0); + List st = []; + + for (int j = 0; j < c; j++) { + while (st.isNotEmpty && h[st.last] >= h[j]) { + st.removeLast(); + } + + if (st.isNotEmpty) { + int p = st.last; + sumv[j] = sumv[p] + h[j] * (j - p); + } else { + sumv[j] = h[j] * (j + 1); + } + + st.add(j); + ans += sumv[j]; + } + } + + return ans; + } +} diff --git a/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.go b/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.go new file mode 100644 index 00000000..130d5aaa --- /dev/null +++ b/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.go @@ -0,0 +1,37 @@ +func numSubmat(mat [][]int) int { + r := len(mat) + c := len(mat[0]) + h := make([]int, c) + ans := 0 + + for i := 0; i < r; i++ { + for j := 0; j < c; j++ { + if mat[i][j] == 1 { + h[j]++ + } else { + h[j] = 0 + } + } + + sumv := make([]int, c) + st := []int{} + + for j := 0; j < c; j++ { + for len(st) > 0 && h[st[len(st)-1]] >= h[j] { + st = st[:len(st)-1] + } + + if len(st) > 0 { + p := st[len(st)-1] + sumv[j] = sumv[p] + h[j] * (j - p) + } else { + sumv[j] = h[j] * (j + 1) + } + + st = append(st, j) + ans += sumv[j] + } + } + + return ans +} diff --git a/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.java b/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.java new file mode 100644 index 00000000..1077e5fb --- /dev/null +++ b/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.java @@ -0,0 +1,36 @@ +class Solution { + public int numSubmat(int[][] mat) { + int r = mat.length; + int c = mat[0].length; + int[] h = new int[c]; + int ans = 0; + + for (int i = 0; i < r; i++) { + for (int j = 0; j < c; j++) { + h[j] = mat[i][j] == 1 ? h[j] + 1 : 0; + } + + int[] sumv = new int[c]; + int[] st = new int[c]; + int top = -1; + + for (int j = 0; j < c; j++) { + while (top >= 0 && h[st[top]] >= h[j]) { + top--; + } + + if (top >= 0) { + int p = st[top]; + sumv[j] = sumv[p] + h[j] * (j - p); + } else { + sumv[j] = h[j] * (j + 1); + } + + st[++top] = j; + ans += sumv[j]; + } + } + + return ans; + } +} diff --git a/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.kt b/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.kt new file mode 100644 index 00000000..1ef6e59c --- /dev/null +++ b/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.kt @@ -0,0 +1,35 @@ +class Solution { + fun numSubmat(mat: Array): Int { + val r = mat.size + val c = mat[0].size + val h = IntArray(c) + var ans = 0 + + for (i in 0 until r) { + for (j in 0 until c) { + h[j] = if (mat[i][j] == 1) h[j] + 1 else 0 + } + + val sumv = IntArray(c) + val st = mutableListOf() + + for (j in 0 until c) { + while (st.isNotEmpty() && h[st.last()] >= h[j]) { + st.removeAt(st.size - 1) + } + + if (st.isNotEmpty()) { + val p = st.last() + sumv[j] = sumv[p] + h[j] * (j - p) + } else { + sumv[j] = h[j] * (j + 1) + } + + st.add(j) + ans += sumv[j] + } + } + + return ans + } +} diff --git a/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.py b/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.py new file mode 100644 index 00000000..acecd978 --- /dev/null +++ b/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.py @@ -0,0 +1,20 @@ +class Solution: + def numSubmat(self, mat: List[List[int]]) -> int: + r, c = len(mat), len(mat[0]) + h = [0] * c + ans = 0 + for i in range(r): + for j in range(c): + h[j] = h[j] + 1 if mat[i][j] else 0 + sumv, st = [0] * c, [] + for j in range(c): + while st and h[st[-1]] >= h[j]: + st.pop() + if st: + p = st[-1] + sumv[j] = sumv[p] + h[j] * (j - p) + else: + sumv[j] = h[j] * (j + 1) + st.append(j) + ans += sumv[j] + return ans diff --git a/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.py2 b/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.py2 new file mode 100644 index 00000000..8b2ec68e --- /dev/null +++ b/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.py2 @@ -0,0 +1,25 @@ +class Solution(object): + def numSubmat(self, mat): + """ + :type mat: List[List[int]] + :rtype: int + """ + r, c = len(mat), len(mat[0]) + h = [0] * c + ans = 0 + for i in range(r): + for j in range(c): + h[j] = h[j] + 1 if mat[i][j] else 0 + sumv = [0] * c + st = [] + for j in range(c): + while st and h[st[-1]] >= h[j]: + st.pop() + if st: + p = st[-1] + sumv[j] = sumv[p] + h[j] * (j - p) + else: + sumv[j] = h[j] * (j + 1) + st.append(j) + ans += sumv[j] + return ans diff --git a/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.rb b/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.rb new file mode 100644 index 00000000..e456d710 --- /dev/null +++ b/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.rb @@ -0,0 +1,35 @@ +# @param {Integer[][]} mat +# @return {Integer} +def num_submat(mat) + r = mat.length + c = mat[0].length + h = Array.new(c, 0) + ans = 0 + + (0...r).each do |i| + (0...c).each do |j| + h[j] = mat[i][j] == 1 ? h[j] + 1 : 0 + end + + sumv = Array.new(c, 0) + st = [] + + (0...c).each do |j| + while !st.empty? && h[st[-1]] >= h[j] + st.pop + end + + if !st.empty? + p = st[-1] + sumv[j] = sumv[p] + h[j] * (j - p) + else + sumv[j] = h[j] * (j + 1) + end + + st.push(j) + ans += sumv[j] + end + end + + ans +end diff --git a/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.rs b/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.rs new file mode 100644 index 00000000..86c09767 --- /dev/null +++ b/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.rs @@ -0,0 +1,34 @@ +impl Solution { + pub fn num_submat(mat: Vec>) -> i32 { + let r = mat.len(); + let c = mat[0].len(); + let mut h = vec![0; c]; + let mut ans = 0; + + for i in 0..r { + for j in 0..c { + h[j] = if mat[i][j] == 1 { h[j] + 1 } else { 0 }; + } + + let mut sumv = vec![0; c]; + let mut st: Vec = Vec::new(); + + for j in 0..c { + while !st.is_empty() && h[st[st.len() - 1]] >= h[j] { + st.pop(); + } + + if let Some(&p) = st.last() { + sumv[j] = sumv[p] + h[j] * (j - p) as i32; + } else { + sumv[j] = h[j] * (j + 1) as i32; + } + + st.push(j); + ans += sumv[j]; + } + } + + ans + } +} diff --git a/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.swift b/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.swift new file mode 100644 index 00000000..3b1200c6 --- /dev/null +++ b/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.swift @@ -0,0 +1,34 @@ +class Solution { + func numSubmat(_ mat: [[Int]]) -> Int { + let r = mat.count + let c = mat[0].count + var h = Array(repeating: 0, count: c) + var ans = 0 + + for i in 0..= h[j] { + st.removeLast() + } + + if let p = st.last { + sumv[j] = sumv[p] + h[j] * (j - p) + } else { + sumv[j] = h[j] * (j + 1) + } + + st.append(j) + ans += sumv[j] + } + } + + return ans + } +} diff --git a/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.ts b/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.ts new file mode 100644 index 00000000..2c2cade7 --- /dev/null +++ b/tests/1501-2000/1504. count-submatrices-with-all-ones/sol.ts @@ -0,0 +1,33 @@ +function numSubmat(mat: number[][]): number { + const r = mat.length; + const c = mat[0].length; + const h: number[] = new Array(c).fill(0); + let ans = 0; + + for (let i = 0; i < r; i++) { + for (let j = 0; j < c; j++) { + h[j] = mat[i][j] === 1 ? h[j] + 1 : 0; + } + + const sumv: number[] = new Array(c).fill(0); + const st: number[] = []; + + for (let j = 0; j < c; j++) { + while (st.length > 0 && h[st[st.length - 1]] >= h[j]) { + st.pop(); + } + + if (st.length > 0) { + const p = st[st.length - 1]; + sumv[j] = sumv[p] + h[j] * (j - p); + } else { + sumv[j] = h[j] * (j + 1); + } + + st.push(j); + ans += sumv[j]; + } + } + + return ans; +} diff --git a/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/manifest.yaml b/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/manifest.yaml new file mode 100644 index 00000000..81969002 --- /dev/null +++ b/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/manifest.yaml @@ -0,0 +1,299 @@ +entry: + id: 1505 + title: "minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits" + params: + num: + type: string + k: + type: int + call: + cpp: "Solution().minInteger({num}, {k})" + rust: "Solution::min_integer({num}, {k})" + python3: "Solution().minInteger({num}, {k})" + python2: "Solution().minInteger({num}, {k})" + ruby: "min_integer({num}, {k})" + java: "new Solution().minInteger({num}, {k})" + csharp: "new Solution().MinInteger({num}, {k})" + kotlin: "Solution().minInteger({num}, {k})" + go: "minInteger({num}, {k})" + dart: "Solution().minInteger({num}, {k})" + swift: "Solution().minInteger({num}, {k})" + typescript: "minInteger({num}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().minInteger(num, k, {result})" + checker: | + class Checker: + def minInteger(self, num, k, result): + if not isinstance(result, str) or len(result) != len(num): + return False + positions = [[] for _ in range(10)] + for i, ch in enumerate(num): + positions[ord(ch) - 48].append(i) + bit = [0] * (len(num) + 1) + for i in range(1, len(num) + 1): + bit[i] += 1 + j = i + (i & -i) + if j <= len(num): + bit[j] += bit[i] + def prefix(i): + total = 0 + while i: + total += bit[i] + i -= i & -i + return total + def remove(i): + while i <= len(num): + bit[i] -= 1 + i += i & -i + expected = [] + for _ in num: + for digit in range(10): + if positions[digit]: + pos = positions[digit][0] + cost = prefix(pos) + if cost <= k: + k -= cost + positions[digit].pop(0) + remove(pos + 1) + expected.append(str(digit)) + break + return result == ''.join(expected) + +seed: 1505 + +tests: + - name: example_reverse_four + in: + num: "4321" + k: 4 + - name: example_leading_zero_after_swap + in: + num: "100" + k: 1 + - name: example_large_budget + in: + num: "36789" + k: 1000 + - name: single_digit + in: + num: "7" + k: 1 + - name: no_effective_swap + in: + num: "123456789" + k: 1 + - name: smallest_digit_moves_one + in: + num: "21" + k: 1 + - name: smallest_digit_blocked + in: + num: "9876543210" + k: 1 + - name: exact_distance + in: + num: "9081726354" + k: 9 + - name: zero_already_front + in: + num: "1020304050" + k: 2 + - name: repeated_digits + in: + num: "1111100000" + k: 5 + - name: repeated_zeroes + in: + num: "900000001" + k: 8 + - name: tie_preserves_order + in: + num: "3141592653589793" + k: 10 + - name: alternating_digits + in: + num: "9090909090" + k: 6 + - name: all_equal + in: + num: "5555555555" + k: 999 + - name: one_move_from_end + in: + num: "8123456709" + k: 1 + - name: budget_stops_mid_selection + in: + num: "76543210" + k: 7 + - name: two_zero_choices + in: + num: "505001" + k: 3 + - name: descending_short + in: + num: "654321" + k: 10 + - name: near_max_budget_small + in: + num: "9876543210123456789" + k: 1000000000 + - name: digit_order_boundary + in: + num: "1098765432" + k: 2 + - name: all_digits_once + in: + num: "1029384756" + k: 12 + - name: clustered_low_digits + in: + num: "8642000013579" + k: 7 + - name: long_static_pattern + in: + num: "9182736455463728190" + k: 25 + - name: generated_random_digits_1 + in: + num: + gen: str + len: 31 + alphabet: "123456789" + k: + gen: int + min: 1 + max: 465 + - name: generated_random_digits_2 + in: + num: + gen: str + len: 73 + alphabet: "123456789" + k: + gen: int + min: 1 + max: 2628 + - name: generated_binary_digits + in: + num: + gen: str + len: 128 + alphabet: "12" + k: + gen: int + min: 1 + max: 8128 + - name: generated_large_digits + in: + num: + gen: str + len: 1000 + alphabet: "123456789" + k: + gen: int + min: 1 + max: 1000000 + - name: generated_maximum_length + in: + num: + gen: str + len: 30000 + alphabet: "123456789" + k: + gen: int + min: 1 + max: 1000000000 + - name: generated_maximum_length_small_budget + in: + num: + gen: str + len: 30000 + alphabet: "123456789" + k: + gen: int + min: 1 + max: 3 + - name: generated_many_duplicates + in: + num: + gen: str + len: 256 + alphabet: "11229" + k: + gen: int + min: 1 + max: 32640 + - name: generated_small + in: + num: + gen: str + len: 2 + alphabet: "1289" + k: + gen: int + min: 1 + max: 1 + - name: generated_medium_budget + in: + num: + gen: str + len: 512 + alphabet: "369" + k: + gen: int + min: 1 + max: 100000 + - name: generated_long_binary + in: + num: + gen: str + len: 4096 + alphabet: "112" + k: + gen: int + min: 1 + max: 8388608 + - name: generated_large_already_sorted + in: + num: "12345678901234567890123456789012345678901234567890" + k: + gen: int + min: 1 + max: 1000000000 + - name: generated_large_reverse_static + in: + num: "98765432109876543210987654321098765432109876543210" + k: + gen: int + min: 1 + max: 1000000000 + - name: zero_at_last_position + in: + num: "1111111110" + k: 9 + - name: zero_requires_budget + in: + num: "5000000000" + k: 4 + - name: low_digit_not_worth_cost + in: + num: "9870123456" + k: 2 + - name: final_exact_reordering + in: + num: "321000" + k: 6 + - name: maximum_budget_two_digits + in: + num: "90" + k: 1000000000 diff --git a/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.cpp b/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.cpp new file mode 100644 index 00000000..db563bc6 --- /dev/null +++ b/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.cpp @@ -0,0 +1,46 @@ +class Solution { +public: + string minInteger(string num, int k) { + int n = num.size(); + unordered_map> dict; + for (int i = 0; i < n; i++) { + dict[num[i]].push_back(i); + } + + vector bit(n + 1, 0); + auto update = [&](int i, int val) { + while (i < bit.size()) { + bit[i] += val; + i += i & -i; + } + }; + auto query = [&](int i) { + int total = 0; + while (i > 0) { + total += bit[i]; + i -= i & -i; + } + return total; + }; + + for (int i = 1; i <= n; i++) update(i, 1); + + string res; + for (int pos = 0; pos < n; pos++) { + for (char v = '0'; v <= '9'; v++) { + if (!dict[v].empty()) { + int idx = dict[v].front(); + int cnt = query(idx); + if (cnt <= k) { + dict[v].pop_front(); + k -= cnt; + res += v; + update(idx + 1, -1); + break; + } + } + } + } + return res; + } +}; diff --git a/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.cs b/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.cs new file mode 100644 index 00000000..90cec7b3 --- /dev/null +++ b/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.cs @@ -0,0 +1,48 @@ +public class Solution { + public string MinInteger(string num, int k) { + int n = num.Length; + var dict = new Dictionary>(); + for (int i = 0; i < n; i++) { + char ch = num[i]; + if (!dict.ContainsKey(ch)) dict[ch] = new LinkedList(); + dict[ch].AddLast(i); + } + + int[] bit = new int[n + 1]; + void Update(int i, int val) { + while (i < bit.Length) { + bit[i] += val; + i += i & -i; + } + } + int Query(int i) { + int total = 0; + while (i > 0) { + total += bit[i]; + i -= i & -i; + } + return total; + } + + for (int i = 1; i <= n; i++) Update(i, 1); + + var res = new System.Text.StringBuilder(); + int remaining = k; + for (int pos = 0; pos < n; pos++) { + for (char v = '0'; v <= '9'; v++) { + if (dict.ContainsKey(v) && dict[v].Count > 0) { + int idx = dict[v].First.Value; + int cnt = Query(idx); + if (cnt <= remaining) { + dict[v].RemoveFirst(); + remaining -= cnt; + res.Append(v); + Update(idx + 1, -1); + break; + } + } + } + } + return res.ToString(); + } +} diff --git a/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.dart b/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.dart new file mode 100644 index 00000000..8794c527 --- /dev/null +++ b/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.dart @@ -0,0 +1,50 @@ +class Solution { + String minInteger(String num, int k) { + int n = num.length; + Map> dict = {}; + for (int i = 0; i < n; i++) { + String ch = num[i]; + dict.putIfAbsent(ch, () => []); + dict[ch]!.add(i); + } + + List bit = List.filled(n + 1, 0); + void update(int i, int val) { + while (i < bit.length) { + bit[i] += val; + i += i & -i; + } + } + int query(int i) { + int total = 0; + while (i > 0) { + total += bit[i]; + i -= i & -i; + } + return total; + } + + for (int i = 1; i <= n; i++) { + update(i, 1); + } + + StringBuffer res = StringBuffer(); + int remaining = k; + for (int pos = 0; pos < n; pos++) { + for (String v in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']) { + if (dict.containsKey(v) && dict[v]!.isNotEmpty) { + int idx = dict[v]!.first; + int cnt = query(idx); + if (cnt <= remaining) { + dict[v]!.removeAt(0); + remaining -= cnt; + res.write(v); + update(idx + 1, -1); + break; + } + } + } + } + return res.toString(); + } +} diff --git a/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.go b/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.go new file mode 100644 index 00000000..cbb22b93 --- /dev/null +++ b/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.go @@ -0,0 +1,46 @@ +func minInteger(num string, k int) string { + n := len(num) + dict := make(map[byte][]int) + for i := 0; i < n; i++ { + ch := num[i] + dict[ch] = append(dict[ch], i) + } + + bit := make([]int, n+1) + update := func(i, val int) { + for i < len(bit) { + bit[i] += val + i += i & -i + } + } + query := func(i int) int { + total := 0 + for i > 0 { + total += bit[i] + i -= i & -i + } + return total + } + + for i := 1; i <= n; i++ { + update(i, 1) + } + + res := make([]byte, 0, n) + for pos := 0; pos < n; pos++ { + for v := byte('0'); v <= byte('9'); v++ { + if len(dict[v]) > 0 { + idx := dict[v][0] + cnt := query(idx) + if cnt <= k { + dict[v] = dict[v][1:] + k -= cnt + res = append(res, v) + update(idx+1, -1) + break + } + } + } + } + return string(res) +} diff --git a/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.java b/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.java new file mode 100644 index 00000000..661191d7 --- /dev/null +++ b/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.java @@ -0,0 +1,50 @@ +class Solution { + public String minInteger(String num, int k) { + int n = num.length(); + java.util.Map> dict = new java.util.HashMap<>(); + for (int i = 0; i < n; i++) { + char ch = num.charAt(i); + dict.computeIfAbsent(ch, key -> new java.util.ArrayDeque<>()).addLast(i); + } + + int[] bit = new int[n + 1]; + for (int i = 1; i <= n; i++) { + update(bit, i, 1); + } + + StringBuilder res = new StringBuilder(); + for (int pos = 0; pos < n; pos++) { + for (char v = '0'; v <= '9'; v++) { + java.util.ArrayDeque dq = dict.get(v); + if (dq != null && !dq.isEmpty()) { + int idx = dq.peekFirst(); + int cnt = query(bit, idx); + if (cnt <= k) { + dq.pollFirst(); + k -= cnt; + res.append(v); + update(bit, idx + 1, -1); + break; + } + } + } + } + return res.toString(); + } + + private void update(int[] bit, int i, int val) { + while (i < bit.length) { + bit[i] += val; + i += i & -i; + } + } + + private int query(int[] bit, int i) { + int total = 0; + while (i > 0) { + total += bit[i]; + i -= i & -i; + } + return total; + } +} diff --git a/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.kt b/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.kt new file mode 100644 index 00000000..847160a4 --- /dev/null +++ b/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.kt @@ -0,0 +1,49 @@ +class Solution { + fun minInteger(num: String, k: Int): String { + val n = num.length + val dict = mutableMapOf>() + for (i in 0 until n) { + val ch = num[i] + dict.getOrPut(ch) { ArrayDeque() }.addLast(i) + } + + val bit = IntArray(n + 1) + fun update(i: Int, v: Int) { + var idx = i + while (idx < bit.size) { + bit[idx] += v + idx += idx and -idx + } + } + fun query(i: Int): Int { + var total = 0 + var idx = i + while (idx > 0) { + total += bit[idx] + idx -= idx and -idx + } + return total + } + + for (i in 1..n) update(i, 1) + var kk = k + val res = StringBuilder() + for (pos in 0 until n) { + for (v in '0'..'9') { + val dq = dict[v] + if (dq != null && dq.isNotEmpty()) { + val idx = dq.first() + val cnt = query(idx) + if (cnt <= kk) { + dq.removeFirst() + kk -= cnt + res.append(v) + update(idx + 1, -1) + break + } + } + } + } + return res.toString() + } +} diff --git a/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.py b/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.py new file mode 100644 index 00000000..9227c136 --- /dev/null +++ b/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.py @@ -0,0 +1,47 @@ +from collections import defaultdict, deque + + +class BIT: + def __init__(self, m): + self.ans = [0] * (m + 1) + + def update(self, i, val): + while i < len(self.ans): + self.ans[i] += val + i += i & -i + + def query(self, i): + total = 0 + + while i: + total += self.ans[i] + i -= i & -i + + return total + + +class Solution: + def minInteger(self, num, k): + n, dict1, res = len(num), defaultdict(deque), "" + + for i, x in enumerate(num): + dict1[x].append(i) + + fenwick = BIT(n) + + for i in range(n): + fenwick.update(i + 1, 1) + + for i in range(n): + for v in "0123456789": + if dict1[v]: + idx = dict1[v][0] + cnt = fenwick.query(idx) + if cnt <= k: + dict1[v].popleft() + k -= cnt + res += v + fenwick.update(idx + 1, -1) + break + + return res diff --git a/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.py2 b/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.py2 new file mode 100644 index 00000000..095966a5 --- /dev/null +++ b/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.py2 @@ -0,0 +1,44 @@ +class Solution(object): + def minInteger(self, num, k): + """ + :type num: str + :type k: int + :rtype: str + """ + from collections import defaultdict, deque + + n = len(num) + d = defaultdict(deque) + for i, ch in enumerate(num): + d[ch].append(i) + + bit = [0] * (n + 1) + + def update(i, val): + while i < len(bit): + bit[i] += val + i += i & -i + + def query(i): + total = 0 + while i: + total += bit[i] + i -= i & -i + return total + + for i in range(1, n + 1): + update(i, 1) + + res = [] + for _ in range(n): + for v in "0123456789": + if d[v]: + idx = d[v][0] + cnt = query(idx) + if cnt <= k: + d[v].popleft() + k -= cnt + res.append(v) + update(idx + 1, -1) + break + return "".join(res) diff --git a/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.rb b/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.rb new file mode 100644 index 00000000..2ebcbe1c --- /dev/null +++ b/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.rb @@ -0,0 +1,46 @@ +# @param {String} num +# @param {Integer} k +# @return {String} +def min_integer(num, k) + n = num.length + dict = Hash.new { |h, key| h[key] = [] } + num.each_char.with_index { |ch, i| dict[ch] << i } + + bit = Array.new(n + 1, 0) + + define_method(:update) do |i, val| + while i < bit.length + bit[i] += val + i += i & -i + end + end + + define_method(:query) do |i| + total = 0 + while i > 0 + total += bit[i] + i -= i & -i + end + total + end + + (1..n).each { |i| update(i, 1) } + + res = "" + n.times do + "0123456789".each_char do |v| + unless dict[v].empty? + idx = dict[v].first + cnt = query(idx) + if cnt <= k + dict[v].shift + k -= cnt + res << v + update(idx + 1, -1) + break + end + end + end + end + res +end diff --git a/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.rs b/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.rs new file mode 100644 index 00000000..3f5c85bf --- /dev/null +++ b/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.rs @@ -0,0 +1,49 @@ +impl Solution { + pub fn min_integer(num: String, k: i32) -> String { + let n = num.len(); + let mut dict: std::collections::HashMap> = std::collections::HashMap::new(); + for (i, ch) in num.chars().enumerate() { + dict.entry(ch).or_default().push_back(i); + } + + let mut bit = vec![0i32; n + 1]; + fn update(bit: &mut Vec, mut i: usize, val: i32) { + while i < bit.len() { + bit[i] += val; + i += i & (!i + 1); + } + } + fn query(bit: &Vec, mut i: usize) -> i32 { + let mut total = 0; + while i > 0 { + total += bit[i]; + i -= i & (!i + 1); + } + total + } + + for i in 1..=n { + update(&mut bit, i, 1); + } + + let mut kk = k; + let mut res = String::with_capacity(n); + for _ in 0..n { + for v in '0'..='9' { + if let Some(dq) = dict.get_mut(&v) { + if let Some(&idx) = dq.front() { + let cnt = query(&bit, idx); + if cnt <= kk { + dq.pop_front(); + kk -= cnt; + res.push(v); + update(&mut bit, idx + 1, -1); + break; + } + } + } + } + } + res + } +} diff --git a/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.swift b/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.swift new file mode 100644 index 00000000..96294e5b --- /dev/null +++ b/tests/1501-2000/1505. minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/sol.swift @@ -0,0 +1,50 @@ +class Solution { + func minInteger(_ num: String, _ k: Int) -> String { + let n = num.count + var dict = [Character: [Int]]() + for (i, ch) in num.enumerated() { + dict[ch, default: []].append(i) + } + + var bit = [Int](repeating: 0, count: n + 1) + func update(_ i: Int, _ val: Int) { + var idx = i + while idx < bit.count { + bit[idx] += val + idx += idx & -idx + } + } + func query(_ i: Int) -> Int { + var total = 0 + var idx = i + while idx > 0 { + total += bit[idx] + idx -= idx & -idx + } + return total + } + + for i in 1...n { + update(i, 1) + } + + var kk = k + var res = "" + for _ in 0.. = new Map(); + for (let i = 0; i < n; i++) { + const ch = num[i]; + if (!dict.has(ch)) dict.set(ch, []); + dict.get(ch)!.push(i); + } + + const bit: number[] = new Array(n + 1).fill(0); + const update = (i: number, val: number) => { + while (i < bit.length) { + bit[i] += val; + i += i & -i; + } + }; + const query = (i: number): number => { + let total = 0; + while (i > 0) { + total += bit[i]; + i -= i & -i; + } + return total; + }; + + for (let i = 1; i <= n; i++) { + update(i, 1); + } + + let remaining = k; + let res = ""; + for (let pos = 0; pos < n; pos++) { + for (const v of "0123456789") { + const arr = dict.get(v); + if (arr && arr.length > 0) { + const idx = arr[0]; + const cnt = query(idx); + if (cnt <= remaining) { + arr.shift(); + remaining -= cnt; + res += v; + update(idx + 1, -1); + break; + } + } + } + } + return res; +} diff --git a/tests/1501-2000/1507. reformat-date/manifest.yaml b/tests/1501-2000/1507. reformat-date/manifest.yaml new file mode 100644 index 00000000..43b00375 --- /dev/null +++ b/tests/1501-2000/1507. reformat-date/manifest.yaml @@ -0,0 +1,230 @@ +entry: + id: 1507 + title: "reformat-date" + params: + date: + type: string + call: + cpp: "Solution().reformatDate({date})" + rust: "Solution::reformat_date({date})" + python3: "Solution().reformatDate({date})" + python2: "Solution().reformatDate({date})" + ruby: "reformat_date({date})" + java: "new Solution().reformatDate({date})" + csharp: "new Solution().ReformatDate({date})" + kotlin: "Solution().reformatDate({date})" + go: "reformatDate({date})" + dart: "Solution().reformatDate({date})" + swift: "Solution().reformatDate({date})" + typescript: "reformatDate({date})" + +judge: + type: "exact" + +limits: + time_ms: 200 + memory_mb: 300 + +oracle: + python3: + call: "Checker().reformatDate(date, {result})" + checker: | + class Checker: + def reformatDate(self, date, result): + parts = date.split() + if len(parts) != 3 or not isinstance(result, str): + return False + day, month, year = parts + months = dict( + Jan='01', Feb='02', Mar='03', Apr='04', + May='05', Jun='06', Jul='07', Aug='08', + Sep='09', Oct='10', Nov='11', Dec='12', + ) + if month not in months or len(year) != 4 or not year.isdigit(): + return False + if not 1900 <= int(year) <= 2100: + return False + if len(day) < 3 or day[-2:] not in ('st', 'nd', 'rd', 'th'): + return False + digits = day[:-2] + if not digits.isdigit() or not 1 <= int(digits) <= 31: + return False + number = int(digits) + if 10 < number % 100 < 14: + suffix = 'th' + elif number % 10 == 1: + suffix = 'st' + elif number % 10 == 2: + suffix = 'nd' + elif number % 10 == 3: + suffix = 'rd' + else: + suffix = 'th' + if day[-2:] != suffix: + return False + expected = year + '-' + months[month] + '-' + digits.zfill(2) + return result == expected and len(result) == 10 and result[4] == '-' and result[7] == '-' + +seed: 1507 + +tests: + - name: "example twentieth october" + in: + date: "20th Oct 2052" + out: "2052-10-20" + - name: "example sixth june" + in: + date: "6th Jun 1933" + out: "1933-06-06" + - name: "example twenty sixth may" + in: + date: "26th May 1960" + out: "1960-05-26" + - name: "first january minimum year" + in: + date: "1st Jan 1900" + out: "1900-01-01" + - name: "second february" + in: + date: "2nd Feb 1901" + out: "1901-02-02" + - name: "third march" + in: + date: "3rd Mar 1902" + out: "1902-03-03" + - name: "fourth april" + in: + date: "4th Apr 1903" + out: "1903-04-04" + - name: "fifth may" + in: + date: "5th May 1904" + out: "1904-05-05" + - name: "seventh july" + in: + date: "7th Jul 1905" + out: "1905-07-07" + - name: "eighth august" + in: + date: "8th Aug 1906" + out: "1906-08-08" + - name: "ninth september" + in: + date: "9th Sep 1907" + out: "1907-09-09" + - name: "tenth october" + in: + date: "10th Oct 1908" + out: "1908-10-10" + - name: "eleventh november" + in: + date: "11th Nov 1909" + out: "1909-11-11" + - name: "twelfth december" + in: + date: "12th Dec 1910" + out: "1910-12-12" + - name: "thirteenth january" + in: + date: "13th Jan 1911" + out: "1911-01-13" + - name: "fourteenth february" + in: + date: "14th Feb 1912" + out: "1912-02-14" + - name: "fifteenth march" + in: + date: "15th Mar 1913" + out: "1913-03-15" + - name: "sixteenth april" + in: + date: "16th Apr 1914" + out: "1914-04-16" + - name: "seventeenth may" + in: + date: "17th May 1915" + out: "1915-05-17" + - name: "eighteenth june" + in: + date: "18th Jun 1916" + out: "1916-06-18" + - name: "nineteenth july" + in: + date: "19th Jul 1917" + out: "1917-07-19" + - name: "twenty first august" + in: + date: "21st Aug 1918" + out: "1918-08-21" + - name: "twenty second september" + in: + date: "22nd Sep 1919" + out: "1919-09-22" + - name: "twenty third october" + in: + date: "23rd Oct 1920" + out: "1920-10-23" + - name: "twenty fourth november" + in: + date: "24th Nov 1921" + out: "1921-11-24" + - name: "twenty fifth december" + in: + date: "25th Dec 1922" + out: "1922-12-25" + - name: "twenty sixth february" + in: + date: "26th Feb 1933" + out: "1933-02-26" + - name: "twenty seventh march" + in: + date: "27th Mar 1960" + out: "1960-03-27" + - name: "twenty eighth april" + in: + date: "28th Apr 1999" + out: "1999-04-28" + - name: "twenty ninth may" + in: + date: "29th May 2000" + out: "2000-05-29" + - name: "thirtieth june" + in: + date: "30th Jun 2001" + out: "2001-06-30" + - name: "thirty first january" + in: + date: "31st Jan 2024" + out: "2024-01-31" + - name: "thirty first march" + in: + date: "31st Mar 2052" + out: "2052-03-31" + - name: "thirty first august" + in: + date: "31st Aug 2099" + out: "2099-08-31" + - name: "thirty first december maximum year" + in: + date: "31st Dec 2100" + out: "2100-12-31" + - name: "single digit leap year" + in: + date: "6th Feb 2000" + out: "2000-02-06" + - name: "ordinal eleventh boundary" + in: + date: "11th Nov 2100" + out: "2100-11-11" + - name: "thirtieth september minimum year" + in: + date: "30th Sep 1900" + out: "1900-09-30" + - name: "second july midrange year" + in: + date: "2nd Jul 1950" + out: "1950-07-02" + - name: "first december maximum year" + in: + date: "1st Dec 2100" + out: "2100-12-01" diff --git a/tests/1501-2000/1507. reformat-date/sol.cpp b/tests/1501-2000/1507. reformat-date/sol.cpp new file mode 100644 index 00000000..e9979a79 --- /dev/null +++ b/tests/1501-2000/1507. reformat-date/sol.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + string reformatDate(string date) { + unordered_map monthDict = { + {"Jan", "01"}, {"Feb", "02"}, {"Mar", "03"}, {"Apr", "04"}, + {"May", "05"}, {"Jun", "06"}, {"Jul", "07"}, {"Aug", "08"}, + {"Sep", "09"}, {"Oct", "10"}, {"Nov", "11"}, {"Dec", "12"} + }; + istringstream iss(date); + string day, month, year; + iss >> day >> month >> year; + day = day.substr(0, day.size() - 2); + if (day.size() == 1) day = "0" + day; + return year + "-" + monthDict[month] + "-" + day; + } +}; diff --git a/tests/1501-2000/1507. reformat-date/sol.cs b/tests/1501-2000/1507. reformat-date/sol.cs new file mode 100644 index 00000000..4f34c0f2 --- /dev/null +++ b/tests/1501-2000/1507. reformat-date/sol.cs @@ -0,0 +1,15 @@ +public class Solution { + public string ReformatDate(string date) { + var monthDict = new System.Collections.Generic.Dictionary { + {"Jan", "01"}, {"Feb", "02"}, {"Mar", "03"}, {"Apr", "04"}, + {"May", "05"}, {"Jun", "06"}, {"Jul", "07"}, {"Aug", "08"}, + {"Sep", "09"}, {"Oct", "10"}, {"Nov", "11"}, {"Dec", "12"} + }; + var parts = date.Split(' '); + var day = parts[0].Substring(0, parts[0].Length - 2); + if (day.Length == 1) day = "0" + day; + var month = monthDict[parts[1]]; + var year = parts[2]; + return year + "-" + month + "-" + day; + } +} diff --git a/tests/1501-2000/1507. reformat-date/sol.dart b/tests/1501-2000/1507. reformat-date/sol.dart new file mode 100644 index 00000000..c58043d6 --- /dev/null +++ b/tests/1501-2000/1507. reformat-date/sol.dart @@ -0,0 +1,15 @@ +class Solution { + String reformatDate(String date) { + final monthDict = { + 'Jan': '01', 'Feb': '02', 'Mar': '03', 'Apr': '04', + 'May': '05', 'Jun': '06', 'Jul': '07', 'Aug': '08', + 'Sep': '09', 'Oct': '10', 'Nov': '11', 'Dec': '12', + }; + final parts = date.split(' '); + var day = parts[0].substring(0, parts[0].length - 2); + if (day.length == 1) day = '0$day'; + final month = monthDict[parts[1]]!; + final year = parts[2]; + return '$year-$month-$day'; + } +} diff --git a/tests/1501-2000/1507. reformat-date/sol.go b/tests/1501-2000/1507. reformat-date/sol.go new file mode 100644 index 00000000..44208ea7 --- /dev/null +++ b/tests/1501-2000/1507. reformat-date/sol.go @@ -0,0 +1,15 @@ +func reformatDate(date string) string { + monthDict := map[string]string{ + "Jan": "01", "Feb": "02", "Mar": "03", "Apr": "04", + "May": "05", "Jun": "06", "Jul": "07", "Aug": "08", + "Sep": "09", "Oct": "10", "Nov": "11", "Dec": "12", + } + parts := strings.Split(date, " ") + day := parts[0][:len(parts[0])-2] + if len(day) == 1 { + day = "0" + day + } + month := monthDict[parts[1]] + year := parts[2] + return year + "-" + month + "-" + day +} diff --git a/tests/1501-2000/1507. reformat-date/sol.java b/tests/1501-2000/1507. reformat-date/sol.java new file mode 100644 index 00000000..3d8518e0 --- /dev/null +++ b/tests/1501-2000/1507. reformat-date/sol.java @@ -0,0 +1,20 @@ +class Solution { + public String reformatDate(String date) { + java.util.Map monthDict = new java.util.HashMap<>(); + monthDict.put("Jan", "01"); monthDict.put("Feb", "02"); monthDict.put("Mar", "03"); + monthDict.put("Apr", "04"); monthDict.put("May", "05"); monthDict.put("Jun", "06"); + monthDict.put("Jul", "07"); monthDict.put("Aug", "08"); monthDict.put("Sep", "09"); + monthDict.put("Oct", "10"); monthDict.put("Nov", "11"); monthDict.put("Dec", "12"); + + String[] parts = date.split(" "); + String day = parts[0]; + String month = parts[1]; + String year = parts[2]; + + day = day.substring(0, day.length() - 2); + if (day.length() == 1) day = "0" + day; + month = monthDict.get(month); + + return year + "-" + month + "-" + day; + } +} diff --git a/tests/1501-2000/1507. reformat-date/sol.kt b/tests/1501-2000/1507. reformat-date/sol.kt new file mode 100644 index 00000000..c3d1ed9e --- /dev/null +++ b/tests/1501-2000/1507. reformat-date/sol.kt @@ -0,0 +1,15 @@ +class Solution { + fun reformatDate(date: String): String { + val monthDict = mapOf( + "Jan" to "01", "Feb" to "02", "Mar" to "03", "Apr" to "04", + "May" to "05", "Jun" to "06", "Jul" to "07", "Aug" to "08", + "Sep" to "09", "Oct" to "10", "Nov" to "11", "Dec" to "12" + ) + val parts = date.split(" ") + var day = parts[0].dropLast(2) + if (day.length == 1) day = "0$day" + val month = monthDict[parts[1]]!! + val year = parts[2] + return "$year-$month-$day" + } +} diff --git a/tests/1501-2000/1507. reformat-date/sol.py b/tests/1501-2000/1507. reformat-date/sol.py new file mode 100644 index 00000000..a38348fa --- /dev/null +++ b/tests/1501-2000/1507. reformat-date/sol.py @@ -0,0 +1,20 @@ +class Solution(object): + def reformatDate(self, date): + month_dict = { + "Jan": "01", + "Feb": "02", + "Mar": "03", + "Apr": "04", + "May": "05", + "Jun": "06", + "Jul": "07", + "Aug": "08", + "Sep": "09", + "Oct": "10", + "Nov": "11", + "Dec": "12", + } + day, month, year = date.split() + day = day[:-2].zfill(2) + month = month_dict[month] + return year + "-" + month + "-" + day diff --git a/tests/1501-2000/1507. reformat-date/sol.py2 b/tests/1501-2000/1507. reformat-date/sol.py2 new file mode 100644 index 00000000..62023c8e --- /dev/null +++ b/tests/1501-2000/1507. reformat-date/sol.py2 @@ -0,0 +1,11 @@ +class Solution(object): + def reformatDate(self, date): + month_dict = { + 'Jan': '01', 'Feb': '02', 'Mar': '03', 'Apr': '04', + 'May': '05', 'Jun': '06', 'Jul': '07', 'Aug': '08', + 'Sep': '09', 'Oct': '10', 'Nov': '11', 'Dec': '12', + } + day, month, year = date.split() + day = day[:-2].zfill(2) + month = month_dict[month] + return year + '-' + month + '-' + day diff --git a/tests/1501-2000/1507. reformat-date/sol.rb b/tests/1501-2000/1507. reformat-date/sol.rb new file mode 100644 index 00000000..3335e3a1 --- /dev/null +++ b/tests/1501-2000/1507. reformat-date/sol.rb @@ -0,0 +1,13 @@ +# @param {String} date +# @return {String} +def reformat_date(date) + month_dict = { + 'Jan' => '01', 'Feb' => '02', 'Mar' => '03', 'Apr' => '04', + 'May' => '05', 'Jun' => '06', 'Jul' => '07', 'Aug' => '08', + 'Sep' => '09', 'Oct' => '10', 'Nov' => '11', 'Dec' => '12' + } + day, month, year = date.split + day = day[0...-2].rjust(2, '0') + month = month_dict[month] + year + '-' + month + '-' + day +end diff --git a/tests/1501-2000/1507. reformat-date/sol.rs b/tests/1501-2000/1507. reformat-date/sol.rs new file mode 100644 index 00000000..39169948 --- /dev/null +++ b/tests/1501-2000/1507. reformat-date/sol.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn reformat_date(date: String) -> String { + let month_dict = std::collections::HashMap::from([ + ("Jan", "01"), ("Feb", "02"), ("Mar", "03"), ("Apr", "04"), + ("May", "05"), ("Jun", "06"), ("Jul", "07"), ("Aug", "08"), + ("Sep", "09"), ("Oct", "10"), ("Nov", "11"), ("Dec", "12"), + ]); + let parts: Vec<&str> = date.split_whitespace().collect(); + let day_str = parts[0]; + let day_num = &day_str[..day_str.len()-2]; + let day = if day_num.len() == 1 { format!("0{}", day_num) } else { day_num.to_string() }; + let month = month_dict[parts[1]]; + let year = parts[2]; + format!("{}-{}-{}", year, month, day) + } +} diff --git a/tests/1501-2000/1507. reformat-date/sol.swift b/tests/1501-2000/1507. reformat-date/sol.swift new file mode 100644 index 00000000..a8116a66 --- /dev/null +++ b/tests/1501-2000/1507. reformat-date/sol.swift @@ -0,0 +1,15 @@ +class Solution { + func reformatDate(_ date: String) -> String { + let monthDict = [ + "Jan": "01", "Feb": "02", "Mar": "03", "Apr": "04", + "May": "05", "Jun": "06", "Jul": "07", "Aug": "08", + "Sep": "09", "Oct": "10", "Nov": "11", "Dec": "12" + ] + let parts = date.split(separator: " ").map(String.init) + var day = String(parts[0].dropLast(2)) + if day.count == 1 { day = "0" + day } + let month = monthDict[parts[1]]! + let year = parts[2] + return year + "-" + month + "-" + day + } +} diff --git a/tests/1501-2000/1507. reformat-date/sol.ts b/tests/1501-2000/1507. reformat-date/sol.ts new file mode 100644 index 00000000..f26f9814 --- /dev/null +++ b/tests/1501-2000/1507. reformat-date/sol.ts @@ -0,0 +1,22 @@ +function reformatDate(date: string): string { + const monthDict: { [key: string]: string } = { + Jan: "01", + Feb: "02", + Mar: "03", + Apr: "04", + May: "05", + Jun: "06", + Jul: "07", + Aug: "08", + Sep: "09", + Oct: "10", + Nov: "11", + Dec: "12", + }; + const parts = date.split(" "); + let day = parts[0].slice(0, -2); + if (day.length === 1) day = "0" + day; + const month = monthDict[parts[1]]; + const year = parts[2]; + return year + "-" + month + "-" + day; +} diff --git a/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/manifest.yaml b/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/manifest.yaml new file mode 100644 index 00000000..0a51053e --- /dev/null +++ b/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/manifest.yaml @@ -0,0 +1,482 @@ +entry: + id: 1508 + title: "range-sum-of-sorted-subarray-sums" + params: + nums: + type: array + items: + type: int + n: + type: int + left: + type: int + right: + type: int + call: + cpp: "Solution().rangeSum({nums}, {n}, {left}, {right})" + rust: "Solution::range_sum({nums}, {n}, {left}, {right})" + python3: "Solution().rangeSum({nums}, {n}, {left}, {right})" + python2: "Solution().rangeSum({nums}, {n}, {left}, {right})" + ruby: "range_sum({nums}, {n}, {left}, {right})" + java: "new Solution().rangeSum({nums}, {n}, {left}, {right})" + csharp: "new Solution().RangeSum({nums}, {n}, {left}, {right})" + kotlin: "Solution().rangeSum({nums}, {n}, {left}, {right})" + go: "rangeSum({nums}, {n}, {left}, {right})" + dart: "Solution().rangeSum({nums}, {n}, {left}, {right})" + swift: "Solution().rangeSum({nums}, {n}, {left}, {right})" + typescript: "rangeSum({nums}, {n}, {left}, {right})" +judge: + type: "exact" +limits: + time_ms: 1000 + memory_mb: 256 +oracle: + python3: + call: "Checker().rangeSum(nums, n, left, right, {result})" + checker: | + class Checker: + def rangeSum(self, nums, n, left, right, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + values = [] + for i in range(n): + total = 0 + for j in range(i, n): + total += nums[j] + values.append(total) + values.sort() + expected = sum(values[left - 1:right]) % 1000000007 + return result == expected +seed: 1508 +tests: + - name: "example one" + in: + nums: [1, 2, 3, 4] + n: 4 + left: 1 + right: 5 + out: 13 + - name: "example two" + in: + nums: [1, 2, 3, 4] + n: 4 + left: 3 + right: 4 + out: 6 + - name: "example three" + in: + nums: [1, 2, 3, 4] + n: 4 + left: 1 + right: 10 + out: 50 + - name: "single minimum" + in: + nums: [1] + n: 1 + left: 1 + right: 1 + - name: "single maximum" + in: + nums: [100] + n: 1 + left: 1 + right: 1 + - name: "two ascending first" + in: + nums: [1, 2] + n: 2 + left: 1 + right: 1 + - name: "two ascending all" + in: + nums: [1, 2] + n: 2 + left: 1 + right: 3 + - name: "two descending middle" + in: + nums: [2, 1] + n: 2 + left: 2 + right: 2 + - name: "equal pair" + in: + nums: [5, 5] + n: 2 + left: 2 + right: 3 + - name: "three ones" + in: + nums: [1, 1, 1] + n: 3 + left: 2 + right: 5 + - name: "three hundreds" + in: + nums: [100, 100, 100] + n: 3 + left: 1 + right: 6 + - name: "alternating small" + in: + nums: [1, 10, 1] + n: 3 + left: 1 + right: 4 + - name: "alternating large" + in: + nums: [10, 1, 10] + n: 3 + left: 3 + right: 6 + - name: "four duplicates" + in: + nums: [7, 7, 7, 7] + n: 4 + left: 4 + right: 9 + - name: "four varied prefix" + in: + nums: [4, 1, 9, 2] + n: 4 + left: 1 + right: 3 + - name: "four varied suffix" + in: + nums: [4, 1, 9, 2] + n: 4 + left: 8 + right: 10 + - name: "five increasing" + in: + nums: [1, 2, 3, 4, 5] + n: 5 + left: 2 + right: 12 + - name: "five decreasing" + in: + nums: [5, 4, 3, 2, 1] + n: 5 + left: 6 + right: 10 + - name: "five all range" + in: + nums: [3, 3, 3, 3, 3] + n: 5 + left: 1 + right: 15 + - name: "six mixed low" + in: + nums: [1, 3, 2, 1, 2, 3] + n: 6 + left: 1 + right: 8 + - name: "six mixed high" + in: + nums: [1, 3, 2, 1, 2, 3] + n: 6 + left: 14 + right: 21 + - name: "seven alternating" + in: + nums: [2, 9, 2, 9, 2, 9, 2] + n: 7 + left: 5 + right: 20 + - name: "eight varied" + in: + nums: [8, 1, 6, 2, 7, 3, 5, 4] + n: 8 + left: 10 + right: 25 + - name: "nine ones and hundred" + in: + nums: [1, 1, 1, 1, 1, 1, 1, 1, 100] + n: 9 + left: 20 + right: 35 + - name: "ten increasing" + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + n: 10 + left: 30 + right: 50 + - name: "ten decreasing" + in: + nums: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + n: 10 + left: 1 + right: 10 + - name: "twelve patterned" + in: + nums: [1, 100, 2, 99, 3, 98, 4, 97, 5, 96, 6, 95] + n: 12 + left: 40 + right: 70 + - name: "twenty uniform" + in: + nums: + [ + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + ] + n: 20 + left: 1 + right: 210 + - name: "twenty max alternating" + in: + nums: + [ + 100, + 1, + 100, + 1, + 100, + 1, + 100, + 1, + 100, + 1, + 100, + 1, + 100, + 1, + 100, + 1, + 100, + 1, + 100, + 1, + ] + n: 20 + left: 100 + right: 200 + - name: "thirty varied" + in: + nums: + [ + 1, + 17, + 3, + 42, + 8, + 5, + 99, + 2, + 14, + 6, + 73, + 4, + 28, + 11, + 65, + 9, + 31, + 7, + 88, + 13, + 22, + 10, + 54, + 12, + 36, + 15, + 47, + 16, + 81, + 18, + ] + n: 30 + left: 200 + right: 400 + - name: "fifteen repeated blocks" + in: + nums: [1, 1, 50, 50, 1, 1, 50, 50, 1, 1, 50, 50, 1, 1, 50] + n: 15 + left: 25 + right: 75 + - name: "sixteen extremes middle slice" + in: + nums: [100, 1, 100, 1, 100, 1, 100, 1, 1, 100, 1, 100, 1, 100, 1, 100] + n: 16 + left: 60 + right: 100 + - name: "twenty five varied upper slice" + in: + nums: + [ + 2, + 98, + 4, + 96, + 6, + 94, + 8, + 92, + 10, + 90, + 12, + 88, + 14, + 86, + 16, + 84, + 18, + 82, + 20, + 80, + 22, + 78, + 24, + 76, + 26, + ] + n: 25 + left: 250 + right: 325 + - name: "fifty ones" + 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, + ] + n: 50 + left: 500 + right: 1000 + - name: "three extreme full range" + in: + nums: [100, 1, 100] + n: 3 + left: 1 + right: 6 + - name: "upper bound all minimum" + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 1 + n: 1000 + left: 1 + right: 500500 + - name: "upper bound all maximum" + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 100 + max: 100 + n: 1000 + left: 250001 + right: 500500 + - name: "upper bound random full range" + seed: 150801 + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 100 + n: 1000 + left: 1 + right: 500500 + - name: "upper bound random prefix" + seed: 150802 + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 100 + n: 1000 + left: 1 + right: 1000 + - name: "upper bound random suffix" + seed: 150803 + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 100 + n: 1000 + left: 499501 + right: 500500 diff --git a/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.cpp b/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.cpp new file mode 100644 index 00000000..7e1cc357 --- /dev/null +++ b/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int rangeSum(vector& nums, int n, int left, int right) { + const int MOD = 1000000007; + vector sums; + sums.reserve(n * (n + 1) / 2); + for (int i = 0; i < n; ++i) { + long long total = 0; + for (int j = i; j < n; ++j) { + total += nums[j]; + sums.push_back(total); + } + } + sort(sums.begin(), sums.end()); + long long result = 0; + for (int i = left - 1; i < right; ++i) { + result = (result + sums[i]) % MOD; + } + return (int)result; + } +}; diff --git a/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.cs b/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.cs new file mode 100644 index 00000000..e9f8a34d --- /dev/null +++ b/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.cs @@ -0,0 +1,19 @@ +public class Solution { + public int RangeSum(int[] nums, int n, int left, int right) { + const int MOD = 1000000007; + var sums = new List(); + for (int i = 0; i < n; i++) { + long total = 0; + for (int j = i; j < n; j++) { + total += nums[j]; + sums.Add(total); + } + } + sums.Sort(); + long result = 0; + for (int i = left - 1; i < right; i++) { + result = (result + sums[i]) % MOD; + } + return (int)result; + } +} diff --git a/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.dart b/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.dart new file mode 100644 index 00000000..386b9bf2 --- /dev/null +++ b/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.dart @@ -0,0 +1,19 @@ +class Solution { + int rangeSum(List nums, int n, int left, int right) { + const int MOD = 1000000007; + List sums = []; + for (int i = 0; i < n; i++) { + int total = 0; + for (int j = i; j < n; j++) { + total += nums[j]; + sums.add(total); + } + } + sums.sort(); + int result = 0; + for (int i = left - 1; i < right; i++) { + result = (result + sums[i]) % MOD; + } + return result; + } +} diff --git a/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.go b/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.go new file mode 100644 index 00000000..bbdb47ae --- /dev/null +++ b/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.go @@ -0,0 +1,17 @@ +func rangeSum(nums []int, n int, left int, right int) int { + const MOD = 1000000007 + sums := make([]int64, 0, n*(n+1)/2) + for i := 0; i < n; i++ { + var total int64 = 0 + for _, v := range nums[i:] { + total += int64(v) + sums = append(sums, total) + } + } + sort.Slice(sums, func(i, j int) bool { return sums[i] < sums[j] }) + var result int64 = 0 + for i := left - 1; i < right; i++ { + result = (result + sums[i]) % MOD + } + return int(result) +} diff --git a/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.java b/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.java new file mode 100644 index 00000000..e2890402 --- /dev/null +++ b/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.java @@ -0,0 +1,21 @@ +class Solution { + public int rangeSum(int[] nums, int n, int left, int right) { + int MOD = 1000000007; + int size = n * (n + 1) / 2; + long[] sums = new long[size]; + int idx = 0; + for (int i = 0; i < n; i++) { + long total = 0; + for (int j = i; j < n; j++) { + total += nums[j]; + sums[idx++] = total; + } + } + Arrays.sort(sums); + long result = 0; + for (int i = left - 1; i < right; i++) { + result = (result + sums[i]) % MOD; + } + return (int) result; + } +} diff --git a/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.kt b/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.kt new file mode 100644 index 00000000..4f4eae25 --- /dev/null +++ b/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.kt @@ -0,0 +1,19 @@ +class Solution { + fun rangeSum(nums: IntArray, n: Int, left: Int, right: Int): Int { + val MOD = 1000000007 + val sums = mutableListOf() + for (i in 0 until n) { + var total = 0L + for (j in i until n) { + total += nums[j] + sums.add(total) + } + } + sums.sort() + var result = 0L + for (i in left - 1 until right) { + result = (result + sums[i]) % MOD + } + return result.toInt() + } +} diff --git a/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.py b/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.py new file mode 100644 index 00000000..7ad06eec --- /dev/null +++ b/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.py @@ -0,0 +1,10 @@ +class Solution: + def rangeSum(self, nums, n, left, right): + sums = [] + for i in range(n): + total = 0 + for value in nums[i:n]: + total += value + sums.append(total) + sums.sort() + return sum(sums[left - 1 : right]) % 1000000007 diff --git a/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.py2 b/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.py2 new file mode 100644 index 00000000..93c087cf --- /dev/null +++ b/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.py2 @@ -0,0 +1,17 @@ +class Solution(object): + def rangeSum(self, nums, n, left, right): + """ + :type nums: List[int] + :type n: int + :type left: int + :type right: int + :rtype: int + """ + sums = [] + for i in range(n): + total = 0 + for value in nums[i:n]: + total += value + sums.append(total) + sums.sort() + return sum(sums[left - 1:right]) % 1000000007 diff --git a/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.rb b/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.rb new file mode 100644 index 00000000..98edf610 --- /dev/null +++ b/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.rb @@ -0,0 +1,17 @@ +# @param {Integer[]} nums +# @param {Integer} n +# @param {Integer} left +# @param {Integer} right +# @return {Integer} +def range_sum(nums, n, left, right) + sums = [] + (0...n).each do |i| + total = 0 + nums[i..-1].each do |value| + total += value + sums << total + end + end + sums.sort! + sums[left - 1...right].sum % 1000000007 +end diff --git a/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.rs b/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.rs new file mode 100644 index 00000000..9f8ce415 --- /dev/null +++ b/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.rs @@ -0,0 +1,20 @@ +impl Solution { + pub fn range_sum(nums: Vec, n: i32, left: i32, right: i32) -> i32 { + const MOD: i64 = 1_000_000_007; + let n = n as usize; + let mut sums = Vec::with_capacity(n * (n + 1) / 2); + for i in 0..n { + let mut total = 0i64; + for &v in &nums[i..] { + total += v as i64; + sums.push(total); + } + } + sums.sort(); + let mut result = 0i64; + for i in (left as usize - 1)..(right as usize) { + result = (result + sums[i]) % MOD; + } + result as i32 + } +} diff --git a/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.swift b/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.swift new file mode 100644 index 00000000..2f1f64f8 --- /dev/null +++ b/tests/1501-2000/1508. range-sum-of-sorted-subarray-sums/sol.swift @@ -0,0 +1,19 @@ +class Solution { + func rangeSum(_ nums: [Int], _ n: Int, _ left: Int, _ right: Int) -> Int { + let MOD = 1000000007 + var sums = [Int]() + for i in 0.. a - b); + let result = 0; + for (let i = left - 1; i < right; i++) { + result = (result + sums[i]) % MOD; + } + return result; +} diff --git a/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/manifest.yaml b/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/manifest.yaml new file mode 100644 index 00000000..4eafa805 --- /dev/null +++ b/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/manifest.yaml @@ -0,0 +1,218 @@ +entry: + id: 1509 + title: "minimum-difference-between-largest-and-smallest-value-in-three-moves" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().minDifference({nums})" + rust: "Solution::min_difference({nums})" + python3: "Solution().minDifference({nums})" + python2: "Solution().minDifference({nums})" + ruby: "min_difference({nums})" + java: "new Solution().minDifference({nums})" + csharp: "new Solution().MinDifference({nums})" + kotlin: "Solution().minDifference({nums})" + go: "minDifference({nums})" + dart: "Solution().minDifference({nums})" + swift: "Solution().minDifference({nums})" + typescript: "minDifference({nums})" +judge: + type: "exact" +limits: + time_ms: 2000 + memory_mb: 256 +oracle: + python3: + call: "Checker().minDifference(nums, {result})" + checker: | + class Checker: + def minDifference(self, nums, result): + if len(nums) <= 4: + expected = 0 + else: + values = sorted(nums) + n = len(values) + expected = min(values[n - 4] - values[0], values[n - 3] - values[1], values[n - 2] - values[2], values[n - 1] - values[3]) + return result == expected +seed: 1509 +tests: + - name: "minimum length one" + in: + nums: [7] + out: 0 + - name: "minimum length two" + in: + nums: [-5, 12] + out: 0 + - name: "minimum length three" + in: + nums: [3, 100, 20] + out: 0 + - name: "example one" + in: + nums: [5, 3, 2, 4] + out: 0 + - name: "example two" + in: + nums: [1, 5, 0, 10, 14] + out: 1 + - name: "all equal" + in: + nums: [4, 4, 4, 4, 4, 4] + out: 0 + - name: "four distinct values" + in: + nums: [1, 2, 3, 100] + out: 0 + - name: "five consecutive" + in: + nums: [1, 2, 3, 4, 5] + out: 1 + - name: "five widely spaced" + in: + nums: [0, 100, 200, 300, 400] + out: 100 + - name: "negative values" + in: + nums: [-10, -8, -6, -4, -2] + out: 2 + - name: "mixed signs" + in: + nums: [-100, -50, -1, 0, 50, 100] + out: 50 + - name: "unsorted duplicates" + in: + nums: [8, 1, 1, 1, 9, 10] + out: 0 + - name: "one extreme low" + in: + nums: [-1000, 2, 3, 4, 5, 6] + out: 2 + - name: "one extreme high" + in: + nums: [2, 3, 4, 5, 6, 1000] + out: 2 + - name: "two low outliers" + in: + nums: [-100, -90, 0, 1, 2, 3, 4] + out: 3 + - name: "two high outliers" + in: + nums: [0, 1, 2, 3, 4, 90, 100] + out: 3 + - name: "three low outliers" + in: + nums: [-30, -20, -10, 5, 6, 7, 8] + out: 3 + - name: "three high outliers" + in: + nums: [5, 6, 7, 8, 30, 40, 50] + out: 3 + - name: "four low outliers" + in: + nums: [-40, -30, -20, -10, 1, 2, 3, 4] + out: 14 + - name: "four high outliers" + in: + nums: [1, 2, 3, 4, 10, 20, 30, 40] + out: 9 + - name: "alternating order" + in: + nums: [100, 0, 99, 1, 98, 2, 97, 3] + out: 97 + - name: "cluster with gap" + in: + nums: [1, 1, 2, 2, 50, 50, 51, 51] + out: 49 + - name: "repeated extremes" + in: + nums: [-5, -5, 0, 0, 0, 10, 10, 10] + out: 5 + - name: "large positive bounds" + in: + nums: [1000000000, 999999999, 999999998, 999999997, 0] + out: 1 + - name: "large negative bounds" + in: + nums: [-1000000000, -999999999, -999999998, -999999997, 0] + out: 1 + - name: "full integer span" + in: + nums: [-1000000000, -1, 0, 1, 1000000000] + out: 1 + - name: "large span six" + in: + nums: [-1000000000, -500000000, -1, 1, 500000000, 1000000000] + out: 500000001 + - name: "already narrow" + in: + nums: [100, 101, 102, 103, 104, 105, 106] + out: 3 + - name: "single duplicate outlier" + in: + nums: [0, 0, 0, 0, 0, 100] + out: 0 + - name: "balanced gaps" + in: + nums: [0, 10, 20, 30, 40, 50, 60] + out: 30 + - name: "uneven gaps" + in: + nums: [0, 1, 10, 11, 100, 101, 1000] + out: 11 + - name: "negative duplicate core" + in: + nums: [-10, -9, -9, -9, 20, 21, 22] + out: 1 + - name: "descending input" + in: + nums: [9, 8, 7, 6, 5, 4, 3, 2] + out: 4 + - name: "near zero" + in: + nums: [-4, -3, -2, -1, 0, 1, 2, 3] + out: 4 + - name: "large duplicate bands" + in: + nums: + [-1000000000, -1000000000, 500000000, 500000000, 500000001, 1000000000] + out: 1 + - name: "seven random order" + in: + nums: [42, -7, 19, 100, 0, 18, 20] + out: 20 + - name: "eight tight middle" + in: + nums: [1000, 2, 3, 4, 5, 6, 7, -1000] + out: 4 + - name: "nine repeated center" + in: + nums: [1, 1, 1, 2, 2, 2, 3, 100, 200] + out: 1 + - name: "large generated lower bound" + in: + nums: + gen: "array" + len: 50000 + of: + gen: "int" + min: -1000000000 + max: 1000000000 + distinct: false + sorted: false + elemType: "int" + - name: "large generated upper bound" + 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/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.cpp b/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.cpp new file mode 100644 index 00000000..1b1690cc --- /dev/null +++ b/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int minDifference(vector& nums) { + if (nums.size() <= 3) { + return 0; + } + sort(nums.begin(), nums.end()); + int n = nums.size(); + return min({ + nums[n-4] - nums[0], + nums[n-3] - nums[1], + nums[n-2] - nums[2], + nums[n-1] - nums[3] + }); + } +}; diff --git a/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.cs b/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.cs new file mode 100644 index 00000000..edd8b16d --- /dev/null +++ b/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.cs @@ -0,0 +1,15 @@ +public class Solution { + public int MinDifference(int[] nums) { + if (nums.Length <= 3) { + return 0; + } + Array.Sort(nums); + int n = nums.Length; + return new int[] { + nums[n-4] - nums[0], + nums[n-3] - nums[1], + nums[n-2] - nums[2], + nums[n-1] - nums[3] + }.Min(); + } +} diff --git a/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.dart b/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.dart new file mode 100644 index 00000000..2ddb8e9e --- /dev/null +++ b/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.dart @@ -0,0 +1,15 @@ +class Solution { + int minDifference(List nums) { + if (nums.length <= 3) { + return 0; + } + nums.sort(); + int n = nums.length; + return [ + nums[n-4] - nums[0], + nums[n-3] - nums[1], + nums[n-2] - nums[2], + nums[n-1] - nums[3] + ].reduce((a, b) => a < b ? a : b); + } +} diff --git a/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.go b/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.go new file mode 100644 index 00000000..0d6aae7e --- /dev/null +++ b/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.go @@ -0,0 +1,27 @@ +func minDifference(nums []int) int { + if len(nums) <= 3 { + return 0 + } + sort.Ints(nums) + n := len(nums) + return min( + nums[n-4] - nums[0], + nums[n-3] - nums[1], + nums[n-2] - nums[2], + nums[n-1] - nums[3], + ) +} + +func min(a, b, c, d int) int { + m := a + if b < m { + m = b + } + if c < m { + m = c + } + if d < m { + m = d + } + return m +} diff --git a/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.java b/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.java new file mode 100644 index 00000000..70636e33 --- /dev/null +++ b/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.java @@ -0,0 +1,13 @@ +class Solution { + public int minDifference(int[] nums) { + if (nums.length <= 3) { + return 0; + } + Arrays.sort(nums); + int n = nums.length; + return Math.min( + Math.min(nums[n-4] - nums[0], nums[n-3] - nums[1]), + Math.min(nums[n-2] - nums[2], nums[n-1] - nums[3]) + ); + } +} diff --git a/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.kt b/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.kt new file mode 100644 index 00000000..93fdd163 --- /dev/null +++ b/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.kt @@ -0,0 +1,15 @@ +class Solution { + fun minDifference(nums: IntArray): Int { + if (nums.size <= 3) { + return 0 + } + nums.sort() + val n = nums.size + return minOf( + nums[n-4] - nums[0], + nums[n-3] - nums[1], + nums[n-2] - nums[2], + nums[n-1] - nums[3] + ) + } +} diff --git a/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.py b/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.py new file mode 100644 index 00000000..3bd14994 --- /dev/null +++ b/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.py @@ -0,0 +1,45 @@ +""" +Complexity Analysis: + - Greedy: + 1) Time Complexity: O(nlogn) + 2) Space Complexity: O(1) + - DFS: + 1) Time Complexity: O(nlogn) + 2) Space Complexity: O(1) +""" + + +class Greedy: + def find_min_difference(self, nums): + if len(nums) <= 3: + return 0 + nums.sort() + n = len(nums) + return min( + nums[n - 4] - nums[0], + nums[n - 3] - nums[1], + nums[n - 2] - nums[2], + nums[n - 1] - nums[3], + ) + + +class DFS: + def get_min_difference(self, start, end, steps, nums): + if steps == 0: + return nums[end] - nums[start] + return min( + self.get_min_difference(start + 1, end, steps - 1, nums), + self.get_min_difference(start, end - 1, steps - 1, nums), + ) + + def find_min_difference(self, nums): + if len(nums) <= 3: + return 0 + nums.sort() + return self.get_min_difference(0, len(nums) - 1, 3, nums) + + +class Solution: + def minDifference(self, nums: List[int]) -> int: + # return Greedy().find_min_difference(nums) + return DFS().find_min_difference(nums) diff --git a/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.py2 b/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.py2 new file mode 100644 index 00000000..e2849cc5 --- /dev/null +++ b/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def minDifference(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + if len(nums) <= 3: + return 0 + nums.sort() + n = len(nums) + return min( + nums[n-4] - nums[0], + nums[n-3] - nums[1], + nums[n-2] - nums[2], + nums[n-1] - nums[3] + ) diff --git a/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.rb b/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.rb new file mode 100644 index 00000000..700efcbb --- /dev/null +++ b/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.rb @@ -0,0 +1,13 @@ +# @param {Integer[]} nums +# @return {Integer} +def min_difference(nums) + return 0 if nums.length <= 3 + nums.sort! + n = nums.length + return [ + nums[n-4] - nums[0], + nums[n-3] - nums[1], + nums[n-2] - nums[2], + nums[n-1] - nums[3] + ].min +end diff --git a/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.rs b/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.rs new file mode 100644 index 00000000..e53f97c0 --- /dev/null +++ b/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn min_difference(nums: Vec) -> i32 { + if nums.len() <= 3 { + return 0; + } + let mut nums = nums; + nums.sort(); + let n = nums.len(); + *[ + nums[n-4] - nums[0], + nums[n-3] - nums[1], + nums[n-2] - nums[2], + nums[n-1] - nums[3], + ].iter().min().unwrap() + } +} diff --git a/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.swift b/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.swift new file mode 100644 index 00000000..17ebd789 --- /dev/null +++ b/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.swift @@ -0,0 +1,15 @@ +class Solution { + func minDifference(_ nums: [Int]) -> Int { + if nums.count <= 3 { + return 0 + } + let sorted = nums.sorted() + let n = sorted.count + return min( + sorted[n-4] - sorted[0], + sorted[n-3] - sorted[1], + sorted[n-2] - sorted[2], + sorted[n-1] - sorted[3] + ) + } +} diff --git a/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.ts b/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.ts new file mode 100644 index 00000000..370d3191 --- /dev/null +++ b/tests/1501-2000/1509. minimum-difference-between-largest-and-smallest-value-in-three-moves/sol.ts @@ -0,0 +1,13 @@ +function minDifference(nums: number[]): number { + if (nums.length <= 3) { + return 0; + } + nums.sort((a, b) => a - b); + const n = nums.length; + return Math.min( + nums[n - 4] - nums[0], + nums[n - 3] - nums[1], + nums[n - 2] - nums[2], + nums[n - 1] - nums[3], + ); +} diff --git a/tests/1501-2000/1510. stone-game-iv/manifest.yaml b/tests/1501-2000/1510. stone-game-iv/manifest.yaml new file mode 100644 index 00000000..57f35150 --- /dev/null +++ b/tests/1501-2000/1510. stone-game-iv/manifest.yaml @@ -0,0 +1,186 @@ +entry: + id: 1510 + title: "stone-game-iv" + params: + n: + type: int + call: + cpp: "Solution().winnerSquareGame({n})" + rust: "Solution::winner_square_game({n})" + python3: "Solution().winnerSquareGame({n})" + python2: "Solution().winnerSquareGame({n})" + ruby: "winner_square_game({n})" + java: "new Solution().winnerSquareGame({n})" + csharp: "new Solution().WinnerSquareGame({n})" + kotlin: "Solution().winnerSquareGame({n})" + go: "winnerSquareGame({n})" + dart: "Solution().winnerSquareGame({n})" + swift: "Solution().winnerSquareGame({n})" + typescript: "winnerSquareGame({n})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().winnerSquareGame(n, {result})" + checker: | + class Checker: + def winnerSquareGame(self, n, result): + if not isinstance(result, bool): + return False + win = [False] * (n + 1) + for stones in range(1, n + 1): + square = 1 + while square * square <= stones: + if not win[stones - square * square]: + win[stones] = True + break + square += 1 + return result == win[n] + +seed: 1510 + +tests: + - name: "example_one" + in: + n: 1 + out: true + - name: "example_two" + in: + n: 2 + out: false + - name: "example_four" + in: + n: 4 + out: true + - name: "small_three" + in: + n: 3 + - name: "small_five" + in: + n: 5 + - name: "small_six" + in: + n: 6 + - name: "small_seven" + in: + n: 7 + - name: "small_eight" + in: + n: 8 + - name: "small_nine" + in: + n: 9 + - name: "square_sixteen" + in: + n: 16 + - name: "square_twenty_five" + in: + n: 25 + - name: "square_one_hundred" + in: + n: 100 + - name: "near_square_ten" + in: + n: 10 + - name: "near_square_fifteen" + in: + n: 15 + - name: "near_square_seventeen" + in: + n: 17 + - name: "near_square_twenty_four" + in: + n: 24 + - name: "near_square_twenty_six" + in: + n: 26 + - name: "middle_thirty" + in: + n: 30 + - name: "middle_fifty" + in: + n: 50 + - name: "middle_seventy_three" + in: + n: 73 + - name: "middle_one_fifty" + in: + n: 150 + - name: "middle_two_fifty_six" + in: + n: 256 + - name: "middle_five_hundred" + in: + n: 500 + - name: "large_one_thousand" + in: + n: 1000 + - name: "large_one_thousand_one" + in: + n: 1001 + - name: "large_ten_thousand" + in: + n: 10000 + - name: "large_ten_thousand_one" + in: + n: 10001 + - name: "large_half_limit" + in: + n: 50000 + - name: "maximum_limit" + in: + n: 100000 + - name: "generated_low" + in: + n: + gen: "int" + min: 1 + max: 100 + - name: "generated_lower_middle" + in: + n: + gen: "int" + min: 101 + max: 1000 + - name: "generated_middle" + in: + n: + gen: "int" + min: 1001 + max: 10000 + - name: "generated_upper_middle" + in: + n: + gen: "int" + min: 10001 + max: 50000 + - name: "generated_high" + in: + n: + gen: "int" + min: 50001 + max: 100000 + - name: "boundary_two" + in: + n: 2 + - name: "boundary_limit_minus_one" + in: + n: 99999 + - name: "square_nine_hundred" + in: + n: 900 + - name: "near_square_nine_hundred_one" + in: + n: 901 + - name: "maximum_adjacent_square" + in: + n: 99856 + - name: "maximum_near_limit" + in: + n: 99998 diff --git a/tests/1501-2000/1510. stone-game-iv/sol.cpp b/tests/1501-2000/1510. stone-game-iv/sol.cpp new file mode 100644 index 00000000..4d13aef7 --- /dev/null +++ b/tests/1501-2000/1510. stone-game-iv/sol.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + bool winnerSquareGame(int n) { + vector> memo(2, vector(n + 1, -1)); + function dp = [&](int player, int stones) -> bool { + if (stones == 0) return false; + if (memo[player][stones] != -1) return memo[player][stones] == 1; + int sqrt = (int)std::sqrt(stones); + for (int i = sqrt; i >= 1; i--) { + int sq = i * i; + if (sq == stones || !dp(player ^ 1, stones - sq)) { + memo[player][stones] = 1; + return true; + } + } + memo[player][stones] = 0; + return false; + }; + return dp(0, n); + } +}; diff --git a/tests/1501-2000/1510. stone-game-iv/sol.cs b/tests/1501-2000/1510. stone-game-iv/sol.cs new file mode 100644 index 00000000..9209b7b1 --- /dev/null +++ b/tests/1501-2000/1510. stone-game-iv/sol.cs @@ -0,0 +1,25 @@ +public class Solution { + public bool WinnerSquareGame(int n) { + int[][] memo = new int[2][]; + for (int i = 0; i < 2; i++) { + memo[i] = new int[n + 1]; + System.Array.Fill(memo[i], -1); + } + return dp(0, n, memo); + } + + private bool dp(int player, int stones, int[][] memo) { + if (stones == 0) return false; + if (memo[player][stones] != -1) return memo[player][stones] == 1; + int sqrt = (int)System.Math.Sqrt(stones); + for (int i = sqrt; i >= 1; i--) { + int sq = i * i; + if (sq == stones || !dp(player ^ 1, stones - sq, memo)) { + memo[player][stones] = 1; + return true; + } + } + memo[player][stones] = 0; + return false; + } +} diff --git a/tests/1501-2000/1510. stone-game-iv/sol.dart b/tests/1501-2000/1510. stone-game-iv/sol.dart new file mode 100644 index 00000000..7d954525 --- /dev/null +++ b/tests/1501-2000/1510. stone-game-iv/sol.dart @@ -0,0 +1,22 @@ +import 'dart:math' as math; + +class Solution { + bool winnerSquareGame(int n) { + List> memo = List.generate(2, (_) => List.filled(n + 1, -1)); + bool dp(int player, int stones) { + if (stones == 0) return false; + if (memo[player][stones] != -1) return memo[player][stones] == 1; + int sqrt = math.sqrt(stones).toInt(); + for (int i = sqrt; i >= 1; i--) { + int sq = i * i; + if (sq == stones || !dp(player ^ 1, stones - sq)) { + memo[player][stones] = 1; + return true; + } + } + memo[player][stones] = 0; + return false; + } + return dp(0, n); + } +} diff --git a/tests/1501-2000/1510. stone-game-iv/sol.go b/tests/1501-2000/1510. stone-game-iv/sol.go new file mode 100644 index 00000000..49dcccd8 --- /dev/null +++ b/tests/1501-2000/1510. stone-game-iv/sol.go @@ -0,0 +1,29 @@ +func winnerSquareGame(n int) bool { + memo := make([][]int, 2) + for i := range memo { + memo[i] = make([]int, n+1) + for j := range memo[i] { + memo[i][j] = -1 + } + } + var dp func(player, stones int) bool + dp = func(player, stones int) bool { + if stones == 0 { + return false + } + if memo[player][stones] != -1 { + return memo[player][stones] == 1 + } + sqrt := int(math.Sqrt(float64(stones))) + for i := sqrt; i >= 1; i-- { + sq := i * i + if sq == stones || !dp(player^1, stones-sq) { + memo[player][stones] = 1 + return true + } + } + memo[player][stones] = 0 + return false + } + return dp(0, n) +} diff --git a/tests/1501-2000/1510. stone-game-iv/sol.java b/tests/1501-2000/1510. stone-game-iv/sol.java new file mode 100644 index 00000000..74334699 --- /dev/null +++ b/tests/1501-2000/1510. stone-game-iv/sol.java @@ -0,0 +1,24 @@ +class Solution { + public boolean winnerSquareGame(int n) { + int[][] memo = new int[2][n + 1]; + for (int i = 0; i < 2; i++) { + java.util.Arrays.fill(memo[i], -1); + } + return dp(0, n, memo); + } + + private boolean dp(int player, int stones, int[][] memo) { + if (stones == 0) return false; + if (memo[player][stones] != -1) return memo[player][stones] == 1; + int sqrt = (int) Math.sqrt(stones); + for (int i = sqrt; i >= 1; i--) { + int sq = i * i; + if (sq == stones || !dp(player ^ 1, stones - sq, memo)) { + memo[player][stones] = 1; + return true; + } + } + memo[player][stones] = 0; + return false; + } +} diff --git a/tests/1501-2000/1510. stone-game-iv/sol.kt b/tests/1501-2000/1510. stone-game-iv/sol.kt new file mode 100644 index 00000000..43489c2d --- /dev/null +++ b/tests/1501-2000/1510. stone-game-iv/sol.kt @@ -0,0 +1,20 @@ +class Solution { + fun winnerSquareGame(n: Int): Boolean { + val memo = Array(2) { IntArray(n + 1) { -1 } } + fun dp(player: Int, stones: Int): Boolean { + if (stones == 0) return false + if (memo[player][stones] != -1) return memo[player][stones] == 1 + val sqrt = kotlin.math.sqrt(stones.toDouble()).toInt() + for (i in sqrt downTo 1) { + val sq = i * i + if (sq == stones || !dp(player xor 1, stones - sq)) { + memo[player][stones] = 1 + return true + } + } + memo[player][stones] = 0 + return false + } + return dp(0, n) + } +} diff --git a/tests/1501-2000/1510. stone-game-iv/sol.py b/tests/1501-2000/1510. stone-game-iv/sol.py new file mode 100644 index 00000000..189a35fb --- /dev/null +++ b/tests/1501-2000/1510. stone-game-iv/sol.py @@ -0,0 +1,11 @@ +class Solution: + def winnerSquareGame(self, n: int) -> bool: + @cache + def dp(player: int, stones: int) -> int: + sqrt = int(math.sqrt(stones)) + for i in range(sqrt, 0, -1): + if i**2 == stones or not dp(player ^ 1, stones - i**2): + return True + return False + + return dp(0, n) diff --git a/tests/1501-2000/1510. stone-game-iv/sol.py2 b/tests/1501-2000/1510. stone-game-iv/sol.py2 new file mode 100644 index 00000000..a93ee589 --- /dev/null +++ b/tests/1501-2000/1510. stone-game-iv/sol.py2 @@ -0,0 +1,21 @@ +class Solution(object): + def winnerSquareGame(self, n): + """ + :type n: int + :rtype: bool + """ + import math + memo = {} + def dp(player, stones): + if stones == 0: + return False + if (player, stones) in memo: + return memo[(player, stones)] + sqrt = int(math.sqrt(stones)) + for i in range(sqrt, 0, -1): + if i * i == stones or not dp(player ^ 1, stones - i * i): + memo[(player, stones)] = True + return True + memo[(player, stones)] = False + return False + return dp(0, n) diff --git a/tests/1501-2000/1510. stone-game-iv/sol.rb b/tests/1501-2000/1510. stone-game-iv/sol.rb new file mode 100644 index 00000000..5f37c463 --- /dev/null +++ b/tests/1501-2000/1510. stone-game-iv/sol.rb @@ -0,0 +1,21 @@ +# @param {Integer} n +# @return {Boolean} +def winner_square_game(n) + memo = {} + dp = lambda do |player, stones| + return false if stones == 0 + key = [player, stones] + return memo[key] if memo.key?(key) + sqrt = Integer.sqrt(stones) + sqrt.downto(1) do |i| + sq = i * i + if sq == stones || !dp.call(player ^ 1, stones - sq) + memo[key] = true + return true + end + end + memo[key] = false + false + end + dp.call(0, n) +end diff --git a/tests/1501-2000/1510. stone-game-iv/sol.rs b/tests/1501-2000/1510. stone-game-iv/sol.rs new file mode 100644 index 00000000..99fe6ecd --- /dev/null +++ b/tests/1501-2000/1510. stone-game-iv/sol.rs @@ -0,0 +1,25 @@ +impl Solution { + pub fn winner_square_game(n: i32) -> bool { + let n = n as usize; + let mut memo = vec![vec![-1i8; n + 1]; 2]; + fn dp(player: usize, stones: usize, memo: &mut Vec>) -> bool { + if stones == 0 { + return false; + } + if memo[player][stones] != -1 { + return memo[player][stones] == 1; + } + let sqrt = (stones as f64).sqrt() as usize; + for i in (1..=sqrt).rev() { + let sq = i * i; + if sq == stones || !dp(player ^ 1, stones - sq, memo) { + memo[player][stones] = 1; + return true; + } + } + memo[player][stones] = 0; + false + } + dp(0, n, &mut memo) + } +} diff --git a/tests/1501-2000/1510. stone-game-iv/sol.swift b/tests/1501-2000/1510. stone-game-iv/sol.swift new file mode 100644 index 00000000..8976a08c --- /dev/null +++ b/tests/1501-2000/1510. stone-game-iv/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func winnerSquareGame(_ n: Int) -> Bool { + var memo = Array(repeating: Array(repeating: -1, count: n + 1), count: 2) + func dp(_ player: Int, _ stones: Int) -> Bool { + if stones == 0 { return false } + if memo[player][stones] != -1 { return memo[player][stones] == 1 } + let sqrt = Int(Double(stones).squareRoot()) + for i in stride(from: sqrt, through: 1, by: -1) { + let sq = i * i + if sq == stones || !dp(player ^ 1, stones - sq) { + memo[player][stones] = 1 + return true + } + } + memo[player][stones] = 0 + return false + } + return dp(0, n) + } +} diff --git a/tests/1501-2000/1510. stone-game-iv/sol.ts b/tests/1501-2000/1510. stone-game-iv/sol.ts new file mode 100644 index 00000000..ac39b3d1 --- /dev/null +++ b/tests/1501-2000/1510. stone-game-iv/sol.ts @@ -0,0 +1,20 @@ +function winnerSquareGame(n: number): boolean { + const memo: number[][] = Array.from({ length: 2 }, () => + Array(n + 1).fill(-1), + ); + const dp = (player: number, stones: number): boolean => { + if (stones === 0) return false; + if (memo[player][stones] !== -1) return memo[player][stones] === 1; + const sqrt = Math.floor(Math.sqrt(stones)); + for (let i = sqrt; i >= 1; i--) { + const sq = i * i; + if (sq === stones || !dp(player ^ 1, stones - sq)) { + memo[player][stones] = 1; + return true; + } + } + memo[player][stones] = 0; + return false; + }; + return dp(0, n); +} diff --git a/tests/1501-2000/1512. number-of-good-pairs/manifest.yaml b/tests/1501-2000/1512. number-of-good-pairs/manifest.yaml new file mode 100644 index 00000000..a57b5652 --- /dev/null +++ b/tests/1501-2000/1512. number-of-good-pairs/manifest.yaml @@ -0,0 +1,779 @@ +entry: + id: 1512 + title: "number-of-good-pairs" + params: + nums: + type: array + items: + type: int + call: + python3: "Solution().numIdenticalPairs({nums})" + python2: "Solution().numIdenticalPairs({nums})" + java: "new Solution().numIdenticalPairs({nums})" + kotlin: "Solution().numIdenticalPairs({nums})" + go: "numIdenticalPairs({nums})" + rust: "Solution::num_identical_pairs({nums})" + cpp: "Solution().numIdenticalPairs({nums})" + csharp: "new Solution().NumIdenticalPairs({nums})" + ruby: "num_identical_pairs({nums})" + dart: "Solution().numIdenticalPairs({nums})" + swift: "Solution().numIdenticalPairs({nums})" + typescript: "numIdenticalPairs({nums})" +judge: + type: "exact" +limits: + time_ms: 300 + memory_mb: 300 +oracle: + python3: + call: "Checker().numIdenticalPairs(nums, {result})" + checker: | + class Checker: + def numIdenticalPairs(self, nums, result): + if not isinstance(result, int): + return False + expected = 0 + for i in range(len(nums)): + for j in range(i + 1, len(nums)): + if nums[i] == nums[j]: + expected += 1 + return result == expected +seed: 1512 +tests: + - name: "example_one" + in: + nums: [1, 2, 3, 1, 1, 3] + out: 4 + - name: "example_two" + in: + nums: [1, 1, 1, 1] + out: 6 + - name: "example_three" + in: + nums: [1, 2, 3] + out: 0 + - name: "alternating_pair_values" + in: + nums: [1, 2, 1, 2] + out: 2 + - name: "five_distinct" + in: + nums: [1, 2, 3, 4, 5] + out: 0 + - name: "three_duplicate_groups" + in: + nums: [1, 1, 2, 2, 3, 3] + out: 3 + - name: "repeated_cycle" + in: + nums: [1, 2, 3, 1, 2, 3] + out: 3 + - name: "dominant_late_value" + in: + nums: [5, 5, 5, 2, 2, 5] + out: 7 + - name: "one_value_interleaved" + in: + nums: [1, 2, 1, 3, 1, 4] + out: 3 + - name: "two_interleaved_groups" + in: + nums: [7, 7, 8, 8, 7, 8] + out: 6 + - name: "uneven_groups" + in: + nums: [1, 1, 1, 2, 2, 3] + out: 4 + - name: "four_pairs_spaced" + in: + nums: [1, 2, 3, 4, 1, 2, 3, 4] + out: 4 + - name: "descending_distinct" + in: + nums: [9, 8, 7, 6, 5, 4, 3, 2, 1] + out: 0 + - name: "ten_equal" + in: + nums: [2, 2, 2, 2, 2, 2, 2, 2, 2, 2] + out: 45 + - name: "ten_distinct" + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + out: 0 + - name: "single_duplicate_among_distinct" + in: + nums: [1, 1, 2, 3, 4, 5, 6, 7, 8, 9] + out: 1 + - name: "four_repeated_twice" + in: + nums: [1, 2, 1, 2, 1, 2, 1, 2] + out: 12 + - name: "five_values_twice" + in: + nums: [1, 3, 5, 7, 9, 1, 3, 5, 7, 9] + out: 5 + - name: "one_heavy_three_single_pairs" + in: + nums: [4, 4, 4, 4, 5, 5, 6, 6, 7] + out: 8 + - name: "five_values_two_cycles" + in: + nums: [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] + out: 5 + - name: "five_pairs_at_end" + in: + nums: [10, 10, 9, 9, 8, 8, 7, 7, 6, 6] + out: 5 + - name: "three_large_groups" + in: + nums: [1, 1, 1, 1, 1, 2, 2, 2, 2, 3] + out: 16 + - name: "six_values_two_cycles" + in: + nums: [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6] + out: 6 + - name: "three_value_mirror" + in: + nums: [3, 3, 2, 2, 1, 1, 3, 2, 1] + out: 9 + - name: "eight_values_two_cycles" + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8] + out: 8 + - name: "six_duplicate_groups" + in: + nums: [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6] + out: 6 + - name: "twenty_equal" + in: + nums: + [ + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + ] + out: 190 + - name: "four_cycles_of_three" + in: + nums: [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3] + out: 18 + - name: "four_equal_groups" + in: + nums: [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4] + out: 12 + - name: "boundary_values_repeated" + in: + nums: [1, 100, 1, 100, 1, 100, 1, 100] + out: 12 + - name: "maximum_all_equal" + in: + nums: + [ + 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, + 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, + ] + out: 4950 + - name: "maximum_all_distinct" + 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, + ] + out: 0 + - name: "maximum_two_full_cycles" + 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, + 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: 50 + - name: "maximum_unbalanced_two_values" + 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, + 1, + 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, + 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: 3075 + - name: "maximum_ten_equal_groups" + in: + nums: + [ + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 6, + 6, + 6, + 6, + 6, + 6, + 6, + 6, + 6, + 6, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 8, + 8, + 8, + 8, + 8, + 8, + 8, + 8, + 8, + 8, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + ] + out: 450 + - name: "generated_max_all_equal" + seed: 151201 + in: + nums: + gen: "array" + len: 100 + of: + gen: "int" + min: 42 + max: 42 + distinct: false + sorted: false + elemType: "int" + - name: "generated_max_all_distinct" + seed: 151202 + in: + nums: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 100 + distinct: true + sorted: false + elemType: "int" + - name: "generated_two_value_domain" + seed: 151203 + in: + nums: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 2 + distinct: false + sorted: false + elemType: "int" + - name: "generated_fifty_value_domain" + seed: 151204 + in: + nums: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 50 + distinct: false + sorted: false + elemType: "int" + - name: "generated_full_value_domain" + seed: 151205 + in: + nums: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + sorted: false + elemType: "int" diff --git a/tests/1501-2000/1512. number-of-good-pairs/sol.cpp b/tests/1501-2000/1512. number-of-good-pairs/sol.cpp new file mode 100644 index 00000000..ed441397 --- /dev/null +++ b/tests/1501-2000/1512. number-of-good-pairs/sol.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int numIdenticalPairs(vector& nums) { + unordered_map pairs; + int count = 0; + for (int num : nums) { + if (pairs.find(num) != pairs.end()) { + count += pairs[num]; + } + pairs[num]++; + } + return count; + } +}; diff --git a/tests/1501-2000/1512. number-of-good-pairs/sol.cs b/tests/1501-2000/1512. number-of-good-pairs/sol.cs new file mode 100644 index 00000000..7731b1b0 --- /dev/null +++ b/tests/1501-2000/1512. number-of-good-pairs/sol.cs @@ -0,0 +1,13 @@ +public class Solution { + public int NumIdenticalPairs(int[] nums) { + var pairs = new Dictionary(); + int count = 0; + foreach (int num in nums) { + if (pairs.ContainsKey(num)) { + count += pairs[num]; + } + pairs[num] = pairs.GetValueOrDefault(num, 0) + 1; + } + return count; + } +} diff --git a/tests/1501-2000/1512. number-of-good-pairs/sol.dart b/tests/1501-2000/1512. number-of-good-pairs/sol.dart new file mode 100644 index 00000000..f6f9d5ba --- /dev/null +++ b/tests/1501-2000/1512. number-of-good-pairs/sol.dart @@ -0,0 +1,13 @@ +class Solution { + int numIdenticalPairs(List nums) { + var pairs = {}; + int count = 0; + for (var num in nums) { + if (pairs.containsKey(num)) { + count += pairs[num]!; + } + pairs[num] = (pairs[num] ?? 0) + 1; + } + return count; + } +} diff --git a/tests/1501-2000/1512. number-of-good-pairs/sol.go b/tests/1501-2000/1512. number-of-good-pairs/sol.go new file mode 100644 index 00000000..055d6c6b --- /dev/null +++ b/tests/1501-2000/1512. number-of-good-pairs/sol.go @@ -0,0 +1,11 @@ +func numIdenticalPairs(nums []int) int { + pairs := make(map[int]int) + count := 0 + for _, num := range nums { + if val, ok := pairs[num]; ok { + count += val + } + pairs[num]++ + } + return count +} diff --git a/tests/1501-2000/1512. number-of-good-pairs/sol.java b/tests/1501-2000/1512. number-of-good-pairs/sol.java new file mode 100644 index 00000000..03b62f7a --- /dev/null +++ b/tests/1501-2000/1512. number-of-good-pairs/sol.java @@ -0,0 +1,13 @@ +class Solution { + public int numIdenticalPairs(int[] nums) { + java.util.Map pairs = new java.util.HashMap<>(); + int count = 0; + for (int num : nums) { + if (pairs.containsKey(num)) { + count += pairs.get(num); + } + pairs.put(num, pairs.getOrDefault(num, 0) + 1); + } + return count; + } +} diff --git a/tests/1501-2000/1512. number-of-good-pairs/sol.kt b/tests/1501-2000/1512. number-of-good-pairs/sol.kt new file mode 100644 index 00000000..1f1e0058 --- /dev/null +++ b/tests/1501-2000/1512. number-of-good-pairs/sol.kt @@ -0,0 +1,13 @@ +class Solution { + fun numIdenticalPairs(nums: IntArray): Int { + val pairs = mutableMapOf() + var count = 0 + for (num in nums) { + if (pairs.containsKey(num)) { + count += pairs[num]!! + } + pairs[num] = pairs.getOrDefault(num, 0) + 1 + } + return count + } +} diff --git a/tests/1501-2000/1512. number-of-good-pairs/sol.py b/tests/1501-2000/1512. number-of-good-pairs/sol.py new file mode 100644 index 00000000..b329891c --- /dev/null +++ b/tests/1501-2000/1512. number-of-good-pairs/sol.py @@ -0,0 +1,12 @@ +class Solution: + def numIdenticalPairs(self, nums: List[int]) -> int: + pairs = {} + count = 0 + + for i in range(len(nums)): + if nums[i] in pairs: + count += pairs[nums[i]] + + pairs[nums[i]] = pairs.get(nums[i], 0) + 1 + + return count diff --git a/tests/1501-2000/1512. number-of-good-pairs/sol.py2 b/tests/1501-2000/1512. number-of-good-pairs/sol.py2 new file mode 100644 index 00000000..70a8f57b --- /dev/null +++ b/tests/1501-2000/1512. number-of-good-pairs/sol.py2 @@ -0,0 +1,13 @@ +class Solution(object): + def numIdenticalPairs(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + pairs = {} + count = 0 + for i in range(len(nums)): + if nums[i] in pairs: + count += pairs[nums[i]] + pairs[nums[i]] = pairs.get(nums[i], 0) + 1 + return count diff --git a/tests/1501-2000/1512. number-of-good-pairs/sol.rb b/tests/1501-2000/1512. number-of-good-pairs/sol.rb new file mode 100644 index 00000000..e569433d --- /dev/null +++ b/tests/1501-2000/1512. number-of-good-pairs/sol.rb @@ -0,0 +1,13 @@ +# @param {Integer[]} nums +# @return {Integer} +def num_identical_pairs(nums) + pairs = {} + count = 0 + nums.each do |num| + if pairs.key?(num) + count += pairs[num] + end + pairs[num] = (pairs[num] || 0) + 1 + end + count +end diff --git a/tests/1501-2000/1512. number-of-good-pairs/sol.rs b/tests/1501-2000/1512. number-of-good-pairs/sol.rs new file mode 100644 index 00000000..d0787be1 --- /dev/null +++ b/tests/1501-2000/1512. number-of-good-pairs/sol.rs @@ -0,0 +1,13 @@ +impl Solution { + pub fn num_identical_pairs(nums: Vec) -> i32 { + let mut pairs = std::collections::HashMap::new(); + let mut count = 0; + for num in nums { + if let Some(&val) = pairs.get(&num) { + count += val; + } + *pairs.entry(num).or_insert(0) += 1; + } + count + } +} diff --git a/tests/1501-2000/1512. number-of-good-pairs/sol.swift b/tests/1501-2000/1512. number-of-good-pairs/sol.swift new file mode 100644 index 00000000..da7ded54 --- /dev/null +++ b/tests/1501-2000/1512. number-of-good-pairs/sol.swift @@ -0,0 +1,13 @@ +class Solution { + func numIdenticalPairs(_ nums: [Int]) -> Int { + var pairs = [Int: Int]() + var count = 0 + for num in nums { + if let val = pairs[num] { + count += val + } + pairs[num, default: 0] += 1 + } + return count + } +} diff --git a/tests/1501-2000/1512. number-of-good-pairs/sol.ts b/tests/1501-2000/1512. number-of-good-pairs/sol.ts new file mode 100644 index 00000000..2b7f6225 --- /dev/null +++ b/tests/1501-2000/1512. number-of-good-pairs/sol.ts @@ -0,0 +1,11 @@ +function numIdenticalPairs(nums: number[]): number { + const pairs: { [key: number]: number } = {}; + let count = 0; + for (const num of nums) { + if (pairs[num] !== undefined) { + count += pairs[num]; + } + pairs[num] = (pairs[num] || 0) + 1; + } + return count; +} diff --git a/tests/1501-2000/1513. number-of-substrings-with-only-1s/manifest.yaml b/tests/1501-2000/1513. number-of-substrings-with-only-1s/manifest.yaml new file mode 100644 index 00000000..862869cb --- /dev/null +++ b/tests/1501-2000/1513. number-of-substrings-with-only-1s/manifest.yaml @@ -0,0 +1,203 @@ +entry: + id: 1513 + title: "number-of-substrings-with-only-1s" + params: + s: + type: string + call: + cpp: "Solution().numSub({s})" + rust: "Solution::num_sub({s})" + python3: "Solution().numSub({s})" + python2: "Solution().numSub({s})" + ruby: "num_sub({s})" + java: "new Solution().numSub({s})" + csharp: "new Solution().NumSub({s})" + kotlin: "Solution().numSub({s})" + go: "numSub({s})" + dart: "Solution().numSub({s})" + swift: "Solution().numSub({s})" + typescript: "numSub({s})" + +judge: + type: "exact" + +limits: + time_ms: 500 + memory_mb: 300 + +oracle: + python3: + call: "Checker().numSub(s, {result})" + checker: | + class Checker: + def numSub(self, s, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + mod = 1000000007 + expected = 0 + run = 0 + for ch in s: + if ch == "1": + run += 1 + else: + run = 0 + expected = (expected + run) % mod + return result == expected + +seed: 1513 + +tests: + - name: "example_1" + in: + s: "0110111" + out: 9 + - name: "example_2" + in: + s: "101" + out: 2 + - name: "example_3" + in: + s: "111111" + out: 21 + - name: "single_zero" + in: + s: "0" + out: 0 + - name: "single_one" + in: + s: "1" + out: 1 + - name: "two_zeros" + in: + s: "00" + out: 0 + - name: "two_ones" + in: + s: "11" + out: 3 + - name: "alternating_even" + in: + s: "10101010" + - name: "alternating_odd" + in: + s: "01010101" + - name: "zero_then_run" + in: + s: "01111" + - name: "run_then_zero" + in: + s: "11110" + - name: "zero_between_runs" + in: + s: "1110111" + - name: "zeros_between_singletons" + in: + s: "100010001" + - name: "leading_zeros" + in: + s: "00000111" + - name: "trailing_zeros" + in: + s: "11100000" + - name: "all_zeros_16" + in: + s: "0000000000000000" + - name: "all_ones_16" + in: + s: "1111111111111111" + - name: "two_runs_different" + in: + s: "1101111110" + - name: "many_short_runs" + in: + s: "1101101101101101" + - name: "isolated_ones" + in: + s: "1001001001001001001" + - name: "single_gap" + in: + s: "1111011111" + - name: "single_zero_middle" + in: + s: "11101111111" + - name: "one_at_each_end" + in: + s: "10000000001" + - name: "palindrome_mixed" + in: + s: "11010101101" + - name: "long_prefix_run" + in: + s: "1111111111010101" + - name: "long_suffix_run" + in: + s: "0101010111111111111" + - name: "runs_1_2_3_4" + in: + s: "1011011101111" + - name: "runs_4_3_2_1" + in: + s: "1111011101101" + - name: "dense_mixed_32" + in: + s: "11101101111000111101011101110111" + - name: "mostly_zero_mixed" + in: + s: "000100001000011000000100001" + - name: "medium_all_ones" + in: + s: "11111111111111111111111111111111111111111111111111" + - name: "medium_alternating" + in: + s: "1010101010101010101010101010101010101010101010101010" + - name: "medium_blocks" + in: + s: "11111000001111100000111110000011111" + - name: "generated_small_binary" + in: + s: + gen: "str" + len: + gen: "int" + min: 1 + max: 80 + alphabet: "01" + - name: "generated_medium_binary" + in: + s: + gen: "str" + len: + gen: "int" + min: 500 + max: 1500 + alphabet: "01" + - name: "generated_bounded_stress_a" + in: + s: + gen: "str" + len: 5000 + alphabet: "01" + - name: "generated_bounded_stress_b" + in: + s: + gen: "str" + len: 7500 + alphabet: "01" + - name: "generated_max_all_ones" + in: + s: + gen: "str" + len: 100000 + alphabet: "1" + - name: "generated_max_all_zeros" + in: + s: + gen: "str" + len: 100000 + alphabet: "0" + - name: "generated_max_binary_stress" + in: + s: + gen: "str" + len: 100000 + alphabet: "01" diff --git a/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.cpp b/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.cpp new file mode 100644 index 00000000..7b7b5d2b --- /dev/null +++ b/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int numSub(string s) { + int cnt = 0; + int total = 0; + int mod = 1000000007; + for (char a : s) { + if (a == '1') { + cnt++; + } else { + cnt = 0; + } + total = (total + cnt) % mod; + } + return total; + } +}; diff --git a/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.cs b/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.cs new file mode 100644 index 00000000..55f17343 --- /dev/null +++ b/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.cs @@ -0,0 +1,16 @@ +public class Solution { + public int NumSub(string s) { + int cnt = 0; + int total = 0; + int mod = 1000000007; + foreach (char a in s) { + if (a == '1') { + cnt++; + } else { + cnt = 0; + } + total = (total + cnt) % mod; + } + return total; + } +} diff --git a/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.dart b/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.dart new file mode 100644 index 00000000..dfaa4fc5 --- /dev/null +++ b/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.dart @@ -0,0 +1,16 @@ +class Solution { + int numSub(String s) { + int cnt = 0; + int total = 0; + int mod = 1000000007; + for (int i = 0; i < s.length; i++) { + if (s[i] == '1') { + cnt++; + } else { + cnt = 0; + } + total = (total + cnt) % mod; + } + return total; + } +} diff --git a/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.go b/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.go new file mode 100644 index 00000000..42d802aa --- /dev/null +++ b/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.go @@ -0,0 +1,14 @@ +func numSub(s string) int { + cnt := 0 + total := 0 + mod := 1000000007 + for _, a := range s { + if a == '1' { + cnt++ + } else { + cnt = 0 + } + total = (total + cnt) % mod + } + return total +} diff --git a/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.java b/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.java new file mode 100644 index 00000000..2b77feb1 --- /dev/null +++ b/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.java @@ -0,0 +1,16 @@ +class Solution { + public int numSub(String s) { + int cnt = 0; + int total = 0; + int mod = 1000000007; + for (char a : s.toCharArray()) { + if (a == '1') { + cnt++; + } else { + cnt = 0; + } + total = (total + cnt) % mod; + } + return total; + } +} diff --git a/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.kt b/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.kt new file mode 100644 index 00000000..9ad7cb4b --- /dev/null +++ b/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun numSub(s: String): Int { + var cnt = 0 + var total = 0 + val mod = 1000000007 + for (a in s) { + if (a == '1') { + cnt++ + } else { + cnt = 0 + } + total = (total + cnt) % mod + } + return total + } +} diff --git a/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.py b/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.py new file mode 100644 index 00000000..f291c946 --- /dev/null +++ b/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.py @@ -0,0 +1,12 @@ +class Solution(object): + def numSub(self, s): + cnt = 0 + total = 0 + mod = 1000000007 + for a in s: + if a == "1": + cnt += 1 + else: + cnt = 0 + total = (total + cnt) % mod + return total diff --git a/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.py2 b/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.py2 new file mode 100644 index 00000000..d52ee623 --- /dev/null +++ b/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.py2 @@ -0,0 +1,12 @@ +class Solution(object): + def numSub(self, s): + cnt = 0 + total = 0 + mod = 1000000007 + for a in s: + if a == '1': + cnt += 1 + else: + cnt = 0 + total = (total + cnt) % mod + return total diff --git a/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.rb b/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.rb new file mode 100644 index 00000000..7f7e4afd --- /dev/null +++ b/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.rb @@ -0,0 +1,16 @@ +# @param {String} s +# @return {Integer} +def num_sub(s) + cnt = 0 + total = 0 + mod = 1000000007 + s.each_char do |a| + if a == '1' + cnt += 1 + else + cnt = 0 + end + total = (total + cnt) % mod + end + total +end diff --git a/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.rs b/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.rs new file mode 100644 index 00000000..f84947b1 --- /dev/null +++ b/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn num_sub(s: String) -> i32 { + let mut cnt: i32 = 0; + let mut total: i32 = 0; + let modulo: i32 = 1000000007; + for a in s.chars() { + if a == '1' { + cnt += 1; + } else { + cnt = 0; + } + total = (total + cnt) % modulo; + } + total + } +} diff --git a/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.swift b/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.swift new file mode 100644 index 00000000..67f94252 --- /dev/null +++ b/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.swift @@ -0,0 +1,16 @@ +class Solution { + func numSub(_ s: String) -> Int { + var cnt = 0 + var total = 0 + let mod = 1000000007 + for a in s { + if a == "1" { + cnt += 1 + } else { + cnt = 0 + } + total = (total + cnt) % mod + } + return total + } +} diff --git a/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.ts b/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.ts new file mode 100644 index 00000000..1346cb58 --- /dev/null +++ b/tests/1501-2000/1513. number-of-substrings-with-only-1s/sol.ts @@ -0,0 +1,14 @@ +function numSub(s: string): number { + let cnt = 0; + let total = 0; + const mod = 1000000007; + for (const a of s) { + if (a === "1") { + cnt++; + } else { + cnt = 0; + } + total = (total + cnt) % mod; + } + return total; +} diff --git a/tests/1501-2000/1514. path-with-maximum-probability/manifest.yaml b/tests/1501-2000/1514. path-with-maximum-probability/manifest.yaml new file mode 100644 index 00000000..d4941a4a --- /dev/null +++ b/tests/1501-2000/1514. path-with-maximum-probability/manifest.yaml @@ -0,0 +1,600 @@ +entry: + id: 1514 + title: "path-with-maximum-probability" + params: + n: + type: int + edges: + type: array + items: + type: array + items: + type: int + succProb: + type: array + items: + type: double + start_node: + type: int + end_node: + type: int + call: + cpp: "Solution().maxProbability({n}, {edges}, {succProb}, {start_node}, {end_node})" + rust: "Solution::max_probability({n}, {edges}, {succProb}, {start_node}, {end_node})" + python3: "Solution().maxProbability({n}, {edges}, {succProb}, {start_node}, {end_node})" + python2: "Solution().maxProbability({n}, {edges}, {succProb}, {start_node}, {end_node})" + ruby: "max_probability({n}, {edges}, {succProb}, {start_node}, {end_node})" + java: "new Solution().maxProbability({n}, {edges}, {succProb}, {start_node}, {end_node})" + csharp: "new Solution().MaxProbability({n}, {edges}, {succProb}, {start_node}, {end_node})" + kotlin: "Solution().maxProbability({n}, {edges}, {succProb}, {start_node}, {end_node})" + go: "maxProbability({n}, {edges}, {succProb}, {start_node}, {end_node})" + dart: "Solution().maxProbability({n}, {edges}, {succProb}, {start_node}, {end_node})" + swift: "Solution().maxProbability({n}, {edges}, {succProb}, {start_node}, {end_node})" + typescript: "maxProbability({n}, {edges}, {succProb}, {start_node}, {end_node})" + +judge: + type: "exact" + +limits: + time_ms: 500 + memory_mb: 300 + +oracle: + python3: + call: "Checker().maxProbability(n, edges, succProb, start_node, end_node, {result})" + checker: | + import heapq + + class Checker: + def maxProbability(self, n, edges, probs, start, end, result): + if not isinstance(result, (int, float)): + return False + graph = [[] for _ in range(n)] + for (u, v), p in zip(edges, probs): + graph[u].append((v, p)) + graph[v].append((u, p)) + best = [0.0] * n + best[start] = 1.0 + queue = [(-1.0, start)] + while queue: + neg_prob, node = heapq.heappop(queue) + probability = -neg_prob + if probability < best[node]: + continue + if node == end: + break + for neighbor, edge_prob in graph[node]: + candidate = probability * edge_prob + if candidate > best[neighbor]: + best[neighbor] = candidate + heapq.heappush(queue, (-candidate, neighbor)) + return abs(float(result) - best[end]) <= 1e-5 + +seed: 1514 + +tests: + - name: "example indirect beats direct" + in: + n: 3 + edges: + - [0, 1] + - [1, 2] + - [0, 2] + succProb: [0.5, 0.5, 0.2] + start_node: 0 + end_node: 2 + - name: "example direct wins" + in: + n: 3 + edges: + - [0, 1] + - [1, 2] + - [0, 2] + succProb: [0.5, 0.5, 0.3] + start_node: 0 + end_node: 2 + - name: "example disconnected" + in: + n: 3 + edges: + - [0, 1] + succProb: [0.5] + start_node: 0 + end_node: 2 + - name: "single edge" + in: + n: 2 + edges: + - [0, 1] + succProb: [0.73] + start_node: 0 + end_node: 1 + - name: "reverse single edge" + in: + n: 2 + edges: + - [0, 1] + succProb: [0.91] + start_node: 1 + end_node: 0 + - name: "certain edge" + in: + n: 4 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + succProb: [1.0, 1.0, 1.0] + start_node: 0 + end_node: 3 + - name: "zero edge blocks route" + in: + n: 3 + edges: + - [0, 1] + - [1, 2] + succProb: [0.0, 0.8] + start_node: 0 + end_node: 2 + - name: "zero direct avoided" + in: + n: 4 + edges: + - [0, 3] + - [0, 1] + - [1, 2] + - [2, 3] + succProb: [0.0, 0.9, 0.9, 0.9] + start_node: 0 + end_node: 3 + - name: "three hop product" + in: + n: 4 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + succProb: [0.8, 0.7, 0.6] + start_node: 0 + end_node: 3 + - name: "longer path beats shortcut" + in: + n: 5 + edges: + - [0, 4] + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + succProb: [0.1, 0.95, 0.95, 0.95, 0.95] + start_node: 0 + end_node: 4 + - name: "cycle with improving route" + in: + n: 5 + edges: + - [0, 1] + - [1, 2] + - [2, 0] + - [2, 3] + - [3, 4] + succProb: [0.6, 0.9, 0.8, 0.7, 0.9] + start_node: 0 + end_node: 4 + - name: "isolated target" + in: + n: 6 + edges: + - [0, 1] + - [1, 2] + - [3, 4] + succProb: [0.9, 0.8, 1.0] + start_node: 0 + end_node: 5 + - name: "multiple branches" + in: + n: 6 + edges: + - [0, 1] + - [1, 5] + - [0, 2] + - [2, 3] + - [3, 5] + - [0, 4] + - [4, 5] + succProb: [0.8, 0.8, 0.95, 0.95, 0.95, 0.5, 0.99] + start_node: 0 + end_node: 5 + - name: "tiny probabilities" + in: + n: 4 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + succProb: [0.0001, 0.0002, 0.0003] + start_node: 0 + end_node: 3 + - name: "dense four nodes" + in: + n: 4 + edges: + - [0, 1] + - [0, 2] + - [0, 3] + - [1, 2] + - [1, 3] + - [2, 3] + succProb: [0.4, 0.8, 0.2, 0.9, 0.6, 0.7] + start_node: 0 + end_node: 3 + - name: "reverse dense traversal" + in: + n: 4 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [0, 3] + succProb: [0.7, 0.8, 0.9, 0.1] + start_node: 3 + end_node: 0 + - name: "equal competing paths" + in: + n: 5 + edges: + - [0, 1] + - [1, 4] + - [0, 2] + - [2, 4] + - [0, 3] + - [3, 4] + succProb: [0.8, 0.8, 0.8, 0.8, 0.5, 0.9] + start_node: 0 + end_node: 4 + - name: "zero probability isolated component" + in: + n: 5 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + succProb: [0.0, 0.0, 0.0, 0.0] + start_node: 0 + end_node: 4 + - name: "six hop chain" + in: + n: 7 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + succProb: [0.99, 0.98, 0.97, 0.96, 0.95, 0.94] + start_node: 0 + end_node: 6 + - name: "shortcut among chain" + in: + n: 7 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [0, 6] + succProb: [0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.5] + start_node: 0 + end_node: 6 + - name: "start at high index" + in: + n: 8 + edges: + - [7, 0] + - [0, 3] + - [3, 6] + - [7, 5] + - [5, 6] + succProb: [0.6, 0.8, 0.9, 0.9, 0.9] + start_node: 7 + end_node: 6 + - name: "unreachable with many edges" + in: + n: 8 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [4, 5] + - [5, 6] + - [6, 7] + succProb: [0.8, 0.8, 0.8, 0.9, 0.9, 0.9] + start_node: 0 + end_node: 7 + - name: "direct probability one" + in: + n: 5 + edges: + - [0, 4] + - [0, 1] + - [1, 4] + succProb: [1.0, 0.9, 0.9] + start_node: 0 + end_node: 4 + - name: "fractional branch" + in: + n: 6 + edges: + - [0, 1] + - [1, 5] + - [0, 2] + - [2, 3] + - [3, 4] + - [4, 5] + succProb: [0.73, 0.64, 0.99, 0.99, 0.99, 0.99] + start_node: 0 + end_node: 5 + - name: "late edge order" + in: + n: 6 + edges: + - [4, 5] + - [3, 4] + - [2, 3] + - [1, 2] + - [0, 1] + succProb: [0.9, 0.9, 0.9, 0.9, 0.9] + start_node: 0 + end_node: 5 + - name: "mixed zero and direct" + in: + n: 6 + edges: + - [0, 1] + - [1, 5] + - [0, 2] + - [2, 3] + - [3, 5] + - [0, 5] + succProb: [0.0, 0.9, 0.8, 0.8, 0.8, 0.01] + start_node: 0 + end_node: 5 + - name: "nine node ladder" + in: + n: 9 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [0, 4] + - [4, 8] + succProb: [0.95, 0.95, 0.95, 0.95, 0.95, 0.95, 0.95, 0.95, 0.8, 0.8] + start_node: 0 + end_node: 8 + - name: "near underflow chain" + in: + n: 8 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + succProb: [0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01] + start_node: 0 + end_node: 7 + - name: "ten node alternative" + in: + n: 10 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 9] + - [0, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + succProb: [0.8, 0.8, 0.8, 0.8, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99] + start_node: 0 + end_node: 9 + - name: "parallel zero branch" + in: + n: 5 + edges: + - [0, 1] + - [1, 4] + - [0, 2] + - [2, 4] + - [0, 3] + - [3, 4] + succProb: [0.0, 0.0, 0.5, 0.5, 0.7, 0.7] + start_node: 0 + end_node: 4 + - name: "reverse chain" + in: + n: 6 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + succProb: [0.91, 0.82, 0.73, 0.64, 0.55] + start_node: 5 + end_node: 0 + - name: "dense six node" + in: + n: 6 + edges: + - [0, 1] + - [0, 2] + - [0, 3] + - [1, 4] + - [2, 4] + - [3, 5] + - [4, 5] + - [1, 5] + - [2, 3] + succProb: [0.4, 0.7, 0.6, 0.9, 0.8, 0.9, 0.9, 0.5, 0.95] + start_node: 0 + end_node: 5 + - name: "all weak edges" + in: + n: 5 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [0, 4] + succProb: [0.2, 0.2, 0.2, 0.2, 0.19] + start_node: 0 + end_node: 4 + - name: "large sparse 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] + succProb: + [ + 0.99, + 0.98, + 0.97, + 0.96, + 0.95, + 0.94, + 0.93, + 0.92, + 0.91, + 0.9, + 0.89, + 0.88, + 0.87, + 0.86, + 0.85, + 0.84, + 0.83, + 0.82, + 0.81, + ] + start_node: 0 + end_node: 19 + - name: "large graph disconnected tail" + in: + n: 12 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [0, 5] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + - [10, 11] + succProb: [0.91, 0.91, 0.91, 0.91, 0.91, 0.8, 1.0, 1.0, 1.0, 1.0, 1.0] + start_node: 0 + end_node: 5 + - name: "no edges" + in: + n: 5 + edges: [] + succProb: [] + start_node: 1 + end_node: 4 + - name: "reverse branch selection" + in: + n: 7 + edges: + - [0, 1] + - [1, 6] + - [0, 2] + - [2, 3] + - [3, 6] + - [0, 4] + - [4, 5] + - [5, 6] + succProb: [0.61, 0.61, 0.95, 0.95, 0.95, 0.95, 0.95, 0.95] + start_node: 6 + end_node: 0 + - name: "many zero edges before valid route" + in: + n: 8 + edges: + - [0, 1] + - [1, 2] + - [2, 7] + - [0, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + succProb: [0.0, 0.0, 0.0, 0.88, 0.88, 0.88, 0.88, 0.88] + start_node: 0 + end_node: 7 + - name: "high precision competing routes" + in: + n: 6 + edges: + - [0, 1] + - [1, 5] + - [0, 2] + - [2, 3] + - [3, 5] + - [0, 4] + - [4, 5] + succProb: [0.99999, 0.99998, 0.999999, 0.999999, 0.999999, 0.9999, 0.9999] + start_node: 0 + end_node: 5 + - name: "dense seven node late optimum" + in: + n: 7 + edges: + - [0, 1] + - [0, 2] + - [0, 3] + - [1, 4] + - [2, 4] + - [3, 5] + - [4, 6] + - [5, 6] + - [1, 5] + - [2, 3] + - [0, 6] + succProb: [0.7, 0.8, 0.6, 0.8, 0.95, 0.95, 0.95, 0.9, 0.9, 0.9, 0.1] + start_node: 0 + end_node: 6 diff --git a/tests/1501-2000/1514. path-with-maximum-probability/sol.cpp b/tests/1501-2000/1514. path-with-maximum-probability/sol.cpp new file mode 100644 index 00000000..caa51c2f --- /dev/null +++ b/tests/1501-2000/1514. path-with-maximum-probability/sol.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + double maxProbability(int n, vector>& edges, vector& succProb, int start_node, int end_node) { + vector dist(n, 0.0); + dist[start_node] = 1.0; + + for (int k = 0; k < n - 1; ++k) { + bool updated = false; + for (int i = 0; i < edges.size(); ++i) { + int u = edges[i][0]; + int v = edges[i][1]; + if (dist[u] * succProb[i] > dist[v]) { + dist[v] = dist[u] * succProb[i]; + updated = true; + } + if (dist[v] * succProb[i] > dist[u]) { + dist[u] = dist[v] * succProb[i]; + updated = true; + } + } + if (!updated) break; + } + + return dist[end_node]; + } +}; diff --git a/tests/1501-2000/1514. path-with-maximum-probability/sol.cs b/tests/1501-2000/1514. path-with-maximum-probability/sol.cs new file mode 100644 index 00000000..e6f84886 --- /dev/null +++ b/tests/1501-2000/1514. path-with-maximum-probability/sol.cs @@ -0,0 +1,25 @@ +public class Solution { + public double MaxProbability(int n, int[][] edges, double[] succProb, int start_node, int end_node) { + double[] dist = new double[n]; + dist[start_node] = 1.0; + + for (int k = 0; k < n - 1; k++) { + bool updated = false; + for (int i = 0; i < edges.Length; i++) { + int u = edges[i][0]; + int v = edges[i][1]; + if (dist[u] * succProb[i] > dist[v]) { + dist[v] = dist[u] * succProb[i]; + updated = true; + } + if (dist[v] * succProb[i] > dist[u]) { + dist[u] = dist[v] * succProb[i]; + updated = true; + } + } + if (!updated) break; + } + + return dist[end_node]; + } +} diff --git a/tests/1501-2000/1514. path-with-maximum-probability/sol.dart b/tests/1501-2000/1514. path-with-maximum-probability/sol.dart new file mode 100644 index 00000000..741cb5f9 --- /dev/null +++ b/tests/1501-2000/1514. path-with-maximum-probability/sol.dart @@ -0,0 +1,25 @@ +class Solution { + double maxProbability(int n, List> edges, List succProb, int start_node, int end_node) { + List dist = List.filled(n, 0.0); + dist[start_node] = 1.0; + + for (int k = 0; k < n - 1; k++) { + bool updated = false; + for (int i = 0; i < edges.length; i++) { + int u = edges[i][0]; + int v = edges[i][1]; + if (dist[u] * succProb[i] > dist[v]) { + dist[v] = dist[u] * succProb[i]; + updated = true; + } + if (dist[v] * succProb[i] > dist[u]) { + dist[u] = dist[v] * succProb[i]; + updated = true; + } + } + if (!updated) break; + } + + return dist[end_node]; + } +} diff --git a/tests/1501-2000/1514. path-with-maximum-probability/sol.go b/tests/1501-2000/1514. path-with-maximum-probability/sol.go new file mode 100644 index 00000000..10b8a745 --- /dev/null +++ b/tests/1501-2000/1514. path-with-maximum-probability/sol.go @@ -0,0 +1,24 @@ +func maxProbability(n int, edges [][]int, succProb []float64, start_node int, end_node int) float64 { + dist := make([]float64, n) + dist[start_node] = 1.0 + + for k := 0; k < n-1; k++ { + updated := false + for i, edge := range edges { + u, v := edge[0], edge[1] + if dist[u]*succProb[i] > dist[v] { + dist[v] = dist[u] * succProb[i] + updated = true + } + if dist[v]*succProb[i] > dist[u] { + dist[u] = dist[v] * succProb[i] + updated = true + } + } + if !updated { + break + } + } + + return dist[end_node] +} diff --git a/tests/1501-2000/1514. path-with-maximum-probability/sol.java b/tests/1501-2000/1514. path-with-maximum-probability/sol.java new file mode 100644 index 00000000..b419e803 --- /dev/null +++ b/tests/1501-2000/1514. path-with-maximum-probability/sol.java @@ -0,0 +1,25 @@ +class Solution { + public double maxProbability(int n, int[][] edges, double[] succProb, int start_node, int end_node) { + double[] dist = new double[n]; + dist[start_node] = 1.0; + + for (int k = 0; k < n - 1; k++) { + boolean updated = false; + for (int i = 0; i < edges.length; i++) { + int u = edges[i][0]; + int v = edges[i][1]; + if (dist[u] * succProb[i] > dist[v]) { + dist[v] = dist[u] * succProb[i]; + updated = true; + } + if (dist[v] * succProb[i] > dist[u]) { + dist[u] = dist[v] * succProb[i]; + updated = true; + } + } + if (!updated) break; + } + + return dist[end_node]; + } +} diff --git a/tests/1501-2000/1514. path-with-maximum-probability/sol.kt b/tests/1501-2000/1514. path-with-maximum-probability/sol.kt new file mode 100644 index 00000000..2d5f7919 --- /dev/null +++ b/tests/1501-2000/1514. path-with-maximum-probability/sol.kt @@ -0,0 +1,25 @@ +class Solution { + fun maxProbability(n: Int, edges: Array, succProb: DoubleArray, start_node: Int, end_node: Int): Double { + val dist = DoubleArray(n) { 0.0 } + dist[start_node] = 1.0 + + for (k in 0 until n - 1) { + var updated = false + for (i in edges.indices) { + val u = edges[i][0] + val v = edges[i][1] + if (dist[u] * succProb[i] > dist[v]) { + dist[v] = dist[u] * succProb[i] + updated = true + } + if (dist[v] * succProb[i] > dist[u]) { + dist[u] = dist[v] * succProb[i] + updated = true + } + } + if (!updated) break + } + + return dist[end_node] + } +} diff --git a/tests/1501-2000/1514. path-with-maximum-probability/sol.py b/tests/1501-2000/1514. path-with-maximum-probability/sol.py new file mode 100644 index 00000000..7f2eb3eb --- /dev/null +++ b/tests/1501-2000/1514. path-with-maximum-probability/sol.py @@ -0,0 +1,25 @@ +class Solution: + def maxProbability( + self, + n: int, + edges: List[List[int]], + succProb: List[float], + start: int, + end: int, + ) -> float: + dist = [0] * n + dist[start] = 1 + + for _ in range(n - 1): + updated = False + for i, (u, v) in enumerate(edges): + if dist[u] * succProb[i] > dist[v]: + dist[v] = dist[u] * succProb[i] + updated = True + if dist[v] * succProb[i] > dist[u]: + dist[u] = dist[v] * succProb[i] + updated = True + if not updated: + break + + return dist[end] diff --git a/tests/1501-2000/1514. path-with-maximum-probability/sol.py2 b/tests/1501-2000/1514. path-with-maximum-probability/sol.py2 new file mode 100644 index 00000000..eaf2724b --- /dev/null +++ b/tests/1501-2000/1514. path-with-maximum-probability/sol.py2 @@ -0,0 +1,26 @@ +class Solution(object): + def maxProbability(self, n, edges, succProb, start_node, end_node): + """ + :type n: int + :type edges: List[List[int]] + :type succProb: List[float] + :type start_node: int + :type end_node: int + :rtype: float + """ + dist = [0.0] * n + dist[start_node] = 1.0 + + for _ in range(n - 1): + updated = False + for i, (u, v) in enumerate(edges): + if dist[u] * succProb[i] > dist[v]: + dist[v] = dist[u] * succProb[i] + updated = True + if dist[v] * succProb[i] > dist[u]: + dist[u] = dist[v] * succProb[i] + updated = True + if not updated: + break + + return dist[end_node] diff --git a/tests/1501-2000/1514. path-with-maximum-probability/sol.rb b/tests/1501-2000/1514. path-with-maximum-probability/sol.rb new file mode 100644 index 00000000..b69e749b --- /dev/null +++ b/tests/1501-2000/1514. path-with-maximum-probability/sol.rb @@ -0,0 +1,27 @@ +# @param {Integer} n +# @param {Integer[][]} edges +# @param {Float[]} succ_prob +# @param {Integer} start_node +# @param {Integer} end_node +# @return {Float} +def max_probability(n, edges, succ_prob, start_node, end_node) + dist = Array.new(n, 0.0) + dist[start_node] = 1.0 + + (n - 1).times do + updated = false + edges.each_with_index do |(u, v), i| + if dist[u] * succ_prob[i] > dist[v] + dist[v] = dist[u] * succ_prob[i] + updated = true + end + if dist[v] * succ_prob[i] > dist[u] + dist[u] = dist[v] * succ_prob[i] + updated = true + end + end + break unless updated + end + + dist[end_node] +end diff --git a/tests/1501-2000/1514. path-with-maximum-probability/sol.rs b/tests/1501-2000/1514. path-with-maximum-probability/sol.rs new file mode 100644 index 00000000..a7dd4640 --- /dev/null +++ b/tests/1501-2000/1514. path-with-maximum-probability/sol.rs @@ -0,0 +1,28 @@ +impl Solution { + pub fn max_probability(n: i32, edges: Vec>, succ_prob: Vec, start_node: i32, end_node: i32) -> f64 { + let n = n as usize; + let mut dist = vec![0.0; n]; + dist[start_node as usize] = 1.0; + + for _ in 0..(n - 1) { + let mut updated = false; + for i in 0..edges.len() { + let u = edges[i][0] as usize; + let v = edges[i][1] as usize; + if dist[u] * succ_prob[i] > dist[v] { + dist[v] = dist[u] * succ_prob[i]; + updated = true; + } + if dist[v] * succ_prob[i] > dist[u] { + dist[u] = dist[v] * succ_prob[i]; + updated = true; + } + } + if !updated { + break; + } + } + + dist[end_node as usize] + } +} diff --git a/tests/1501-2000/1514. path-with-maximum-probability/sol.swift b/tests/1501-2000/1514. path-with-maximum-probability/sol.swift new file mode 100644 index 00000000..f250b1f6 --- /dev/null +++ b/tests/1501-2000/1514. path-with-maximum-probability/sol.swift @@ -0,0 +1,25 @@ +class Solution { + func maxProbability(_ n: Int, _ edges: [[Int]], _ succProb: [Double], _ start_node: Int, _ end_node: Int) -> Double { + var dist = Array(repeating: 0.0, count: n) + dist[start_node] = 1.0 + + for _ in 0..<(n - 1) { + var updated = false + for i in 0.. dist[v] { + dist[v] = dist[u] * succProb[i] + updated = true + } + if dist[v] * succProb[i] > dist[u] { + dist[u] = dist[v] * succProb[i] + updated = true + } + } + if !updated { break } + } + + return dist[end_node] + } +} diff --git a/tests/1501-2000/1514. path-with-maximum-probability/sol.ts b/tests/1501-2000/1514. path-with-maximum-probability/sol.ts new file mode 100644 index 00000000..7b695dbe --- /dev/null +++ b/tests/1501-2000/1514. path-with-maximum-probability/sol.ts @@ -0,0 +1,29 @@ +function maxProbability( + n: number, + edges: number[][], + succProb: number[], + start_node: number, + end_node: number, +): number { + const dist: number[] = new Array(n).fill(0); + dist[start_node] = 1; + + for (let k = 0; k < n - 1; k++) { + let updated = false; + for (let i = 0; i < edges.length; i++) { + const u = edges[i][0]; + const v = edges[i][1]; + if (dist[u] * succProb[i] > dist[v]) { + dist[v] = dist[u] * succProb[i]; + updated = true; + } + if (dist[v] * succProb[i] > dist[u]) { + dist[u] = dist[v] * succProb[i]; + updated = true; + } + } + if (!updated) break; + } + + return dist[end_node]; +} diff --git a/tests/1501-2000/1515. best-position-for-a-service-centre/manifest.yaml b/tests/1501-2000/1515. best-position-for-a-service-centre/manifest.yaml new file mode 100644 index 00000000..cfc0e462 --- /dev/null +++ b/tests/1501-2000/1515. best-position-for-a-service-centre/manifest.yaml @@ -0,0 +1,652 @@ +entry: + id: 1515 + title: "best-position-for-a-service-centre" + params: + positions: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().getMinDistSum({positions})" + rust: "Solution::get_min_dist_sum({positions})" + python3: "Solution().getMinDistSum({positions})" + python2: "Solution().getMinDistSum({positions})" + ruby: "get_min_dist_sum({positions})" + java: "new Solution().getMinDistSum({positions})" + csharp: "new Solution().GetMinDistSum({positions})" + kotlin: "Solution().getMinDistSum({positions})" + go: "getMinDistSum({positions})" + dart: "Solution().getMinDistSum({positions})" + swift: "Solution().getMinDistSum({positions})" + typescript: "getMinDistSum({positions})" +judge: + type: "exact" +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().getMinDistSum(positions, {result})" + checker: | + import math + class Checker: + def getMinDistSum(self, positions, result): + x = sum(p[0] for p in positions) / len(positions) + y = sum(p[1] for p in positions) / len(positions) + for _ in range(10000): + weights = [] + coincident = False + for px, py in positions: + distance = math.hypot(x - px, y - py) + if distance < 1e-12: + coincident = True + break + weights.append((px, py, 1.0 / distance)) + if coincident: + break + total_weight = sum(w for _, _, w in weights) + nx = sum(px * w for px, _, w in weights) / total_weight + ny = sum(py * w for _, py, w in weights) / total_weight + if math.hypot(nx - x, ny - y) < 1e-10: + x, y = nx, ny + break + x, y = nx, ny + best = sum(math.hypot(x - px, y - py) for px, py in positions) + return math.isfinite(result) and abs(result - best) <= 2e-5 +seed: 1515 +tests: + - name: "single customer" + in: + positions: + - [0, 0] + - name: "single corner" + in: + positions: + - [100, 100] + - name: "example diamond" + in: + positions: + - [0, 1] + - [1, 0] + - [1, 2] + - [2, 1] + - name: "example pair" + in: + positions: + - [1, 1] + - [3, 3] + - name: "two horizontal" + in: + positions: + - [0, 0] + - [10, 0] + - name: "two vertical" + in: + positions: + - [0, 0] + - [0, 10] + - name: "two diagonal bounds" + in: + positions: + - [0, 100] + - [100, 0] + - name: "all identical" + in: + positions: + - [7, 9] + - [7, 9] + - [7, 9] + - [7, 9] + - name: "square" + in: + positions: + - [0, 0] + - [0, 10] + - [10, 0] + - [10, 10] + - name: "rectangle" + in: + positions: + - [0, 0] + - [0, 4] + - [20, 0] + - [20, 4] + - name: "triangle" + in: + positions: + - [0, 0] + - [6, 0] + - [3, 4] + - name: "collinear three" + in: + positions: + - [0, 0] + - [5, 0] + - [10, 0] + - name: "collinear uneven" + in: + positions: + - [0, 0] + - [1, 0] + - [20, 0] + - name: "center duplicate weight" + in: + positions: + - [0, 0] + - [10, 0] + - [5, 0] + - [5, 0] + - name: "axis cross" + in: + positions: + - [0, 5] + - [5, 0] + - [10, 5] + - [5, 10] + - name: "lower boundary cluster" + in: + positions: + - [0, 0] + - [1, 0] + - [0, 1] + - [1, 1] + - [2, 2] + - name: "upper boundary cluster" + in: + positions: + - [100, 100] + - [99, 100] + - [100, 99] + - [99, 99] + - [98, 98] + - name: "far outlier" + in: + positions: + - [50, 50] + - [50, 50] + - [50, 50] + - [100, 100] + - name: "corner quartet" + in: + positions: + - [0, 0] + - [0, 100] + - [100, 0] + - [100, 100] + - name: "asymmetric corners" + in: + positions: + - [0, 0] + - [0, 100] + - [100, 0] + - [20, 20] + - [20, 20] + - name: "six symmetric" + in: + positions: + - [10, 50] + - [20, 40] + - [30, 30] + - [40, 20] + - [50, 10] + - [30, 30] + - name: "repeated endpoints" + in: + positions: + - [0, 0] + - [0, 0] + - [100, 100] + - [100, 100] + - name: "near diagonal" + in: + positions: + - [11, 12] + - [21, 22] + - [31, 32] + - [41, 42] + - [51, 52] + - name: "compact irregular" + in: + positions: + - [49, 49] + - [50, 49] + - [49, 50] + - [51, 50] + - [50, 51] + - [52, 52] + - name: "eight spread" + in: + positions: + - [0, 50] + - [14, 71] + - [29, 3] + - [43, 88] + - [57, 17] + - [72, 64] + - [86, 26] + - [100, 100] + - name: "grid corners and center" + in: + positions: + - [0, 0] + - [0, 50] + - [0, 100] + - [50, 0] + - [50, 50] + - [50, 100] + - [100, 0] + - [100, 50] + - [100, 100] + - name: "nine varied" + in: + positions: + - [4, 77] + - [18, 2] + - [27, 44] + - [39, 91] + - [51, 13] + - [63, 68] + - [74, 35] + - [88, 6] + - [96, 82] + - name: "ten diagonal bands" + in: + positions: + - [0, 0] + - [10, 10] + - [20, 20] + - [30, 30] + - [40, 40] + - [60, 60] + - [70, 70] + - [80, 80] + - [90, 90] + - [100, 100] + - name: "ten two clusters" + in: + positions: + - [5, 5] + - [6, 4] + - [4, 6] + - [7, 5] + - [5, 7] + - [93, 95] + - [94, 94] + - [95, 93] + - [92, 95] + - [95, 92] + - name: "maximum boundary sample" + in: + positions: + - [0, 100] + - [10, 90] + - [20, 80] + - [30, 70] + - [40, 60] + - [60, 40] + - [70, 30] + - [80, 20] + - [90, 10] + - [100, 0] + - name: "fifty alternating boundary points" + in: + positions: + - [0, 0] + - [100, 100] + - [0, 2] + - [100, 98] + - [0, 4] + - [100, 96] + - [0, 6] + - [100, 94] + - [0, 8] + - [100, 92] + - [0, 10] + - [100, 90] + - [0, 12] + - [100, 88] + - [0, 14] + - [100, 86] + - [0, 16] + - [100, 84] + - [0, 18] + - [100, 82] + - [0, 20] + - [100, 80] + - [0, 22] + - [100, 78] + - [0, 24] + - [100, 76] + - [0, 26] + - [100, 74] + - [0, 28] + - [100, 72] + - [0, 30] + - [100, 70] + - [0, 32] + - [100, 68] + - [0, 34] + - [100, 66] + - [0, 36] + - [100, 64] + - [0, 38] + - [100, 62] + - [0, 40] + - [100, 60] + - [0, 42] + - [100, 58] + - [0, 44] + - [100, 56] + - [0, 46] + - [100, 54] + - [0, 48] + - [100, 52] + - name: "fifty diagonal line" + in: + positions: + - [0, 0] + - [2, 2] + - [4, 4] + - [6, 6] + - [8, 8] + - [10, 10] + - [12, 12] + - [14, 14] + - [16, 16] + - [18, 18] + - [20, 20] + - [22, 22] + - [24, 24] + - [26, 26] + - [28, 28] + - [30, 30] + - [32, 32] + - [34, 34] + - [36, 36] + - [38, 38] + - [40, 40] + - [42, 42] + - [44, 44] + - [46, 46] + - [48, 48] + - [50, 50] + - [52, 52] + - [54, 54] + - [56, 56] + - [58, 58] + - [60, 60] + - [62, 62] + - [64, 64] + - [66, 66] + - [68, 68] + - [70, 70] + - [72, 72] + - [74, 74] + - [76, 76] + - [78, 78] + - [80, 80] + - [82, 82] + - [84, 84] + - [86, 86] + - [88, 88] + - [90, 90] + - [92, 92] + - [94, 94] + - [96, 96] + - [98, 98] + - name: "fifty central grid" + in: + positions: + - [45, 45] + - [50, 45] + - [55, 45] + - [45, 50] + - [55, 50] + - [45, 55] + - [50, 55] + - [55, 55] + - [46, 46] + - [50, 46] + - [54, 46] + - [46, 50] + - [54, 50] + - [46, 54] + - [50, 54] + - [54, 54] + - [47, 47] + - [50, 47] + - [53, 47] + - [47, 50] + - [53, 50] + - [47, 53] + - [50, 53] + - [53, 53] + - [48, 48] + - [50, 48] + - [52, 48] + - [48, 50] + - [52, 50] + - [48, 52] + - [50, 52] + - [52, 52] + - [49, 49] + - [50, 49] + - [51, 49] + - [49, 50] + - [51, 50] + - [49, 51] + - [50, 51] + - [51, 51] + - [0, 50] + - [100, 50] + - [50, 0] + - [50, 100] + - [25, 50] + - [75, 50] + - [50, 25] + - [50, 75] + - [10, 10] + - [90, 90] + - name: "fifty asymmetric spread" + in: + positions: + - [0, 100] + - [3, 7] + - [6, 94] + - [9, 21] + - [12, 83] + - [15, 35] + - [18, 72] + - [21, 4] + - [24, 61] + - [27, 98] + - [30, 18] + - [33, 47] + - [36, 89] + - [39, 29] + - [42, 66] + - [45, 12] + - [48, 54] + - [51, 77] + - [54, 3] + - [57, 42] + - [60, 95] + - [63, 24] + - [66, 68] + - [69, 8] + - [72, 51] + - [75, 87] + - [78, 31] + - [81, 63] + - [84, 16] + - [87, 92] + - [90, 38] + - [93, 74] + - [96, 5] + - [99, 57] + - [2, 33] + - [5, 80] + - [8, 14] + - [11, 69] + - [14, 26] + - [17, 91] + - [20, 44] + - [23, 6] + - [26, 58] + - [29, 76] + - [32, 11] + - [35, 52] + - [38, 86] + - [41, 37] + - [44, 64] + - [47, 19] + - name: "fifty duplicate-heavy extremes" + in: + positions: + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [100, 100] + - [100, 100] + - [100, 100] + - [100, 100] + - [100, 100] + - [0, 100] + - [0, 100] + - [0, 100] + - [0, 100] + - [0, 100] + - [100, 0] + - [100, 0] + - [100, 0] + - [100, 0] + - [100, 0] + - [25, 25] + - [25, 25] + - [25, 25] + - [25, 25] + - [25, 25] + - [75, 75] + - [75, 75] + - [75, 75] + - [75, 75] + - [75, 75] + - [25, 75] + - [25, 75] + - [25, 75] + - [25, 75] + - [25, 75] + - [75, 25] + - [75, 25] + - [75, 25] + - [75, 25] + - [75, 25] + - [50, 50] + - [50, 50] + - [50, 50] + - [50, 50] + - [1, 1] + - [1, 1] + - [99, 99] + - [99, 99] + - [1, 99] + - [99, 1] + - name: "generated large full range" + seed: 151501 + in: + positions: + gen: array + len: + gen: int + min: 45 + max: 50 + of: + gen: array + len: 2 + of: + gen: int + min: 0 + max: 100 + elemType: int + distinct: false + sorted: false + - name: "generated large lower cluster" + seed: 151502 + in: + positions: + gen: array + len: + gen: int + min: 45 + max: 50 + of: + gen: array + len: 2 + of: + gen: int + min: 0 + max: 10 + elemType: int + distinct: false + sorted: false + - name: "generated large upper cluster" + seed: 151503 + in: + positions: + gen: array + len: + gen: int + min: 45 + max: 50 + of: + gen: array + len: 2 + of: + gen: int + min: 90 + max: 100 + elemType: int + distinct: false + sorted: false + - name: "generated large central cluster" + seed: 151504 + in: + positions: + gen: array + len: + gen: int + min: 45 + max: 50 + of: + gen: array + len: 2 + of: + gen: int + min: 40 + max: 60 + elemType: int + distinct: false + sorted: false + - name: "generated large broad range" + seed: 151505 + in: + positions: + gen: array + len: + gen: int + min: 48 + max: 50 + of: + gen: array + len: 2 + of: + gen: int + min: 20 + max: 80 + elemType: int + distinct: false + sorted: false diff --git a/tests/1501-2000/1515. best-position-for-a-service-centre/sol.cpp b/tests/1501-2000/1515. best-position-for-a-service-centre/sol.cpp new file mode 100644 index 00000000..400ccc1b --- /dev/null +++ b/tests/1501-2000/1515. best-position-for-a-service-centre/sol.cpp @@ -0,0 +1,44 @@ +class Solution { +public: + double getMinDistSum(vector>& positions) { + auto distSum = [&](double x, double y) { + double sum = 0.0; + for (auto& p : positions) { + double dx = x - p[0]; + double dy = y - p[1]; + sum += sqrt(dx * dx + dy * dy); + } + return sum; + }; + + double x = 0.0, y = 0.0; + for (auto& p : positions) { + x += p[0]; + y += p[1]; + } + x /= positions.size(); + y /= positions.size(); + + double ans = distSum(x, y); + double chg = 100.0; + vector> dirs = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}}; + + while (chg > 1e-6) { + bool zoom = true; + for (auto& d : dirs) { + double xx = x + chg * d.first; + double yy = y + chg * d.second; + double dd = distSum(xx, yy); + if (dd < ans) { + ans = dd; + x = xx; + y = yy; + zoom = false; + break; + } + } + if (zoom) chg /= 2; + } + return ans; + } +}; diff --git a/tests/1501-2000/1515. best-position-for-a-service-centre/sol.cs b/tests/1501-2000/1515. best-position-for-a-service-centre/sol.cs new file mode 100644 index 00000000..035c005c --- /dev/null +++ b/tests/1501-2000/1515. best-position-for-a-service-centre/sol.cs @@ -0,0 +1,45 @@ +public class Solution { + public double GetMinDistSum(int[][] positions) { + double DistSum(double x, double y) { + double sum = 0.0; + foreach (var p in positions) { + double dx = x - p[0]; + double dy = y - p[1]; + sum += Math.Sqrt(dx * dx + dy * dy); + } + return sum; + } + + double x = 0.0, y = 0.0; + foreach (var p in positions) { + x += p[0]; + y += p[1]; + } + x /= positions.Length; + y /= positions.Length; + + double ans = DistSum(x, y); + double chg = 100.0; + int[][] dirs = new int[][] { + new int[] {-1, 0}, new int[] {0, -1}, new int[] {0, 1}, new int[] {1, 0} + }; + + while (chg > 1e-6) { + bool zoom = true; + foreach (var d in dirs) { + double xx = x + chg * d[0]; + double yy = y + chg * d[1]; + double dd = DistSum(xx, yy); + if (dd < ans) { + ans = dd; + x = xx; + y = yy; + zoom = false; + break; + } + } + if (zoom) chg /= 2; + } + return ans; + } +} diff --git a/tests/1501-2000/1515. best-position-for-a-service-centre/sol.dart b/tests/1501-2000/1515. best-position-for-a-service-centre/sol.dart new file mode 100644 index 00000000..5479de7b --- /dev/null +++ b/tests/1501-2000/1515. best-position-for-a-service-centre/sol.dart @@ -0,0 +1,41 @@ +class Solution { + double getMinDistSum(List> positions) { + double distSum(double x, double y) { + double sum = 0.0; + for (var p in positions) { + sum += sqrt((x - p[0]) * (x - p[0]) + (y - p[1]) * (y - p[1])); + } + return sum; + } + + double x = 0.0, y = 0.0; + for (var p in positions) { + x += p[0]; + y += p[1]; + } + x /= positions.length; + y /= positions.length; + + double ans = distSum(x, y); + double chg = 100.0; + List> dirs = [[-1, 0], [0, -1], [0, 1], [1, 0]]; + + while (chg > 1e-6) { + bool zoom = true; + for (var d in dirs) { + double xx = x + chg * d[0]; + double yy = y + chg * d[1]; + double dd = distSum(xx, yy); + if (dd < ans) { + ans = dd; + x = xx; + y = yy; + zoom = false; + break; + } + } + if (zoom) chg /= 2; + } + return ans; + } +} diff --git a/tests/1501-2000/1515. best-position-for-a-service-centre/sol.go b/tests/1501-2000/1515. best-position-for-a-service-centre/sol.go new file mode 100644 index 00000000..467cb01a --- /dev/null +++ b/tests/1501-2000/1515. best-position-for-a-service-centre/sol.go @@ -0,0 +1,42 @@ +func getMinDistSum(positions [][]int) float64 { + distSum := func(x, y float64) float64 { + sum := 0.0 + for _, p := range positions { + dx := x - float64(p[0]) + dy := y - float64(p[1]) + sum += math.Sqrt(dx*dx + dy*dy) + } + return sum + } + + x, y := 0.0, 0.0 + for _, p := range positions { + x += float64(p[0]) + y += float64(p[1]) + } + x /= float64(len(positions)) + y /= float64(len(positions)) + + ans := distSum(x, y) + chg := 100.0 + dirs := [][]int{{-1, 0}, {0, -1}, {0, 1}, {1, 0}} + + for chg > 1e-6 { + zoom := true + for _, d := range dirs { + xx := x + chg*float64(d[0]) + yy := y + chg*float64(d[1]) + dd := distSum(xx, yy) + if dd < ans { + ans = dd + x, y = xx, yy + zoom = false + break + } + } + if zoom { + chg /= 2 + } + } + return ans +} diff --git a/tests/1501-2000/1515. best-position-for-a-service-centre/sol.java b/tests/1501-2000/1515. best-position-for-a-service-centre/sol.java new file mode 100644 index 00000000..57fdaaff --- /dev/null +++ b/tests/1501-2000/1515. best-position-for-a-service-centre/sol.java @@ -0,0 +1,41 @@ +class Solution { + public double getMinDistSum(int[][] positions) { + double x = 0.0, y = 0.0; + for (int[] p : positions) { + x += p[0]; + y += p[1]; + } + x /= positions.length; + y /= positions.length; + + double ans = distSum(positions, x, y); + double chg = 100.0; + + while (chg > 1e-6) { + boolean zoom = true; + int[][] dirs = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}}; + for (int[] d : dirs) { + double xx = x + chg * d[0]; + double yy = y + chg * d[1]; + double dd = distSum(positions, xx, yy); + if (dd < ans) { + ans = dd; + x = xx; + y = yy; + zoom = false; + break; + } + } + if (zoom) chg /= 2; + } + return ans; + } + + private double distSum(int[][] positions, double x, double y) { + double sum = 0.0; + for (int[] p : positions) { + sum += Math.sqrt((x - p[0]) * (x - p[0]) + (y - p[1]) * (y - p[1])); + } + return sum; + } +} diff --git a/tests/1501-2000/1515. best-position-for-a-service-centre/sol.kt b/tests/1501-2000/1515. best-position-for-a-service-centre/sol.kt new file mode 100644 index 00000000..19947b53 --- /dev/null +++ b/tests/1501-2000/1515. best-position-for-a-service-centre/sol.kt @@ -0,0 +1,36 @@ +class Solution { + fun getMinDistSum(positions: Array): Double { + fun distSum(x: Double, y: Double): Double { + var sum = 0.0 + for (p in positions) { + sum += Math.sqrt((x - p[0]) * (x - p[0]) + (y - p[1]) * (y - p[1])) + } + return sum + } + + var x = positions.sumOf { it[0].toDouble() } / positions.size + var y = positions.sumOf { it[1].toDouble() } / positions.size + + var ans = distSum(x, y) + var chg = 100.0 + val dirs = arrayOf(intArrayOf(-1, 0), intArrayOf(0, -1), intArrayOf(0, 1), intArrayOf(1, 0)) + + while (chg > 1e-6) { + var zoom = true + for (d in dirs) { + val xx = x + chg * d[0] + val yy = y + chg * d[1] + val dd = distSum(xx, yy) + if (dd < ans) { + ans = dd + x = xx + y = yy + zoom = false + break + } + } + if (zoom) chg /= 2 + } + return ans + } +} diff --git a/tests/1501-2000/1515. best-position-for-a-service-centre/sol.py b/tests/1501-2000/1515. best-position-for-a-service-centre/sol.py new file mode 100644 index 00000000..1e3ba91c --- /dev/null +++ b/tests/1501-2000/1515. best-position-for-a-service-centre/sol.py @@ -0,0 +1,30 @@ +from math import sqrt +from typing import List + + +class Solution: + def getMinDistSum(self, positions: List[List[int]]) -> float: + # euclidean distance + fn = lambda x, y: sum( + sqrt((x - xx) ** 2 + (y - yy) ** 2) for xx, yy in positions + ) + # centroid as starting point + x = sum(x for x, _ in positions) / len(positions) + y = sum(y for _, y in positions) / len(positions) + + ans = fn(x, y) + chg = 100 # change since 0 <= positions[i][0], positions[i][1] <= 100 + while chg > 1e-6: # accuracy within 1e-5 + zoom = True + for dx, dy in (-1, 0), (0, -1), (0, 1), (1, 0): + xx = x + chg * dx + yy = y + chg * dy + dd = fn(xx, yy) + if dd < ans: + ans = dd + x, y = xx, yy + zoom = False + break + if zoom: + chg /= 2 + return ans diff --git a/tests/1501-2000/1515. best-position-for-a-service-centre/sol.py2 b/tests/1501-2000/1515. best-position-for-a-service-centre/sol.py2 new file mode 100644 index 00000000..5cdc994a --- /dev/null +++ b/tests/1501-2000/1515. best-position-for-a-service-centre/sol.py2 @@ -0,0 +1,30 @@ +class Solution(object): + def getMinDistSum(self, positions): + """ + :type positions: List[List[int]] + :rtype: float + """ + from math import sqrt + + def fn(x, y): + return sum(sqrt((x-xx)**2 + (y-yy)**2) for xx, yy in positions) + + x = sum(p[0] for p in positions) / float(len(positions)) + y = sum(p[1] for p in positions) / float(len(positions)) + + ans = fn(x, y) + chg = 100.0 + while chg > 1e-6: + zoom = True + for dx, dy in [(-1, 0), (0, -1), (0, 1), (1, 0)]: + xx = x + chg * dx + yy = y + chg * dy + dd = fn(xx, yy) + if dd < ans: + ans = dd + x, y = xx, yy + zoom = False + break + if zoom: + chg /= 2 + return ans diff --git a/tests/1501-2000/1515. best-position-for-a-service-centre/sol.rb b/tests/1501-2000/1515. best-position-for-a-service-centre/sol.rb new file mode 100644 index 00000000..501a4d4e --- /dev/null +++ b/tests/1501-2000/1515. best-position-for-a-service-centre/sol.rb @@ -0,0 +1,29 @@ +# @param {Integer[][]} positions +# @return {Float} +def get_min_dist_sum(positions) + fn = ->(x, y) { + positions.sum { |xx, yy| Math.sqrt((x - xx)**2 + (y - yy)**2) } + } + + x = positions.sum { |p| p[0] }.to_f / positions.length + y = positions.sum { |p| p[1] }.to_f / positions.length + + ans = fn.call(x, y) + chg = 100.0 + while chg > 1e-6 + zoom = true + [[-1, 0], [0, -1], [0, 1], [1, 0]].each do |dx, dy| + xx = x + chg * dx + yy = y + chg * dy + dd = fn.call(xx, yy) + if dd < ans + ans = dd + x, y = xx, yy + zoom = false + break + end + end + chg /= 2 if zoom + end + ans +end diff --git a/tests/1501-2000/1515. best-position-for-a-service-centre/sol.rs b/tests/1501-2000/1515. best-position-for-a-service-centre/sol.rs new file mode 100644 index 00000000..36a83265 --- /dev/null +++ b/tests/1501-2000/1515. best-position-for-a-service-centre/sol.rs @@ -0,0 +1,39 @@ +impl Solution { + pub fn get_min_dist_sum(positions: Vec>) -> f64 { + fn dist_sum(positions: &Vec>, x: f64, y: f64) -> f64 { + positions.iter().map(|p| { + let dx = x - p[0] as f64; + let dy = y - p[1] as f64; + (dx * dx + dy * dy).sqrt() + }).sum() + } + + let n = positions.len() as f64; + let mut x: f64 = positions.iter().map(|p| p[0] as f64).sum::() / n; + let mut y: f64 = positions.iter().map(|p| p[1] as f64).sum::() / n; + + let mut ans = dist_sum(&positions, x, y); + let mut chg = 100.0f64; + let dirs = [(-1, 0), (0, -1), (0, 1), (1, 0)]; + + while chg > 1e-6 { + let mut zoom = true; + for &(dx, dy) in &dirs { + let xx = x + chg * dx as f64; + let yy = y + chg * dy as f64; + let dd = dist_sum(&positions, xx, yy); + if dd < ans { + ans = dd; + x = xx; + y = yy; + zoom = false; + break; + } + } + if zoom { + chg /= 2.0; + } + } + ans + } +} diff --git a/tests/1501-2000/1515. best-position-for-a-service-centre/sol.swift b/tests/1501-2000/1515. best-position-for-a-service-centre/sol.swift new file mode 100644 index 00000000..1cb21a52 --- /dev/null +++ b/tests/1501-2000/1515. best-position-for-a-service-centre/sol.swift @@ -0,0 +1,43 @@ +class Solution { + func getMinDistSum(_ positions: [[Int]]) -> Double { + func distSum(_ x: Double, _ y: Double) -> Double { + var sum = 0.0 + for p in positions { + let dx = x - Double(p[0]) + let dy = y - Double(p[1]) + sum += sqrt(dx * dx + dy * dy) + } + return sum + } + + var x = 0.0, y = 0.0 + for p in positions { + x += Double(p[0]) + y += Double(p[1]) + } + x /= Double(positions.count) + y /= Double(positions.count) + + var ans = distSum(x, y) + var chg = 100.0 + let dirs = [(-1.0, 0.0), (0.0, -1.0), (0.0, 1.0), (1.0, 0.0)] + + while chg > 1e-6 { + var zoom = true + for (dx, dy) in dirs { + let xx = x + chg * dx + let yy = y + chg * dy + let dd = distSum(xx, yy) + if dd < ans { + ans = dd + x = xx + y = yy + zoom = false + break + } + } + if zoom { chg /= 2 } + } + return ans + } +} diff --git a/tests/1501-2000/1515. best-position-for-a-service-centre/sol.ts b/tests/1501-2000/1515. best-position-for-a-service-centre/sol.ts new file mode 100644 index 00000000..b4bce48a --- /dev/null +++ b/tests/1501-2000/1515. best-position-for-a-service-centre/sol.ts @@ -0,0 +1,45 @@ +function getMinDistSum(positions: number[][]): number { + const distSum = (x: number, y: number): number => { + let sum = 0.0; + for (const [px, py] of positions) { + sum += Math.sqrt((x - px) ** 2 + (y - py) ** 2); + } + return sum; + }; + + let x = 0.0, + y = 0.0; + for (const [px, py] of positions) { + x += px; + y += py; + } + x /= positions.length; + y /= positions.length; + + let ans = distSum(x, y); + let chg = 100.0; + const dirs: [number, number][] = [ + [-1, 0], + [0, -1], + [0, 1], + [1, 0], + ]; + + while (chg > 1e-6) { + let zoom = true; + for (const [dx, dy] of dirs) { + const xx = x + chg * dx; + const yy = y + chg * dy; + const dd = distSum(xx, yy); + if (dd < ans) { + ans = dd; + x = xx; + y = yy; + zoom = false; + break; + } + } + if (zoom) chg /= 2; + } + return ans; +} diff --git a/tests/1501-2000/1518. water-bottles/manifest.yaml b/tests/1501-2000/1518. water-bottles/manifest.yaml new file mode 100644 index 00000000..78b2503b --- /dev/null +++ b/tests/1501-2000/1518. water-bottles/manifest.yaml @@ -0,0 +1,209 @@ +entry: + id: 1518 + title: "water-bottles" + params: + numBottles: + type: int + numExchange: + type: int + call: + cpp: "Solution().numWaterBottles({numBottles}, {numExchange})" + rust: "Solution::num_water_bottles({numBottles}, {numExchange})" + python3: "Solution().numWaterBottles({numBottles}, {numExchange})" + python2: "Solution().numWaterBottles({numBottles}, {numExchange})" + ruby: "num_water_bottles({numBottles}, {numExchange})" + java: "new Solution().numWaterBottles({numBottles}, {numExchange})" + csharp: "new Solution().NumWaterBottles({numBottles}, {numExchange})" + kotlin: "Solution().numWaterBottles({numBottles}, {numExchange})" + go: "numWaterBottles({numBottles}, {numExchange})" + dart: "Solution().numWaterBottles({numBottles}, {numExchange})" + swift: "Solution().numWaterBottles({numBottles}, {numExchange})" + typescript: "numWaterBottles({numBottles}, {numExchange})" +judge: + type: "exact" +limits: + time_ms: 500 + memory_mb: 128 +oracle: + python3: + call: "Checker().numWaterBottles(numBottles, numExchange, {result})" + checker: | + class Checker: + def numWaterBottles(self, numBottles, numExchange, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + return result == numBottles + (numBottles - 1) // (numExchange - 1) +seed: 1518 +tests: + - name: "example one" + in: + numBottles: 9 + numExchange: 3 + out: 13 + - name: "example two" + in: + numBottles: 15 + numExchange: 4 + out: 19 + - name: "one bottle" + in: + numBottles: 1 + numExchange: 2 + - name: "two bottles exchange two" + in: + numBottles: 2 + numExchange: 2 + - name: "three bottles exchange two" + in: + numBottles: 3 + numExchange: 2 + - name: "four bottles exchange two" + in: + numBottles: 4 + numExchange: 2 + - name: "five bottles exchange two" + in: + numBottles: 5 + numExchange: 2 + - name: "six bottles exchange two" + in: + numBottles: 6 + numExchange: 2 + - name: "seven bottles exchange three" + in: + numBottles: 7 + numExchange: 3 + - name: "eight bottles exchange three" + in: + numBottles: 8 + numExchange: 3 + - name: "ten bottles exchange three" + in: + numBottles: 10 + numExchange: 3 + - name: "eleven bottles exchange three" + in: + numBottles: 11 + numExchange: 3 + - name: "twelve bottles exchange four" + in: + numBottles: 12 + numExchange: 4 + - name: "thirteen bottles exchange four" + in: + numBottles: 13 + numExchange: 4 + - name: "sixteen bottles exchange four" + in: + numBottles: 16 + numExchange: 4 + - name: "twenty bottles exchange five" + in: + numBottles: 20 + numExchange: 5 + - name: "twenty one exchange five" + in: + numBottles: 21 + numExchange: 5 + - name: "twenty five exchange six" + in: + numBottles: 25 + numExchange: 6 + - name: "thirty exchange two" + in: + numBottles: 30 + numExchange: 2 + - name: "thirty exchange ten" + in: + numBottles: 30 + numExchange: 10 + - name: "thirty seven exchange seven" + in: + numBottles: 37 + numExchange: 7 + - name: "forty exchange three" + in: + numBottles: 40 + numExchange: 3 + - name: "forty four exchange eleven" + in: + numBottles: 44 + numExchange: 11 + - name: "fifty exchange two" + in: + numBottles: 50 + numExchange: 2 + - name: "fifty exchange fifty" + in: + numBottles: 50 + numExchange: 50 + - name: "sixty exchange four" + in: + numBottles: 60 + numExchange: 4 + - name: "sixty three exchange eight" + in: + numBottles: 63 + numExchange: 8 + - name: "seventy exchange nine" + in: + numBottles: 70 + numExchange: 9 + - name: "seventy five exchange twenty five" + in: + numBottles: 75 + numExchange: 25 + - name: "eighty exchange two" + in: + numBottles: 80 + numExchange: 2 + - name: "eighty eight exchange twelve" + in: + numBottles: 88 + numExchange: 12 + - name: "ninety exchange ten" + in: + numBottles: 90 + numExchange: 10 + - name: "ninety nine exchange one hundred" + in: + numBottles: 99 + numExchange: 100 + - name: "maximum bottles minimum exchange" + in: + numBottles: 100 + numExchange: 2 + - name: "maximum bottles maximum exchange" + in: + numBottles: 100 + numExchange: 100 + - name: "two bottles maximum exchange" + in: + numBottles: 2 + numExchange: 100 + out: 2 + - name: "ninety eight exchange three" + in: + numBottles: 98 + numExchange: 3 + out: 146 + - name: "maximum bottles exchange three" + in: + numBottles: 100 + numExchange: 3 + out: 149 + - name: "maximum bottles exchange four" + in: + numBottles: 100 + numExchange: 4 + out: 133 + - name: "generated midrange" + in: + numBottles: + gen: "int" + min: 1 + max: 100 + numExchange: + gen: "int" + min: 2 + max: 100 diff --git a/tests/1501-2000/1518. water-bottles/sol.cpp b/tests/1501-2000/1518. water-bottles/sol.cpp new file mode 100644 index 00000000..432eae3a --- /dev/null +++ b/tests/1501-2000/1518. water-bottles/sol.cpp @@ -0,0 +1,6 @@ +class Solution { +public: + int numWaterBottles(int numBottles, int numExchange) { + return numBottles + (numBottles - 1) / (numExchange - 1); + } +}; diff --git a/tests/1501-2000/1518. water-bottles/sol.cs b/tests/1501-2000/1518. water-bottles/sol.cs new file mode 100644 index 00000000..e1dd9d59 --- /dev/null +++ b/tests/1501-2000/1518. water-bottles/sol.cs @@ -0,0 +1,5 @@ +public class Solution { + public int NumWaterBottles(int numBottles, int numExchange) { + return numBottles + (numBottles - 1) / (numExchange - 1); + } +} diff --git a/tests/1501-2000/1518. water-bottles/sol.dart b/tests/1501-2000/1518. water-bottles/sol.dart new file mode 100644 index 00000000..ff725101 --- /dev/null +++ b/tests/1501-2000/1518. water-bottles/sol.dart @@ -0,0 +1,5 @@ +class Solution { + int numWaterBottles(int numBottles, int numExchange) { + return numBottles + (numBottles - 1) ~/ (numExchange - 1); + } +} diff --git a/tests/1501-2000/1518. water-bottles/sol.go b/tests/1501-2000/1518. water-bottles/sol.go new file mode 100644 index 00000000..e3181df9 --- /dev/null +++ b/tests/1501-2000/1518. water-bottles/sol.go @@ -0,0 +1,3 @@ +func numWaterBottles(numBottles int, numExchange int) int { + return numBottles + (numBottles - 1) / (numExchange - 1) +} diff --git a/tests/1501-2000/1518. water-bottles/sol.java b/tests/1501-2000/1518. water-bottles/sol.java new file mode 100644 index 00000000..31619e17 --- /dev/null +++ b/tests/1501-2000/1518. water-bottles/sol.java @@ -0,0 +1,5 @@ +class Solution { + public int numWaterBottles(int numBottles, int numExchange) { + return numBottles + (numBottles - 1) / (numExchange - 1); + } +} diff --git a/tests/1501-2000/1518. water-bottles/sol.kt b/tests/1501-2000/1518. water-bottles/sol.kt new file mode 100644 index 00000000..e7900ed5 --- /dev/null +++ b/tests/1501-2000/1518. water-bottles/sol.kt @@ -0,0 +1,5 @@ +class Solution { + fun numWaterBottles(numBottles: Int, numExchange: Int): Int { + return numBottles + (numBottles - 1) / (numExchange - 1) + } +} diff --git a/tests/1501-2000/1518. water-bottles/sol.py b/tests/1501-2000/1518. water-bottles/sol.py new file mode 100644 index 00000000..59d834e2 --- /dev/null +++ b/tests/1501-2000/1518. water-bottles/sol.py @@ -0,0 +1,3 @@ +class Solution: + def numWaterBottles(self, numBottles: int, numExchange: int) -> int: + return numBottles + (numBottles - 1) // (numExchange - 1) diff --git a/tests/1501-2000/1518. water-bottles/sol.py2 b/tests/1501-2000/1518. water-bottles/sol.py2 new file mode 100644 index 00000000..de32b79e --- /dev/null +++ b/tests/1501-2000/1518. water-bottles/sol.py2 @@ -0,0 +1,8 @@ +class Solution(object): + def numWaterBottles(self, numBottles, numExchange): + """ + :type numBottles: int + :type numExchange: int + :rtype: int + """ + return numBottles + (numBottles - 1) // (numExchange - 1) diff --git a/tests/1501-2000/1518. water-bottles/sol.rb b/tests/1501-2000/1518. water-bottles/sol.rb new file mode 100644 index 00000000..bfb3cb12 --- /dev/null +++ b/tests/1501-2000/1518. water-bottles/sol.rb @@ -0,0 +1,6 @@ +# @param {Integer} num_bottles +# @param {Integer} num_exchange +# @return {Integer} +def num_water_bottles(num_bottles, num_exchange) + num_bottles + (num_bottles - 1) / (num_exchange - 1) +end diff --git a/tests/1501-2000/1518. water-bottles/sol.rs b/tests/1501-2000/1518. water-bottles/sol.rs new file mode 100644 index 00000000..dd7b143c --- /dev/null +++ b/tests/1501-2000/1518. water-bottles/sol.rs @@ -0,0 +1,5 @@ +impl Solution { + pub fn num_water_bottles(num_bottles: i32, num_exchange: i32) -> i32 { + num_bottles + (num_bottles - 1) / (num_exchange - 1) + } +} diff --git a/tests/1501-2000/1518. water-bottles/sol.swift b/tests/1501-2000/1518. water-bottles/sol.swift new file mode 100644 index 00000000..173db75e --- /dev/null +++ b/tests/1501-2000/1518. water-bottles/sol.swift @@ -0,0 +1,5 @@ +class Solution { + func numWaterBottles(_ numBottles: Int, _ numExchange: Int) -> Int { + return numBottles + (numBottles - 1) / (numExchange - 1) + } +} diff --git a/tests/1501-2000/1518. water-bottles/sol.ts b/tests/1501-2000/1518. water-bottles/sol.ts new file mode 100644 index 00000000..2ffa7d97 --- /dev/null +++ b/tests/1501-2000/1518. water-bottles/sol.ts @@ -0,0 +1,3 @@ +function numWaterBottles(numBottles: number, numExchange: number): number { + return numBottles + Math.floor((numBottles - 1) / (numExchange - 1)); +} diff --git a/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/manifest.yaml b/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/manifest.yaml new file mode 100644 index 00000000..48d3684f --- /dev/null +++ b/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/manifest.yaml @@ -0,0 +1,728 @@ +entry: + id: 1519 + title: "number-of-nodes-in-the-sub-tree-with-the-same-label" + params: + n: + type: int + edges: + type: array + items: + type: array + items: + type: int + labels: + type: string + call: + cpp: "Solution().countSubTrees({n}, {edges}, {labels})" + rust: "Solution::count_sub_trees({n}, {edges}, {labels})" + python3: "Solution().countSubTrees({n}, {edges}, {labels})" + python2: "Solution().countSubTrees({n}, {edges}, {labels})" + ruby: "count_sub_trees({n}, {edges}, {labels})" + java: "new Solution().countSubTrees({n}, {edges}, {labels})" + csharp: "new Solution().CountSubTrees({n}, {edges}, {labels})" + kotlin: "Solution().countSubTrees({n}, {edges}, {labels})" + go: "countSubTrees({n}, {edges}, {labels})" + dart: "Solution().countSubTrees({n}, {edges}, {labels})" + swift: "Solution().countSubTrees({n}, {edges}, {labels})" + typescript: "countSubTrees({n}, {edges}, {labels})" + +judge: + type: "exact" + +limits: + time_ms: 4000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().countSubTrees(n, edges, labels, {result})" + checker: | + class Checker: + def countSubTrees(self, n, edges, labels, result): + graph = [[] for _ in range(n)] + for a, b in edges: + graph[a].append(b) + graph[b].append(a) + expected = [0] * n + def dfs(node, parent): + counts = [0] * 26 + counts[ord(labels[node]) - 97] = 1 + for child in graph[node]: + if child != parent: + child_counts = dfs(child, node) + for i in range(26): + counts[i] += child_counts[i] + expected[node] = counts[ord(labels[node]) - 97] + return counts + dfs(0, -1) + return result == expected + +seed: 1519 + +tests: + - name: "example_one" + in: + n: 7 + edges: + - [0, 1] + - [0, 2] + - [1, 4] + - [1, 5] + - [2, 3] + - [2, 6] + labels: "abaedcd" + out: [2, 1, 1, 1, 1, 1, 1] + - name: "example_two" + in: + n: 4 + edges: + - [0, 1] + - [1, 2] + - [0, 3] + labels: "bbbb" + out: [4, 2, 1, 1] + - name: "example_three" + in: + n: 5 + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [0, 4] + labels: "aabab" + out: [3, 2, 1, 1, 1] + - name: "singleton" + in: + n: 1 + edges: [] + labels: "z" + - name: "two_same" + in: + n: 2 + edges: + - [0, 1] + labels: "aa" + - name: "two_different" + in: + n: 2 + edges: + - [0, 1] + labels: "ab" + - name: "chain_three_same" + in: + n: 3 + edges: + - [0, 1] + - [1, 2] + labels: "aaa" + - name: "chain_three_distinct" + in: + n: 3 + edges: + - [0, 1] + - [1, 2] + labels: "abc" + - name: "star_four_same" + in: + n: 4 + edges: + - [0, 1] + - [0, 2] + - [0, 3] + labels: "aaaa" + - name: "star_four_unique" + in: + n: 4 + edges: + - [0, 1] + - [0, 2] + - [0, 3] + labels: "abcd" + - name: "chain_five_alternating" + in: + n: 5 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + labels: "ababa" + - name: "chain_six_blocks" + in: + n: 6 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + labels: "aabbaa" + - name: "balanced_seven_same" + in: + n: 7 + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [2, 6] + labels: "aaaaaaa" + - name: "balanced_seven_unique" + in: + n: 7 + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [2, 6] + labels: "abcdefg" + - name: "balanced_seven_repeated" + in: + n: 7 + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [2, 6] + labels: "abacaba" + - name: "star_eight_center_match" + in: + n: 8 + edges: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [0, 5] + - [0, 6] + - [0, 7] + labels: "abacadae" + - name: "star_eight_all_same" + in: + n: 8 + edges: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [0, 5] + - [0, 6] + - [0, 7] + labels: "aaaaaaaa" + - name: "chain_ten_periodic" + in: + n: 10 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + labels: "abcabcabca" + - name: "chain_twelve_two_labels" + in: + n: 12 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + - [10, 11] + labels: "abababababab" + - name: "branching_ten" + in: + n: 10 + edges: + - [0, 1] + - [0, 2] + - [0, 3] + - [1, 4] + - [1, 5] + - [2, 6] + - [2, 7] + - [3, 8] + - [8, 9] + labels: "aabbacacaa" + - name: "mixed_twelve" + in: + n: 12 + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [2, 6] + - [5, 7] + - [5, 8] + - [6, 9] + - [9, 10] + - [9, 11] + labels: "abacabadabca" + - name: "chain_twenty_same" + 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] + labels: "aaaaaaaaaaaaaaaaaaaa" + - name: "chain_twenty_unique_cycle" + 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] + labels: "abcdefghijklmnopqrst" + - name: "binary_fifteen_repeated" + in: + n: 15 + 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] + labels: "abbacabbaacabab" + - name: "wide_fifteen" + in: + n: 15 + 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] + labels: "aabbccddeeffggg" + - name: "deep_twenty_five" + in: + n: 25 + 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] + labels: "abcdefghijklmnopqrstuvwxy" + - name: "large_chain_thirty" + in: + n: 30 + 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] + labels: "abcdefghijklmnopqrstuvwxyzabcd" + - name: "large_star_thirty" + in: + n: 30 + 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] + - [0, 20] + - [0, 21] + - [0, 22] + - [0, 23] + - [0, 24] + - [0, 25] + - [0, 26] + - [0, 27] + - [0, 28] + - [0, 29] + labels: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + - name: "forked_six" + in: + n: 6 + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [1, 4] + - [2, 5] + labels: "aabaca" + - name: "two_level_eight" + in: + n: 8 + edges: + - [0, 1] + - [0, 2] + - [0, 3] + - [1, 4] + - [1, 5] + - [2, 6] + - [3, 7] + labels: "abacbcaa" + - name: "chain_eleven_three_labels" + in: + n: 11 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + labels: "abcabcabcab" + - name: "balanced_fifteen_same_leaves" + in: + n: 15 + 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] + labels: "abcdefghijklmno" + - name: "long_branch_twenty_four" + in: + n: 24 + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [2, 10] + - [10, 11] + - [11, 12] + - [12, 13] + - [13, 14] + - [14, 15] + - [15, 16] + - [16, 17] + - [2, 18] + - [18, 19] + - [19, 20] + - [20, 21] + - [21, 22] + - [22, 23] + labels: "abcdefghijklmnopqrstuvwx" + - name: "star_twelve_two_groups" + in: + n: 12 + edges: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [0, 5] + - [0, 6] + - [0, 7] + - [0, 8] + - [0, 9] + - [0, 10] + - [0, 11] + labels: "abababababab" + - name: "asymmetric_nine" + in: + n: 9 + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [3, 4] + - [2, 5] + - [5, 6] + - [6, 7] + - [2, 8] + labels: "aabbacaba" + - name: "balanced_thirty_one_mixed" + in: + n: 31 + 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] + labels: "abacabadabacabaeabacabadabacaba" + - name: "wide_twenty_six_alphabet" + in: + n: 26 + 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] + - [0, 20] + - [0, 21] + - [0, 22] + - [0, 23] + - [0, 24] + - [0, 25] + labels: "abcdefghijklmnopqrstuvwxyz" + - name: "three_arms_twenty_one" + in: + n: 21 + edges: + - [0, 1] + - [0, 2] + - [0, 3] + - [1, 4] + - [4, 5] + - [5, 6] + - [2, 7] + - [7, 8] + - [8, 9] + - [9, 10] + - [3, 11] + - [3, 12] + - [12, 13] + - [13, 14] + - [14, 15] + - [15, 16] + - [16, 17] + - [17, 18] + - [18, 19] + - [19, 20] + labels: "aabacabaacabaabbacaba" + - name: "two_branch_forty" + in: + n: 40 + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [2, 4] + - [3, 5] + - [4, 6] + - [5, 7] + - [6, 8] + - [7, 9] + - [8, 10] + - [9, 11] + - [10, 12] + - [11, 13] + - [12, 14] + - [13, 15] + - [14, 16] + - [15, 17] + - [16, 18] + - [17, 19] + - [18, 20] + - [19, 21] + - [20, 22] + - [21, 23] + - [22, 24] + - [23, 25] + - [24, 26] + - [25, 27] + - [26, 28] + - [27, 29] + - [28, 30] + - [29, 31] + - [30, 32] + - [31, 33] + - [32, 34] + - [33, 35] + - [34, 36] + - [35, 37] + - [36, 38] + - [37, 39] + labels: "abcdefghijklmnopqrstuvwxyzabcdefghijklmn" + - name: "root_and_subtree_label_runs" + in: + n: 18 + 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] + - [8, 16] + - [9, 17] + labels: "aabbbacccabbbacaca" diff --git a/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.cpp b/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.cpp new file mode 100644 index 00000000..6e4b74d1 --- /dev/null +++ b/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + vector countSubTrees(int n, vector>& edges, string labels) { + vector> matrix(n); + for (auto& edge : edges) { + int u = edge[0], v = edge[1]; + matrix[u].push_back(v); + matrix[v].push_back(u); + } + + vector parent(n, -1); + vector order = {0}; + for (int i = 0; i < order.size(); i++) { + int node = order[i]; + for (int child : matrix[node]) { + if (child != parent[node]) { + parent[child] = node; + order.push_back(child); + } + } + } + + vector> counts(n, vector(26, 0)); + vector ans(n); + for (int i = n - 1; i >= 0; i--) { + int node = order[i]; + int label = labels[node] - 'a'; + counts[node][label]++; + ans[node] = counts[node][label]; + if (parent[node] != -1) { + for (int j = 0; j < 26; j++) { + counts[parent[node]][j] += counts[node][j]; + } + } + } + return ans; + } +}; diff --git a/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.cs b/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.cs new file mode 100644 index 00000000..259cdb56 --- /dev/null +++ b/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.cs @@ -0,0 +1,44 @@ +public class Solution { + public int[] CountSubTrees(int n, int[][] edges, string labels) { + var matrix = new List[n]; + for (int i = 0; i < n; i++) { + matrix[i] = new List(); + } + foreach (var edge in edges) { + int u = edge[0], v = edge[1]; + matrix[u].Add(v); + matrix[v].Add(u); + } + + var parent = new int[n]; + Array.Fill(parent, -1); + var order = new List { 0 }; + for (int i = 0; i < order.Count; i++) { + int node = order[i]; + foreach (int child in matrix[node]) { + if (child != parent[node]) { + parent[child] = node; + order.Add(child); + } + } + } + + var counts = new int[n][]; + for (int i = 0; i < n; i++) { + counts[i] = new int[26]; + } + var ans = new int[n]; + for (int i = n - 1; i >= 0; i--) { + int node = order[i]; + int label = labels[node] - 'a'; + counts[node][label]++; + ans[node] = counts[node][label]; + if (parent[node] != -1) { + for (int j = 0; j < 26; j++) { + counts[parent[node]][j] += counts[node][j]; + } + } + } + return ans; + } +} diff --git a/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.dart b/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.dart new file mode 100644 index 00000000..f2e21769 --- /dev/null +++ b/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.dart @@ -0,0 +1,37 @@ +class Solution { + List countSubTrees(int n, List> edges, String labels) { + var matrix = List.generate(n, (_) => []); + for (var edge in edges) { + int u = edge[0], v = edge[1]; + matrix[u].add(v); + matrix[v].add(u); + } + + var parent = List.filled(n, -1); + var order = [0]; + for (int i = 0; i < order.length; i++) { + int node = order[i]; + for (int child in matrix[node]) { + if (child != parent[node]) { + parent[child] = node; + order.add(child); + } + } + } + + var counts = List.generate(n, (_) => List.filled(26, 0)); + var ans = List.filled(n, 0); + for (int i = order.length - 1; i >= 0; i--) { + int node = order[i]; + int label = labels.codeUnitAt(node) - 97; + counts[node][label]++; + ans[node] = counts[node][label]; + if (parent[node] != -1) { + for (int j = 0; j < 26; j++) { + counts[parent[node]][j] += counts[node][j]; + } + } + } + return ans; + } +} diff --git a/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.go b/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.go new file mode 100644 index 00000000..a93bfaa6 --- /dev/null +++ b/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.go @@ -0,0 +1,41 @@ +func countSubTrees(n int, edges [][]int, labels string) []int { + matrix := make([][]int, n) + for i := 0; i < n; i++ { + matrix[i] = []int{} + } + for _, edge := range edges { + u, v := edge[0], edge[1] + matrix[u] = append(matrix[u], v) + matrix[v] = append(matrix[v], u) + } + + parent := make([]int, n) + for i := range parent { + parent[i] = -1 + } + order := []int{0} + for i := 0; i < len(order); i++ { + node := order[i] + for _, child := range matrix[node] { + if child != parent[node] { + parent[child] = node + order = append(order, child) + } + } + } + + counts := make([][26]int, n) + ans := make([]int, n) + for i := len(order) - 1; i >= 0; i-- { + node := order[i] + label := labels[node] - 'a' + counts[node][label]++ + ans[node] = counts[node][label] + if parent[node] != -1 { + for j := 0; j < 26; j++ { + counts[parent[node]][j] += counts[node][j] + } + } + } + return ans +} diff --git a/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.java b/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.java new file mode 100644 index 00000000..b3968bff --- /dev/null +++ b/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.java @@ -0,0 +1,42 @@ +class Solution { + public int[] countSubTrees(int n, int[][] edges, String labels) { + java.util.List> matrix = new java.util.ArrayList<>(); + for (int i = 0; i < n; i++) { + matrix.add(new java.util.ArrayList<>()); + } + for (int[] edge : edges) { + int u = edge[0], v = edge[1]; + matrix.get(u).add(v); + matrix.get(v).add(u); + } + + int[] parent = new int[n]; + java.util.Arrays.fill(parent, -1); + java.util.List order = new java.util.ArrayList<>(); + order.add(0); + for (int i = 0; i < order.size(); i++) { + int node = order.get(i); + for (int child : matrix.get(node)) { + if (child != parent[node]) { + parent[child] = node; + order.add(child); + } + } + } + + int[][] counts = new int[n][26]; + int[] ans = new int[n]; + for (int i = order.size() - 1; i >= 0; i--) { + int node = order.get(i); + int label = labels.charAt(node) - 'a'; + counts[node][label]++; + ans[node] = counts[node][label]; + if (parent[node] != -1) { + for (int j = 0; j < 26; j++) { + counts[parent[node]][j] += counts[node][j]; + } + } + } + return ans; + } +} diff --git a/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.kt b/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.kt new file mode 100644 index 00000000..053f6a75 --- /dev/null +++ b/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.kt @@ -0,0 +1,38 @@ +class Solution { + fun countSubTrees(n: Int, edges: Array, labels: String): IntArray { + val matrix = Array(n) { mutableListOf() } + for ((u, v) in edges) { + matrix[u].add(v) + matrix[v].add(u) + } + + val parent = IntArray(n) { -1 } + val order = mutableListOf(0) + var idx = 0 + while (idx < order.size) { + val node = order[idx] + for (child in matrix[node]) { + if (child != parent[node]) { + parent[child] = node + order.add(child) + } + } + idx++ + } + + val counts = Array(n) { IntArray(26) } + val ans = IntArray(n) + for (i in order.size - 1 downTo 0) { + val node = order[i] + val label = labels[node] - 'a' + counts[node][label]++ + ans[node] = counts[node][label] + if (parent[node] != -1) { + for (j in 0 until 26) { + counts[parent[node]][j] += counts[node][j] + } + } + } + return ans + } +} diff --git a/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.py b/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.py new file mode 100644 index 00000000..bb828761 --- /dev/null +++ b/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.py @@ -0,0 +1,29 @@ +from typing import List + + +class Solution: + def countSubTrees(self, n: int, edges: List[List[int]], labels: str) -> List[int]: + matrix = [[] for _ in range(n)] + + for u, v in edges: + matrix[u].append(v) + matrix[v].append(u) + + parent = [-1] * n + order = [0] + for node in order: + for child in matrix[node]: + if child != parent[node]: + parent[child] = node + order.append(child) + + counts = [[0] * 26 for _ in range(n)] + ans = [0] * n + for node in reversed(order): + label = ord(labels[node]) - 97 + counts[node][label] += 1 + ans[node] = counts[node][label] + if parent[node] != -1: + for i in range(26): + counts[parent[node]][i] += counts[node][i] + return ans diff --git a/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.py2 b/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.py2 new file mode 100644 index 00000000..6f716d85 --- /dev/null +++ b/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.py2 @@ -0,0 +1,31 @@ +class Solution(object): + def countSubTrees(self, n, edges, labels): + """ + :type n: int + :type edges: List[List[int]] + :type labels: str + :rtype: List[int] + """ + matrix = [[] for _ in range(n)] + for u, v in edges: + matrix[u].append(v) + matrix[v].append(u) + + parent = [-1] * n + order = [0] + for node in order: + for child in matrix[node]: + if child != parent[node]: + parent[child] = node + order.append(child) + + counts = [[0] * 26 for _ in range(n)] + ans = [0] * n + for node in reversed(order): + label = ord(labels[node]) - 97 + counts[node][label] += 1 + ans[node] = counts[node][label] + if parent[node] != -1: + for i in range(26): + counts[parent[node]][i] += counts[node][i] + return ans diff --git a/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.rb b/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.rb new file mode 100644 index 00000000..184c34d2 --- /dev/null +++ b/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.rb @@ -0,0 +1,36 @@ +# @param {Integer} n +# @param {Integer[][]} edges +# @param {String} labels +# @return {Integer[]} +def count_sub_trees(n, edges, labels) + matrix = Array.new(n) { [] } + edges.each do |u, v| + matrix[u] << v + matrix[v] << u + end + + parent = Array.new(n, -1) + order = [0] + order.each do |node| + matrix[node].each do |child| + if child != parent[node] + parent[child] = node + order << child + end + end + end + + counts = Array.new(n) { Array.new(26, 0) } + ans = Array.new(n, 0) + order.reverse_each do |node| + label = labels[node].ord - 97 + counts[node][label] += 1 + ans[node] = counts[node][label] + if parent[node] != -1 + 26.times do |i| + counts[parent[node]][i] += counts[node][i] + end + end + end + ans +end diff --git a/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.rs b/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.rs new file mode 100644 index 00000000..13fe2991 --- /dev/null +++ b/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.rs @@ -0,0 +1,43 @@ +impl Solution { + pub fn count_sub_trees(n: i32, edges: Vec>, labels: String) -> Vec { + let n = n as usize; + let mut matrix = vec![vec![]; n]; + for edge in &edges { + let u = edge[0] as usize; + let v = edge[1] as usize; + matrix[u].push(v); + matrix[v].push(u); + } + + let mut parent = vec![-1; n]; + let mut order = vec![0]; + let mut idx = 0; + while idx < order.len() { + let node = order[idx]; + for &child in &matrix[node] { + if child as i32 != parent[node] { + parent[child] = node as i32; + order.push(child); + } + } + idx += 1; + } + + let mut counts = vec![[0; 26]; n]; + let mut ans = vec![0; n]; + let labels_bytes = labels.as_bytes(); + for &node in order.iter().rev() { + let label = (labels_bytes[node] - b'a') as usize; + counts[node][label] += 1; + ans[node] = counts[node][label]; + let p = parent[node]; + if p != -1 { + let p = p as usize; + for i in 0..26 { + counts[p][i] += counts[node][i]; + } + } + } + ans + } +} diff --git a/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.swift b/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.swift new file mode 100644 index 00000000..0eb84317 --- /dev/null +++ b/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.swift @@ -0,0 +1,39 @@ +class Solution { + func countSubTrees(_ n: Int, _ edges: [[Int]], _ labels: String) -> [Int] { + var matrix = [[Int]](repeating: [], count: n) + for edge in edges { + let u = edge[0], v = edge[1] + matrix[u].append(v) + matrix[v].append(u) + } + + var parent = [Int](repeating: -1, count: n) + var order = [0] + var idx = 0 + while idx < order.count { + let node = order[idx] + for child in matrix[node] { + if child != parent[node] { + parent[child] = node + order.append(child) + } + } + idx += 1 + } + + var counts = [[Int]](repeating: [Int](repeating: 0, count: 26), count: n) + var ans = [Int](repeating: 0, count: n) + let labelChars = Array(labels) + for node in order.reversed() { + let label = Int(labelChars[node].asciiValue! - 97) + counts[node][label] += 1 + ans[node] = counts[node][label] + if parent[node] != -1 { + for i in 0..<26 { + counts[parent[node]][i] += counts[node][i] + } + } + } + return ans + } +} diff --git a/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.ts b/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.ts new file mode 100644 index 00000000..39cb0760 --- /dev/null +++ b/tests/1501-2000/1519. number-of-nodes-in-the-sub-tree-with-the-same-label/sol.ts @@ -0,0 +1,36 @@ +function countSubTrees(n: number, edges: number[][], labels: string): number[] { + const matrix: number[][] = Array.from({ length: n }, () => []); + for (const [u, v] of edges) { + matrix[u].push(v); + matrix[v].push(u); + } + + const parent: number[] = new Array(n).fill(-1); + const order: number[] = [0]; + for (let i = 0; i < order.length; i++) { + const node = order[i]; + for (const child of matrix[node]) { + if (child !== parent[node]) { + parent[child] = node; + order.push(child); + } + } + } + + const counts: number[][] = Array.from({ length: n }, () => + new Array(26).fill(0), + ); + const ans: number[] = new Array(n).fill(0); + for (let i = order.length - 1; i >= 0; i--) { + const node = order[i]; + const label = labels.charCodeAt(node) - 97; + counts[node][label]++; + ans[node] = counts[node][label]; + if (parent[node] !== -1) { + for (let j = 0; j < 26; j++) { + counts[parent[node]][j] += counts[node][j]; + } + } + } + return ans; +}